Skip to main content

aecr_sync/
delta.rs

1//! Deterministic Merkle-DAG delta export, verification, merge, and conflict detection.
2
3use std::collections::BTreeSet;
4
5use aecr_pig::{Command, CommandBus, CommandRecord, ContentHash, NodeId, PigError};
6use serde::{Deserialize, Serialize};
7
8use crate::error::SyncError;
9
10/// Portable delta payload spanning transactions from `base_root_hash` to `target_root_hash`.
11#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
12pub struct DeltaEnvelope {
13    /// Merkle root hash from which `records` originate.
14    pub base_root_hash: ContentHash,
15    /// Expected Merkle root hash after replaying `records` onto `base_root_hash`.
16    pub target_root_hash: ContentHash,
17    /// Ordered sequence of Command Bus transactions linking `base_root_hash` to `target_root_hash`.
18    pub records: Vec<CommandRecord>,
19}
20
21impl DeltaEnvelope {
22    /// Serializes this delta envelope to a JSON string.
23    pub fn to_json(&self) -> Result<String, SyncError> {
24        serde_json::to_string(self)
25            .map_err(PigError::from)
26            .map_err(SyncError::from)
27    }
28
29    /// Deserializes a delta envelope from a JSON string.
30    pub fn from_json(json: &str) -> Result<Self, SyncError> {
31        serde_json::from_str(json)
32            .map_err(PigError::from)
33            .map_err(SyncError::from)
34    }
35}
36
37/// Overlapping node conflict detected while merging diverged branches.
38#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
39pub struct ConflictEntry {
40    /// Conflicting PIG node identifier modified or invalidated on both branches.
41    pub node_id: NodeId,
42    /// Content hash of `node_id` on the local branch, or `None` if locally removed/absent.
43    pub local_hash: Option<ContentHash>,
44    /// Content hash of `node_id` on the remote branch, or `None` if remotely removed/absent.
45    pub remote_hash: Option<ContentHash>,
46}
47
48/// Outcome returned by [`apply_delta`].
49#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
50pub enum SyncApplyOutcome {
51    /// Local graph already matches the remote delta state.
52    AlreadyUpToDate,
53    /// Local graph matched `base_root_hash` and fast-forwarded cleanly to `new_root_hash`.
54    FastForwarded {
55        /// Number of remote records replayed.
56        applied_records: usize,
57        /// Resulting PIG graph Merkle root hash.
58        new_root_hash: ContentHash,
59    },
60    /// Diverged local and remote branches touched disjoint nodes and merged cleanly.
61    MergedClean {
62        /// Number of non-conflicting remote records merged onto local.
63        applied_records: usize,
64        /// Resulting PIG graph Merkle root hash.
65        new_root_hash: ContentHash,
66    },
67    /// Diverged branches overlapped on one or more nodes; non-conflicting edits still merged.
68    Conflicts {
69        /// Conflicting node identifiers with local and remote content hashes.
70        conflicts: Vec<ConflictEntry>,
71        /// Count of disjoint remote records merged onto the local branch.
72        merged_non_conflicting: usize,
73    },
74}
75
76/// Exports the contiguous active Command Bus delta from `since_root` to the current graph tip.
77pub fn export_delta(bus: &CommandBus, since_root: ContentHash) -> Result<DeltaEnvelope, SyncError> {
78    let target_root = bus.graph().root_hash();
79    if target_root == since_root {
80        return Ok(DeltaEnvelope {
81            base_root_hash: since_root,
82            target_root_hash: target_root,
83            records: Vec::new(),
84        });
85    }
86
87    let mut cursor = target_root;
88    let mut records = Vec::new();
89    for rec in bus.history().iter().rev() {
90        if rec.post_root_hash == cursor {
91            records.push(rec.clone());
92            cursor = rec.pre_root_hash;
93            if cursor == since_root {
94                records.reverse();
95                return Ok(DeltaEnvelope {
96                    base_root_hash: since_root,
97                    target_root_hash: target_root,
98                    records,
99                });
100            }
101        }
102    }
103
104    Err(SyncError::UnknownBaseHash(since_root))
105}
106
107/// Verifies hash-chain integrity and applies `envelope` onto `bus` (fast-forward or 2-branch merge).
108pub fn apply_delta(
109    bus: &mut CommandBus,
110    envelope: &DeltaEnvelope,
111) -> Result<SyncApplyOutcome, SyncError> {
112    verify_envelope_chain(envelope)?;
113    let (mut remote_bus, local_records) = rewind_to_ancestor(bus, envelope.base_root_hash)?;
114
115    if envelope.records.is_empty() {
116        return Ok(SyncApplyOutcome::AlreadyUpToDate);
117    }
118
119    if local_records.is_empty() {
120        replay_and_verify(&mut remote_bus, envelope)?;
121        let new_root_hash = remote_bus.graph().root_hash();
122        *bus = remote_bus;
123        return Ok(SyncApplyOutcome::FastForwarded {
124            applied_records: envelope.records.len(),
125            new_root_hash,
126        });
127    }
128
129    if bus.graph().root_hash() == envelope.target_root_hash {
130        return Ok(SyncApplyOutcome::AlreadyUpToDate);
131    }
132
133    replay_and_verify(&mut remote_bus, envelope)?;
134    merge_diverged_branches(bus, &remote_bus, &local_records, envelope)
135}
136
137fn merge_diverged_branches(
138    bus: &mut CommandBus,
139    remote_bus: &CommandBus,
140    local_records: &[CommandRecord],
141    envelope: &DeltaEnvelope,
142) -> Result<SyncApplyOutcome, SyncError> {
143    let local_affected = collect_affected_nodes(local_records);
144    let remote_affected = collect_affected_nodes(&envelope.records);
145    let overlap_nodes: Vec<NodeId> = local_affected
146        .intersection(&remote_affected)
147        .copied()
148        .collect();
149
150    let mut blocked_nodes = local_affected;
151    let mut non_conflicting: Vec<&CommandRecord> = Vec::new();
152    for rec in &envelope.records {
153        if record_touches_any(rec, &blocked_nodes) {
154            extend_record_affected_nodes(rec, &mut blocked_nodes);
155        } else {
156            non_conflicting.push(rec);
157        }
158    }
159
160    non_conflicting.sort_by(|a, b| {
161        a.timestamp_utc_ns
162            .cmp(&b.timestamp_utc_ns)
163            .then_with(|| a.actor.cmp(&b.actor))
164            .then_with(|| a.seq.cmp(&b.seq))
165    });
166
167    let mut merged_bus = bus.clone();
168    let mut merged_count = 0_usize;
169    for rec in non_conflicting {
170        let _ = merged_bus.apply_batch(
171            rec.actor.clone(),
172            rec.timestamp_utc_ns,
173            rec.commands.clone(),
174        )?;
175        merged_count += 1;
176    }
177
178    let conflicts: Vec<ConflictEntry> = overlap_nodes
179        .into_iter()
180        .map(|node_id| ConflictEntry {
181            node_id,
182            local_hash: bus.graph().get(node_id).map(|n| n.content_hash),
183            remote_hash: remote_bus.graph().get(node_id).map(|n| n.content_hash),
184        })
185        .collect();
186
187    *bus = merged_bus;
188
189    if conflicts.is_empty() {
190        Ok(SyncApplyOutcome::MergedClean {
191            applied_records: merged_count,
192            new_root_hash: bus.graph().root_hash(),
193        })
194    } else {
195        Ok(SyncApplyOutcome::Conflicts {
196            conflicts,
197            merged_non_conflicting: merged_count,
198        })
199    }
200}
201
202fn verify_envelope_chain(envelope: &DeltaEnvelope) -> Result<(), SyncError> {
203    if envelope.records.is_empty() {
204        if envelope.base_root_hash != envelope.target_root_hash {
205            return Err(SyncError::HashMismatch {
206                expected: envelope.target_root_hash,
207                actual: envelope.base_root_hash,
208            });
209        }
210        return Ok(());
211    }
212
213    let mut expected_prev = envelope.base_root_hash;
214    for rec in &envelope.records {
215        if rec.pre_root_hash != expected_prev {
216            return Err(SyncError::HashMismatch {
217                expected: expected_prev,
218                actual: rec.pre_root_hash,
219            });
220        }
221        expected_prev = rec.post_root_hash;
222    }
223
224    if expected_prev != envelope.target_root_hash {
225        return Err(SyncError::HashMismatch {
226            expected: envelope.target_root_hash,
227            actual: expected_prev,
228        });
229    }
230    Ok(())
231}
232
233fn rewind_to_ancestor(
234    bus: &CommandBus,
235    base_root: ContentHash,
236) -> Result<(CommandBus, Vec<CommandRecord>), SyncError> {
237    let mut ancestor_bus = bus.clone();
238    let mut local_records = Vec::new();
239    while ancestor_bus.graph().root_hash() != base_root {
240        match ancestor_bus.undo() {
241            Ok(rec) => local_records.push(rec),
242            Err(PigError::NothingToUndo) => return Err(SyncError::UnknownBaseHash(base_root)),
243            Err(err) => return Err(SyncError::Pig(err)),
244        }
245    }
246    local_records.reverse();
247    Ok((ancestor_bus, local_records))
248}
249
250fn replay_and_verify(bus: &mut CommandBus, envelope: &DeltaEnvelope) -> Result<(), SyncError> {
251    for rec in &envelope.records {
252        let applied = bus.apply_batch(
253            rec.actor.clone(),
254            rec.timestamp_utc_ns,
255            rec.commands.clone(),
256        )?;
257        if applied.post_root_hash != rec.post_root_hash {
258            return Err(SyncError::HashMismatch {
259                expected: rec.post_root_hash,
260                actual: applied.post_root_hash,
261            });
262        }
263    }
264    let actual_target = bus.graph().root_hash();
265    if actual_target != envelope.target_root_hash {
266        return Err(SyncError::HashMismatch {
267            expected: envelope.target_root_hash,
268            actual: actual_target,
269        });
270    }
271    Ok(())
272}
273
274fn collect_affected_nodes(records: &[CommandRecord]) -> BTreeSet<NodeId> {
275    let mut nodes = BTreeSet::new();
276    for rec in records {
277        extend_record_affected_nodes(rec, &mut nodes);
278    }
279    nodes
280}
281
282fn extend_record_affected_nodes(rec: &CommandRecord, out: &mut BTreeSet<NodeId>) {
283    out.extend(rec.affected_nodes.iter().copied());
284    for cmd in &rec.commands {
285        out.insert(command_target_id(cmd));
286    }
287}
288
289fn record_touches_any(rec: &CommandRecord, blocked: &BTreeSet<NodeId>) -> bool {
290    rec.affected_nodes.iter().any(|id| blocked.contains(id))
291        || rec
292            .commands
293            .iter()
294            .any(|cmd| blocked.contains(&command_target_id(cmd)))
295}
296
297const fn command_target_id(cmd: &Command) -> NodeId {
298    match cmd {
299        Command::UpsertNode { node } => node.id,
300        Command::RemoveNode { id }
301        | Command::SetPayload { id, .. }
302        | Command::AttachAnchor { id, .. }
303        | Command::RehostOrphan { id, .. }
304        | Command::ResolveConstraintConflict { id, .. } => *id,
305    }
306}
307
308#[cfg(test)]
309mod tests {
310    use aecr_pig::{
311        ActorId, Command, CommandBus, ContentHash, ElementGuid, NodeId, NodeKind, NodePayload,
312        PigNode, Sha256Hasher,
313    };
314
315    use super::{DeltaEnvelope, SyncApplyOutcome, apply_delta, export_delta};
316    use crate::error::SyncError;
317
318    fn sample_box(id: u64, inputs: Vec<NodeId>, width: f64) -> PigNode {
319        PigNode {
320            id: NodeId(id),
321            guid: ElementGuid::from_seed(&id.to_le_bytes()),
322            name: format!("elem_{id}"),
323            kind: NodeKind::SolidFeature,
324            inputs,
325            anchors: Vec::new(),
326            payload: NodePayload::BoxSolid {
327                origin: [0.0, 0.0, 0.0],
328                size: [width, 0.2, 3.0],
329            },
330            content_hash: ContentHash::ZERO,
331        }
332    }
333
334    fn seeded_common_ancestor() -> Result<(CommandBus, ContentHash), SyncError> {
335        let mut bus = CommandBus::new();
336        let lead = ActorId::new("lead");
337        let _ = bus.apply_batch(
338            lead,
339            100,
340            vec![
341                Command::UpsertNode {
342                    node: sample_box(1, vec![], 3.0),
343                },
344                Command::UpsertNode {
345                    node: sample_box(2, vec![], 4.0),
346                },
347            ],
348        )?;
349        let root = bus.graph().root_hash();
350        Ok((bus, root))
351    }
352
353    #[test]
354    fn fast_forward_and_already_up_to_date_exact_root_hash_parity() -> Result<(), SyncError> {
355        let (mut remote, base_root) = seeded_common_ancestor()?;
356        let mut local = remote.clone();
357        let alice = ActorId::new("alice");
358
359        let _ = remote.apply(
360            alice.clone(),
361            200,
362            Command::SetPayload {
363                id: NodeId(1),
364                payload: NodePayload::BoxSolid {
365                    origin: [0.0, 0.0, 0.0],
366                    size: [5.0, 0.25, 3.0],
367                },
368            },
369        )?;
370        let _ = remote.apply(
371            alice,
372            300,
373            Command::UpsertNode {
374                node: sample_box(3, vec![NodeId(1)], 2.0),
375            },
376        )?;
377
378        let envelope = export_delta(&remote, base_root)?;
379        let encoded = envelope.to_json()?;
380        let decoded = DeltaEnvelope::from_json(&encoded)?;
381        assert_eq!(decoded, envelope);
382
383        let outcome = apply_delta(&mut local, &decoded)?;
384        assert_eq!(
385            outcome,
386            SyncApplyOutcome::FastForwarded {
387                applied_records: 2,
388                new_root_hash: remote.graph().root_hash(),
389            }
390        );
391        assert_eq!(local.graph().root_hash(), remote.graph().root_hash());
392
393        // Re-applying the same envelope reports AlreadyUpToDate without mutation.
394        let replay = apply_delta(&mut local, &decoded)?;
395        assert_eq!(replay, SyncApplyOutcome::AlreadyUpToDate);
396        assert_eq!(local.graph().root_hash(), remote.graph().root_hash());
397        Ok(())
398    }
399
400    #[test]
401    fn clean_non_overlapping_two_branch_merge_converges_symmetrically() -> Result<(), SyncError> {
402        let (base_bus, base_root) = seeded_common_ancestor()?;
403        let mut branch_a = base_bus.clone();
404        let mut branch_b = base_bus;
405
406        let alice = ActorId::new("alice");
407        let bob = ActorId::new("bob");
408
409        // Branch A edits NodeId(1); Branch B edits NodeId(2) and adds NodeId(3).
410        let _ = branch_a.apply(
411            alice,
412            250,
413            Command::SetPayload {
414                id: NodeId(1),
415                payload: NodePayload::BoxSolid {
416                    origin: [0.0, 0.0, 0.0],
417                    size: [6.0, 0.2, 3.0],
418                },
419            },
420        )?;
421        let _ = branch_b.apply(
422            bob.clone(),
423            200,
424            Command::SetPayload {
425                id: NodeId(2),
426                payload: NodePayload::BoxSolid {
427                    origin: [1.0, 0.0, 0.0],
428                    size: [4.5, 0.2, 3.0],
429                },
430            },
431        )?;
432        let _ = branch_b.apply(
433            bob,
434            300,
435            Command::UpsertNode {
436                node: sample_box(3, vec![], 1.5),
437            },
438        )?;
439
440        let delta_a = export_delta(&branch_a, base_root)?;
441        let delta_b = export_delta(&branch_b, base_root)?;
442
443        let out_a = apply_delta(&mut branch_a, &delta_b)?;
444        let out_b = apply_delta(&mut branch_b, &delta_a)?;
445
446        let (merged_a, merged_b) = match (out_a, out_b) {
447            (
448                SyncApplyOutcome::MergedClean {
449                    applied_records: count_a,
450                    new_root_hash: hash_a,
451                },
452                SyncApplyOutcome::MergedClean {
453                    applied_records: count_b,
454                    new_root_hash: hash_b,
455                },
456            ) => {
457                assert_eq!(count_a, 2);
458                assert_eq!(count_b, 1);
459                (hash_a, hash_b)
460            }
461            _ => {
462                return Err(SyncError::UnknownBaseHash(base_root));
463            }
464        };
465
466        assert_eq!(merged_a, merged_b);
467        assert_eq!(branch_a.graph().root_hash(), branch_b.graph().root_hash());
468        assert!(branch_a.graph().get(NodeId(3)).is_some());
469        Ok(())
470    }
471
472    #[test]
473    fn overlapping_node_conflict_detected_while_merging_disjoint_records() -> Result<(), SyncError>
474    {
475        let (base_bus, base_root) = seeded_common_ancestor()?;
476        let mut local = base_bus.clone();
477        let mut remote = base_bus;
478
479        let alice = ActorId::new("alice");
480        let bob = ActorId::new("bob");
481
482        // Both branches mutate NodeId(1); remote also adds disjoint NodeId(4).
483        let _ = local.apply(
484            alice,
485            200,
486            Command::SetPayload {
487                id: NodeId(1),
488                payload: NodePayload::BoxSolid {
489                    origin: [0.0, 0.0, 0.0],
490                    size: [7.0, 0.2, 3.0],
491                },
492            },
493        )?;
494        let expected_local_node1_hash = local.graph().get(NodeId(1)).map(|n| n.content_hash);
495
496        let _ = remote.apply(
497            bob.clone(),
498            210,
499            Command::SetPayload {
500                id: NodeId(1),
501                payload: NodePayload::BoxSolid {
502                    origin: [0.0, 0.0, 0.0],
503                    size: [8.0, 0.2, 3.0],
504                },
505            },
506        )?;
507        let _ = remote.apply(
508            bob,
509            220,
510            Command::UpsertNode {
511                node: sample_box(4, vec![], 2.5),
512            },
513        )?;
514        let expected_remote_node1_hash = remote.graph().get(NodeId(1)).map(|n| n.content_hash);
515
516        let delta = export_delta(&remote, base_root)?;
517        let outcome = apply_delta(&mut local, &delta)?;
518
519        match outcome {
520            SyncApplyOutcome::Conflicts {
521                conflicts,
522                merged_non_conflicting,
523            } => {
524                assert_eq!(merged_non_conflicting, 1);
525                assert_eq!(conflicts.len(), 1);
526                assert_eq!(conflicts.first().map(|c| c.node_id), Some(NodeId(1)));
527                assert_eq!(
528                    conflicts.first().and_then(|c| c.local_hash),
529                    expected_local_node1_hash
530                );
531                assert_eq!(
532                    conflicts.first().and_then(|c| c.remote_hash),
533                    expected_remote_node1_hash
534                );
535                // Local NodeId(1) is preserved while disjoint NodeId(4) merged cleanly.
536                assert_eq!(
537                    local.graph().get(NodeId(1)).map(|n| n.content_hash),
538                    expected_local_node1_hash
539                );
540                assert!(local.graph().get(NodeId(4)).is_some());
541            }
542            _ => {
543                return Err(SyncError::UnknownBaseHash(base_root));
544            }
545        }
546        Ok(())
547    }
548
549    #[test]
550    fn rejects_unknown_base_hash_and_corrupted_hash_chains() -> Result<(), SyncError> {
551        let (mut bus, base_root) = seeded_common_ancestor()?;
552        let bogus = Sha256Hasher::digest(b"nonexistent-root");
553        assert!(matches!(
554            export_delta(&bus, bogus),
555            Err(SyncError::UnknownBaseHash(hash)) if hash == bogus
556        ));
557
558        let mut remote = bus.clone();
559        let _ = remote.apply(
560            ActorId::new("carol"),
561            500,
562            Command::UpsertNode {
563                node: sample_box(9, vec![], 1.0),
564            },
565        )?;
566        let mut bad_envelope = export_delta(&remote, base_root)?;
567        bad_envelope.target_root_hash = bogus;
568
569        assert!(matches!(
570            apply_delta(&mut bus, &bad_envelope),
571            Err(SyncError::HashMismatch { .. })
572        ));
573        Ok(())
574    }
575
576    #[test]
577    fn deterministic_ordering_and_delete_vs_modify_conflict() -> Result<(), SyncError> {
578        let (base_bus, base_root) = seeded_common_ancestor()?;
579        let mut local = base_bus.clone();
580        let mut remote = base_bus;
581
582        // Local modifies NodeId(1).
583        let _ = local.apply(
584            ActorId::new("alice"),
585            200,
586            Command::SetPayload {
587                id: NodeId(1),
588                payload: NodePayload::BoxSolid {
589                    origin: [0.0, 0.0, 0.0],
590                    size: [9.0, 0.2, 3.0],
591                },
592            },
593        )?;
594        let expected_local_hash = local.graph().get(NodeId(1)).map(|n| n.content_hash);
595
596        // Remote removes NodeId(1) and creates two disjoint nodes with out-of-order timestamps.
597        let _ = remote.apply(
598            ActorId::new("bob"),
599            300,
600            Command::RemoveNode { id: NodeId(1) },
601        )?;
602        let _ = remote.apply(
603            ActorId::new("zoe"),
604            500,
605            Command::UpsertNode {
606                node: sample_box(10, vec![], 1.0),
607            },
608        )?;
609        let _ = remote.apply(
610            ActorId::new("amy"),
611            400,
612            Command::UpsertNode {
613                node: sample_box(11, vec![], 1.5),
614            },
615        )?;
616
617        let delta = export_delta(&remote, base_root)?;
618        let local_history_before = local.history().len();
619        let outcome = apply_delta(&mut local, &delta)?;
620
621        match outcome {
622            SyncApplyOutcome::Conflicts {
623                conflicts,
624                merged_non_conflicting,
625            } => {
626                assert_eq!(merged_non_conflicting, 2);
627                assert_eq!(conflicts.len(), 1);
628                assert_eq!(conflicts.first().map(|c| c.node_id), Some(NodeId(1)));
629                assert_eq!(
630                    conflicts.first().and_then(|c| c.local_hash),
631                    expected_local_hash
632                );
633                assert_eq!(conflicts.first().and_then(|c| c.remote_hash), None);
634            }
635            _ => {
636                return Err(SyncError::UnknownBaseHash(base_root));
637            }
638        }
639
640        // Merged non-conflicting records must be ordered by (timestamp_utc_ns, actor, seq).
641        assert_eq!(local.history().len(), local_history_before + 2);
642        assert_eq!(
643            local
644                .history()
645                .get(local_history_before)
646                .map(|r| r.timestamp_utc_ns),
647            Some(400)
648        );
649        assert_eq!(
650            local
651                .history()
652                .get(local_history_before + 1)
653                .map(|r| r.timestamp_utc_ns),
654            Some(500)
655        );
656        Ok(())
657    }
658}