Skip to main content

lean_ctx_cloud/replica/
fold.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Materialisation of a place's log into its graph (SPEC-ENGINE §3.4.5).
3//!
4//! The fold is pure: it orders events by the server's `seq` (the single
5//! source of truth) and applies them, so any arrival order of the same
6//! events gives the same nodes and edges. Events whose signature or body
7//! check failed (`sig_invalid`) never fold.
8
9use std::collections::{BTreeMap, BTreeSet};
10
11use serde_json::{Map, Value};
12
13/// One event as the fold sees it (already verified).
14#[derive(Debug, Clone, PartialEq)]
15pub struct FoldEvent {
16    pub seq: u64,
17    pub event_id: String,
18    pub op: String,
19    pub target: Option<String>,
20    pub node_type: Option<String>,
21    /// `None` for a purged event (key shredded) or a withheld stub.
22    pub body: Option<Value>,
23    pub sig_invalid: bool,
24    /// Server fields: provenance the server stamped (`own`, `workspace`,
25    /// `foreign`, …) and review state (`confirmed`, `unconfirmed`, …).
26    pub provenance: Option<String>,
27    pub review_state: Option<String>,
28}
29
30#[derive(Debug, Clone, Default, PartialEq)]
31pub struct Node {
32    pub node_type: String,
33    /// The body fields without `body_nonce`; empty once purged.
34    pub fields: Map<String, Value>,
35    pub retracted: bool,
36    pub purged: bool,
37    pub last_seq: u64,
38    /// From the event that added the node.
39    pub provenance: Option<String>,
40    pub review_state: Option<String>,
41}
42
43#[derive(Debug, Clone, Default, PartialEq, Eq)]
44pub struct Edge {
45    pub kind: String,
46    pub from: String,
47    pub to: String,
48    pub retracted: bool,
49    pub last_seq: u64,
50}
51
52/// A purge tombstone as applied (reason and the event ids it shredded).
53#[derive(Debug, Clone, PartialEq, Eq)]
54pub struct Purge {
55    pub purge_id: String,
56    pub reason: String,
57}
58
59/// The folded graph of a place.
60#[derive(Debug, Clone, Default, PartialEq)]
61pub struct Graph {
62    pub nodes: BTreeMap<String, Node>,
63    pub edges: BTreeMap<String, Edge>,
64    /// Event ids whose body a purge shredded.
65    pub purged_events: BTreeSet<String>,
66    /// Node id → the purge that removed its text.
67    pub purged_nodes: BTreeMap<String, Purge>,
68    /// Every purge tombstone folded: `(purge_id, seq of the tombstone)`;
69    /// each one is acknowledged to the place once (E9).
70    pub tombstones: BTreeSet<(String, u64)>,
71    /// Event id of every `node.add` → its node, so a later purge of that
72    /// event finds the node.
73    pub added_by: BTreeMap<String, String>,
74    /// Highest `seq` folded.
75    pub cursor: u64,
76}
77
78/// Why folding a place stopped (fail closed).
79#[derive(Debug, Clone, PartialEq, Eq)]
80pub enum FoldError {
81    /// A purge reason outside the four owner-approved values.
82    PurgeReasonInvalid(String),
83    /// Two different events with the same `seq`.
84    SeqConflict(u64),
85}
86
87impl std::fmt::Display for FoldError {
88    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
89        match self {
90            Self::PurgeReasonInvalid(r) => write!(f, "purge_reason_invalid: {r}"),
91            Self::SeqConflict(seq) => write!(f, "two events with seq {seq}"),
92        }
93    }
94}
95
96fn fields_of(body: &Value) -> Map<String, Value> {
97    let mut fields = body.as_object().cloned().unwrap_or_default();
98    fields.remove("body_nonce");
99    fields
100}
101
102impl Graph {
103    /// Fold `events` (any order) onto this graph. Events at or below the
104    /// cursor were folded before and are skipped.
105    pub fn fold(&mut self, events: &[FoldEvent]) -> Result<(), FoldError> {
106        let mut ordered: Vec<&FoldEvent> = events.iter().filter(|e| e.seq > self.cursor).collect();
107        ordered.sort_by_key(|e| e.seq);
108        for pair in ordered.windows(2) {
109            if pair[0].seq == pair[1].seq {
110                if pair[0] == pair[1] {
111                    continue;
112                }
113                return Err(FoldError::SeqConflict(pair[0].seq));
114            }
115        }
116        ordered.dedup_by_key(|e| e.seq);
117        for e in ordered {
118            self.cursor = e.seq;
119            if e.sig_invalid {
120                continue;
121            }
122            self.apply(e)?;
123        }
124        Ok(())
125    }
126
127    fn apply(&mut self, e: &FoldEvent) -> Result<(), FoldError> {
128        let target = e.target.clone().unwrap_or_default();
129        match e.op.as_str() {
130            "node.add" => {
131                self.added_by
132                    .entry(e.event_id.clone())
133                    .or_insert_with(|| target.clone());
134                let purged = e.body.is_none() || self.purged_events.contains(&e.event_id);
135                let node = self.nodes.entry(target.clone()).or_insert_with(|| Node {
136                    node_type: e.node_type.clone().unwrap_or_default(),
137                    fields: if purged {
138                        Map::new()
139                    } else {
140                        e.body.as_ref().map(fields_of).unwrap_or_default()
141                    },
142                    purged,
143                    provenance: e.provenance.clone(),
144                    review_state: e.review_state.clone(),
145                    ..Node::default()
146                });
147                // The same claim added again (another engine) keeps the
148                // first text; only the sequence moves.
149                node.last_seq = e.seq;
150            }
151            "field.set" => {
152                if let (Some(node), Some(body)) = (self.nodes.get_mut(&target), &e.body)
153                    && !node.purged
154                    && let Some(field) = body.get("field").and_then(Value::as_str)
155                {
156                    node.fields.insert(
157                        field.to_string(),
158                        body.get("value").cloned().unwrap_or(Value::Null),
159                    );
160                    node.last_seq = e.seq;
161                }
162            }
163            "edge.add" => {
164                if let Some(body) = &e.body {
165                    let s = |k: &str| {
166                        body.get(k)
167                            .and_then(Value::as_str)
168                            .unwrap_or_default()
169                            .to_string()
170                    };
171                    let edge = self.edges.entry(target).or_insert_with(|| Edge {
172                        kind: s("kind"),
173                        from: s("from"),
174                        to: s("to"),
175                        ..Edge::default()
176                    });
177                    edge.last_seq = e.seq;
178                }
179            }
180            "retract" | "restore" => {
181                let retracted = e.op == "retract";
182                if let Some(node) = self.nodes.get_mut(&target) {
183                    node.retracted = retracted;
184                    node.last_seq = e.seq;
185                } else if let Some(edge) = self.edges.get_mut(&target) {
186                    edge.retracted = retracted;
187                    edge.last_seq = e.seq;
188                }
189            }
190            "purge" => self.apply_purge(e)?,
191            _ => {}
192        }
193        Ok(())
194    }
195
196    fn apply_purge(&mut self, e: &FoldEvent) -> Result<(), FoldError> {
197        let Some(body) = &e.body else {
198            return Ok(());
199        };
200        let reason = body
201            .get("reason")
202            .and_then(Value::as_str)
203            .unwrap_or_default()
204            .to_string();
205        if !super::store::PURGE_REASONS.contains(&reason.as_str()) {
206            return Err(FoldError::PurgeReasonInvalid(reason));
207        }
208        let purge = Purge {
209            purge_id: body
210                .get("purge_id")
211                .and_then(Value::as_str)
212                .unwrap_or_default()
213                .to_string(),
214            reason,
215        };
216        self.tombstones.insert((purge.purge_id.clone(), e.seq));
217        let ids = ["targets", "cascade"]
218            .iter()
219            .filter_map(|k| body.get(*k).and_then(Value::as_array))
220            .flatten()
221            .filter_map(Value::as_str);
222        for id in ids {
223            self.purged_events.insert(id.to_string());
224            if let Some(node_id) = self.added_by.get(id)
225                && let Some(node) = self.nodes.get_mut(node_id)
226            {
227                node.fields.clear();
228                node.purged = true;
229                self.purged_nodes.insert(node_id.clone(), purge.clone());
230            }
231        }
232        Ok(())
233    }
234
235    /// Nodes an agent may be given: not retracted, not purged.
236    pub fn live_nodes(&self) -> impl Iterator<Item = (&String, &Node)> {
237        self.nodes.iter().filter(|(_, n)| !n.retracted && !n.purged)
238    }
239
240    /// A digest of the graph two engines must agree on once they folded the
241    /// same log: every node (type, fields, state) and edge in id order, as
242    /// canonical JSON. Local server-field views (provenance, review state)
243    /// are left out; they differ per reader.
244    pub fn digest(&self) -> String {
245        let mut h = blake3::Hasher::new();
246        for (id, n) in &self.nodes {
247            let line = serde_json::json!([id, n.node_type, n.fields, n.retracted, n.purged]);
248            if let Ok(bytes) = lean_ctx_protocol::cloud::canonical_json(&line) {
249                h.update(&bytes);
250                h.update(b"\n");
251            }
252        }
253        for (id, e) in &self.edges {
254            let line = serde_json::json!([id, e.kind, e.from, e.to, e.retracted]);
255            if let Ok(bytes) = lean_ctx_protocol::cloud::canonical_json(&line) {
256                h.update(&bytes);
257                h.update(b"\n");
258            }
259        }
260        h.finalize().to_hex()[..16].to_string()
261    }
262}
263
264#[cfg(test)]
265#[path = "fold_tests.rs"]
266mod tests;