Skip to main content

khive_graph_diff/
lib.rs

1//! Deterministic, I/O-free graph-state differences (ADR-101 D5).
2//!
3//! Callers load three substrate-labelled NDJSON streams. This crate validates
4//! record identities, then compares supplied fields without domain defaults or
5//! schema interpretation. Nested JSON values change as whole top-level fields.
6
7use std::collections::{BTreeMap, BTreeSet};
8
9pub use khive_types::Id128;
10use serde::Serialize;
11use serde_json::Value;
12
13mod parse;
14pub use parse::DiffInputError;
15
16/// Independently keyed record collections; equal IDs across substrates coexist.
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
18#[serde(rename_all = "snake_case")]
19pub enum Substrate {
20    Entity,
21    Edge,
22    Note,
23}
24
25impl Substrate {
26    /// Identity field in the existing NDJSON representation.
27    pub const fn identity_field(self) -> &'static str {
28        match self {
29            Self::Entity | Self::Note => "id",
30            Self::Edge => "edge_id",
31        }
32    }
33}
34
35impl std::fmt::Display for Substrate {
36    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
37        f.write_str(match self {
38            Self::Entity => "entity",
39            Self::Edge => "edge",
40            Self::Note => "note",
41        })
42    }
43}
44
45/// Supplied fields other than the substrate's extracted identity.
46pub type Fields = BTreeMap<String, Value>;
47type Records = BTreeMap<Id128, Fields>;
48
49/// Validated, privately held graph state. Construction performs no I/O.
50#[derive(Debug, Clone, Default, PartialEq, Eq)]
51pub struct GraphState {
52    entities: Records,
53    edges: Records,
54    notes: Records,
55}
56
57impl GraphState {
58    /// Parse already-loaded NDJSON. Empty/blank lines are ignored; errors carry
59    /// one-based physical line numbers. Duplicate IDs within a substrate refuse.
60    ///
61    /// Entity/note IDs use `id`; edge IDs use `edge_id`. All other fields are
62    /// retained, including unknown kinds/properties and explicitly null values.
63    pub fn from_ndjson(entities: &str, edges: &str, notes: &str) -> Result<Self, DiffInputError> {
64        Ok(Self {
65            entities: parse::records(entities, Substrate::Entity)?,
66            edges: parse::records(edges, Substrate::Edge)?,
67            notes: parse::records(notes, Substrate::Note)?,
68        })
69    }
70}
71
72/// A complete added/removed record, with its identity represented exactly once.
73#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
74pub struct Record {
75    pub id: Id128,
76    pub fields: Fields,
77}
78
79/// One changed top-level field. Missing sides are omitted during serialization;
80/// present JSON null is serialized explicitly. These DTOs are Serialize-only:
81/// ordinary `Option<Value>` deserialization would conflate missing and null.
82#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
83pub struct FieldChange {
84    pub field: String,
85    #[serde(skip_serializing_if = "Option::is_none")]
86    pub before: Option<Value>,
87    #[serde(skip_serializing_if = "Option::is_none")]
88    pub after: Option<Value>,
89}
90
91/// A record whose supplied fields changed, ordered lexicographically by field.
92#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
93pub struct ModifiedRecord {
94    pub id: Id128,
95    pub changes: Vec<FieldChange>,
96}
97
98/// Additions, removals and changes, each ordered by UUID ascending.
99#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
100pub struct SubstrateDiff {
101    pub added: Vec<Record>,
102    pub removed: Vec<Record>,
103    pub modified: Vec<ModifiedRecord>,
104}
105
106impl SubstrateDiff {
107    pub fn is_empty(&self) -> bool {
108        self.added.is_empty() && self.removed.is_empty() && self.modified.is_empty()
109    }
110}
111
112/// Structured diff over three independent substrate collections.
113#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
114pub struct GraphDiff {
115    pub entities: SubstrateDiff,
116    pub edges: SubstrateDiff,
117    pub notes: SubstrateDiff,
118}
119
120impl GraphDiff {
121    pub fn is_empty(&self) -> bool {
122        self.entities.is_empty() && self.edges.is_empty() && self.notes.is_empty()
123    }
124}
125
126/// Compare validated graph states without mutation, I/O, time or randomness.
127///
128/// Identity aliases are normalized during parsing. Arrays remain ordered and
129/// nested objects compare by their complete typed JSON value. No supplied
130/// non-identity field is ignored or filled in from a runtime default.
131pub fn diff(before: &GraphState, after: &GraphState) -> GraphDiff {
132    GraphDiff {
133        entities: diff_records(&before.entities, &after.entities),
134        edges: diff_records(&before.edges, &after.edges),
135        notes: diff_records(&before.notes, &after.notes),
136    }
137}
138
139fn diff_records(before: &Records, after: &Records) -> SubstrateDiff {
140    let mut result = SubstrateDiff::default();
141    for (&id, fields) in before {
142        let Some(next) = after.get(&id) else {
143            result.removed.push(Record {
144                id,
145                fields: fields.clone(),
146            });
147            continue;
148        };
149        let keys: BTreeSet<_> = fields.keys().chain(next.keys()).collect();
150        let changes: Vec<_> = keys
151            .into_iter()
152            .filter_map(|field| {
153                let old = fields.get(field);
154                let new = next.get(field);
155                if old != new {
156                    Some(FieldChange {
157                        field: field.clone(),
158                        before: old.cloned(),
159                        after: new.cloned(),
160                    })
161                } else {
162                    None
163                }
164            })
165            .collect();
166        if !changes.is_empty() {
167            result.modified.push(ModifiedRecord { id, changes });
168        }
169    }
170    for (&id, fields) in after {
171        if !before.contains_key(&id) {
172            result.added.push(Record {
173                id,
174                fields: fields.clone(),
175            });
176        }
177    }
178    result
179}