Skip to main content

car_sync/
lib.rs

1//! Multi-device sync core for CAR — the oplog + deterministic fold (slice B1
2//! of `docs/proposals/multi-device-sync.md`).
3//!
4//! The proposal's frame: **sync events, not files.** Every state-changing
5//! operation is appended to a content-addressed, append-only, replica-tagged
6//! [`oplog::OpRecord`] log; sync is "send me the ops I don't have"; and each
7//! device [`fold::fold`]s the full op-set into materialized state
8//! **deterministically** — commutative, associative, and idempotent over the
9//! op-set (CRDT properties), so two laptops writing simultaneously converge
10//! the moment they exchange ops.
11//!
12//! What this slice ships (pure, library-only — no network, no daemon wiring):
13//!
14//! - [`oplog`] — [`oplog::OpRecord`] exactly as the proposal specs it
15//!   (`op_id` content-derived, `hlc {wall_ms, counter, device_id}`,
16//!   `scope: Personal | Shared{org}`, the eight-variant `surface` enum,
17//!   surface-specific `payload`), plus the per-device `seq`/`prev` hash-chain
18//!   linkage that makes a device's log **order-verifiable**
19//!   ([`oplog::verify_log`]) and the [`oplog::DeviceLog`] writer that stamps
20//!   [`oplog::Hlc`] values from the hybrid clock (see the B3 note below).
21//! - [`fold`] — [`fold::fold`]`(ops) -> `[`fold::SyncState`] under the
22//!   proposal's per-surface fold rules: **grow-only union by stable ID** for
23//!   the log tier, **LWW-register per record ordered by HLC** for the
24//!   registry tier, and ordered-observation [`fold::SyncState::replay`] for
25//!   the path-dependent routing tier ("sync the observations, not the
26//!   result" — the EMA apply is injected, execution stays out of the crate).
27//!   [`fold::state_hash`] is the divergence-detection invariant ("same
28//!   frontier ⇒ same snapshot hash"), and
29//!   [`fold::registry_as_lww`] projects a folded registry onto
30//!   `car_state::crdt::LwwMap` so the fold provably agrees with the shipped
31//!   `crdt_merge` primitives where the domains overlap.
32//! - [`journal`] — durable JSONL persistence for the log in the
33//!   `car-eventlog` journal idiom: append-only, torn-line tolerant on load,
34//!   plus B4's [`journal::OplogJournal::truncate_to`] (atomic
35//!   temp+rename rewrite under the existing advisory lock, stamping a
36//!   [`journal::TruncationMarker`] that fences the naive
37//!   `load`+`resume` path into a runtime error — a truncated tail resumes
38//!   only through [`checkpoint::resume_anchored`]).
39//! - [`checkpoint`] (B4) — [`checkpoint::Checkpoint`]: a serialized fold at
40//!   a frontier — per-device `{seq, hlc, head}` frontier entries, covered
41//!   scopes, the [`fold::SyncState`] snapshot, [`fold::state_hash`] as the
42//!   divergence invariant, and a whole-record `checkpoint_hash` (frontier +
43//!   scopes + state) as the content address / file name — so "same file ⇒
44//!   same checkpoint" holds even when two frontiers fold to one deduped
45//!   state, and a tampered frontier is rejected on load.
46//!   [`checkpoint::verify_anchored`] proves a truncated tail continues the
47//!   checkpoint's recorded chain heads (the checkpoint IS the anchored
48//!   head); [`checkpoint::resume_anchored`] resumes a device chain past a
49//!   truncation without forking. [`fold::fold_onto`] is the consumption
50//!   primitive: `fold_onto(checkpoint.state, tail) == fold(full log)`.
51//! - [`compact`] (B4) — per-surface retention
52//!   ([`compact::RetentionPolicy::proposal_default`]: conversations last-N,
53//!   runs 50/agent + 30 days, trajectories last-D, knowledge/skills/routing
54//!   keep-all — every dropped id-bearing entry leaves a minimal tombstone
55//!   stub so `supersedes` references resolve even when they arrive after
56//!   compaction, and event-stream trims are rejected), the monotone-only
57//!   [`compact::AckTable`] fold-frontier bookkeeping (an ack asserts
58//!   durably-folded state — MUST, binding on B3), and
59//!   [`compact::compact_and_truncate`] enforcing the crash-ordering
60//!   invariant **checkpoint durable FIRST, then truncate** — acknowledged
61//!   data is never lost, and compaction refuses to drop anything above ANY
62//!   device's acked frontier.
63//!
64//! Determinism discipline (the proposal's "free property" depends on it):
65//! all folded state lives in `BTreeMap`s — no `HashMap` iteration order, no
66//! wall-clock reads anywhere in the fold/retention path (the age rules'
67//! reference instant defaults to [`compact::as_of_from_ops`], pure over the
68//! below-frontier ops).
69//!
70//! B3 adds the missing middle — how ops actually travel:
71//!
72//! - [`oplog::HlcClock`] — the **real hybrid logical clock**: `{wall_ms,
73//!   counter}` state with the standard send/receive rules (max of local
74//!   wall and everything witnessed; counter ticks on ties), monotone under
75//!   clock skew, regression, and same-millisecond bursts. It replaces B1's
76//!   pure-Lamport stamp source behind the SAME wire shape, exactly as
77//!   promised — [`DeviceLog::new`] still defaults to the degenerate
78//!   logical (always-0 wall) mode, and wall readings are **injectable**
79//!   ([`oplog::WallClock`]; [`oplog::system_clock`] is the one opt-in
80//!   place system time exists in this crate).
81//! - [`relay`] — the [`relay::Relay`] trait (`push` / `pull(since seq
82//!   frontier) → {ops, latest_checkpoint_ptr}` / `ack` /
83//!   `checkpoint_put/get` / `roster`) with two reference implementations:
84//!   [`relay::InMemoryRelay`] and the shared-directory
85//!   [`relay::FsRelay`] loopback (the single-user two-Mac case). The relay
86//!   admits only ops that *continue* a device's relay-held chain (fork =
87//!   runtime error), computes the **stable frontier** = `min(acked)` over
88//!   non-evicted roster devices, marks a device silent past the horizon
89//!   `H` [`relay::DeviceStatus::Evicted`] (its ack no longer pins GC;
90//!   reinstated on a caught-up ack), and GC-drops an op **only** when it
91//!   is both at/below the stable frontier AND covered by a stored
92//!   checkpoint — checkpoints dedup on `checkpoint_hash`, the whole-record
93//!   content address, never `state_hash` (the B4 contract).
94//! - [`session`] — [`session::SyncSession`], the device-side pump holding
95//!   the B1/B4 contracts **by construction**: append journals (flushed)
96//!   before an op is pushable (journal-durable before transmit); pulls are
97//!   verified before folding; folds are journaled before the ack, whose
98//!   value is *derived from journal-held ops only* (acking merely-received
99//!   state is impossible). Retry-safe at every crash point (`op_id` dedup
100//!   both ways). Cold bootstrap / straggler re-entry is
101//!   [`session::SyncSession::bootstrap`]/[`session::SyncSession::rebase`]:
102//!   `checkpoint_get` + `pull(since = checkpoint frontier)` +
103//!   [`checkpoint::resume_anchored`] — never `DeviceLog::resume` — with
104//!   locally-held uncovered ops (a returning straggler's unpushed writes)
105//!   carried across the rebase and pushed after.
106//!
107//! B5 adds **execution lease + fencing** — single-leader *execution* layered
108//! on top of the leaderless *replication* above:
109//!
110//! - [`lease`] — the [`lease::LeaseCoordinator`] trait: a **linearizable**
111//!   compare-and-swap register per agent (exactly one holder at a time; a new
112//!   acquire after TTL-expiry or release bumps the monotone `epoch` = the
113//!   fencing token). It is deliberately **separate** from
114//!   [`relay::Relay`] — an eventually-consistent relay structurally cannot
115//!   host a lease (no consensus). [`lease::InMemoryLeaseCoordinator`] is the
116//!   honest in-process reference (`Arc<Mutex>` CAS is genuinely linearizable
117//!   in one process); a distributed backend is B6. The lease register holds
118//!   only non-sensitive metadata, so it never breaches the E2E guarantee on
119//!   the actual agent data (the proposal's data/control-plane split).
120//! - **Fencing as a fold property, over two views** — the leased
121//!   [`oplog::Surface::Intent`] surface ([`fold::FoldTier::Leased`]) carries
122//!   the `epoch`, and the fold yields (a) [`fold::SyncState::committed_run`],
123//!   the **fence-independent, keep-all idempotency ORACLE** (survives epoch
124//!   bumps AND compaction — the correct "did this run already execute?"
125//!   lookup), and (b) [`fold::SyncState::intent`], the "who holds now" view
126//!   where *pending* intents are per-agent fenced (a stale zombie's pending
127//!   loses **deterministically, order-independently, without a wall-clock
128//!   race** — fencing beats HLC) while committed/failed are terminal-immune.
129//!   Idempotency keys on the B7 `car_proto::deterministic_run_id`. **This
130//!   converges the ledger and provides the durable oracle; it is NOT
131//!   exactly-once execution** — that is B6's dispatch fence (a linearizable
132//!   "still epoch N?" plus the oracle read, before the external effect). See
133//!   [`lease`] and [`session::SyncSession::record_intent`] (terminal-guarded).
134//!
135//! B2 adds **transcript resume** — the conversation surface as an ordered,
136//! role-threaded projection of the oplog:
137//!
138//! - [`conversation`] — [`fold::SyncState::transcript`] folds the
139//!   [`oplog::Surface::Conversation`] entries for one `conversation_id` into a
140//!   causally-ordered `Vec<`[`conversation::Turn`]`>` (the crate's canonical
141//!   `(hlc, op_id)` order — two devices talking to the same agent concurrently
142//!   interleave deterministically), and [`fold::SyncState::resume_messages`]
143//!   returns the **repaired, provider-valid** [`car_inference_types::Message`]
144//!   sequence car-inference's multi-turn path replays to continue the
145//!   conversation — the verbatim conversation-resume API
146//!   `docs/solutions/conversation-persistence-removed-in-0.25.md` says does not
147//!   exist today. A conversation turn is an **event stream keyed by `op_id`**
148//!   (op identity IS turn identity — the kernel-review correction: content
149//!   keying silently dropped two genuine same-timestamp turns), so a resent op
150//!   dedups but two distinct authorings never collapse; it differs from routing
151//!   only in being an *independent* multiset (no path-dependent replay), so it
152//!   tolerates `LastN` retention. Because HLC order is deterministic but says
153//!   nothing about *concurrent* turns, `resume_messages` runs a repair (coalesce
154//!   adjacent same-role turns, drop orphan/dangling tool exchanges) so the
155//!   `Message` sequence is never provider-invalid — the "runtime validates"
156//!   thesis applied to the projection. The 0.25 *compaction-vs-store
157//!   incoherence* cannot recur: the oplog is the one source of truth and the
158//!   transcript is a projection of the same folded state B4's checkpoint
159//!   serializes. Built on the shared `car-inference-types` crate, so a
160//!   `Message` shape change is a compile error here, not a runtime break in B6.
161//!
162//! Later slices: rerouting today's file write paths through the oplog and the
163//! daemon/memgine adoption of transcript resume (B6), the `sync.*` WS/FFI
164//! surface + E2E encryption + checkpoint/op signing + per-scope streams + the
165//! **distributed lease coordinator** (B6 — the network backend speaks the
166//! [`relay::Relay`] and [`lease::LeaseCoordinator`] contracts).
167
168pub mod checkpoint;
169pub mod compact;
170pub mod conversation;
171pub mod crypto;
172pub mod fence;
173pub mod fold;
174pub mod journal;
175pub mod lease;
176pub mod oplog;
177pub mod relay;
178pub mod session;
179
180pub use checkpoint::{
181    resume_anchored, verify_anchored, AnchorError, Checkpoint, CheckpointError, FrontierEntry,
182};
183pub use compact::{
184    apply_retention, as_of_from_ops, compact_and_truncate, is_tombstone, plan_compaction,
185    AckTable, CompactError, CompactionOutcome, CompactionPlan, RetentionPolicy, RetentionReport,
186    RetentionRule, RUNS_MAX_AGE_MS, RUNS_MAX_PER_AGENT,
187};
188pub use conversation::{Role, Turn, DEFAULT_CONVERSATION};
189pub use crypto::{
190    encryption_audience, CryptoError, Envelope, LocalKeyCipher, PayloadCipher,
191    ALG_CHACHA20POLY1305,
192};
193pub use fence::{check_dispatch, FenceDecision};
194pub use fold::{
195    fold, fold_onto, hlc_version, registry_as_lww, state_hash, FoldTier, FoldedRecord, IntentAgent,
196    SyncState,
197};
198pub use journal::{OplogJournal, TruncationMarker};
199pub use lease::{
200    InMemoryLeaseCoordinator, Intent, IntentStatus, Lease, LeaseCoordinator, LeaseError,
201};
202pub use oplog::{
203    canonical_json, logical_clock, system_clock, verify_log, ChainError, DeviceLog, Hlc,
204    HlcClock, OpRecord, Scope, Surface, WallClock,
205};
206pub use relay::{
207    checkpoint_frontier, frontier_of, AckOutcome, DeviceStatus, Frontier, FsRelay, GcReport,
208    InMemoryRelay, PullResult, PushOutcome, Relay, RelayConfig, RelayError, RosterEntry,
209};
210pub use session::{PumpReport, SessionError, SyncSession};
211
212#[cfg(test)]
213mod tests {
214    use super::*;
215    use serde_json::json;
216
217    /// Build a two-device op-set exercising both fold tiers:
218    /// grow-only Knowledge facts + LWW Declagent registry records.
219    fn two_device_ops() -> Vec<OpRecord> {
220        let mut a = DeviceLog::new("device-a");
221        let mut b = DeviceLog::new("device-b");
222
223        let mut ops = vec![
224            a.append(
225                Scope::Personal,
226                Surface::Knowledge,
227                json!({"id": "fact-1", "body": "the sky is blue"}),
228            ),
229            a.append(
230                Scope::Personal,
231                Surface::Declagent,
232                json!({"id": "agent-1", "name": "milo", "rev": "a1"}),
233            ),
234            b.append(
235                Scope::Personal,
236                Surface::Knowledge,
237                json!({"id": "fact-2", "body": "water is wet"}),
238            ),
239        ];
240        // b observes a's ops (lamport receive rule) then overwrites agent-1.
241        for op in &ops {
242            b.observe(&op.hlc);
243        }
244        ops.push(b.append(
245            Scope::Personal,
246            Surface::Declagent,
247            json!({"id": "agent-1", "name": "milo", "rev": "b2"}),
248        ));
249        ops.push(a.append(
250            Scope::Personal,
251            Surface::Conversation,
252            json!({"speaker": "user", "text": "hi", "timestamp": 1}),
253        ));
254        ops
255    }
256
257    /// Heap's algorithm — every permutation of `items`, no rand dependency.
258    fn permutations<T: Clone>(items: &[T]) -> Vec<Vec<T>> {
259        fn heap<T: Clone>(k: usize, arr: &mut Vec<T>, out: &mut Vec<Vec<T>>) {
260            if k == 1 {
261                out.push(arr.clone());
262                return;
263            }
264            for i in 0..k {
265                heap(k - 1, arr, out);
266                if k.is_multiple_of(2) {
267                    arr.swap(i, k - 1);
268                } else {
269                    arr.swap(0, k - 1);
270                }
271            }
272        }
273        let mut arr = items.to_vec();
274        let mut out = Vec::new();
275        heap(arr.len(), &mut arr, &mut out);
276        out
277    }
278
279    #[test]
280    fn fold_is_permutation_invariant() {
281        // The core CRDT law: same op-SET in any order → the same state and
282        // the same state hash. All 120 permutations of a 5-op set.
283        let ops = two_device_ops();
284        let baseline = fold(&ops);
285        let baseline_hash = state_hash(&baseline);
286        for perm in permutations(&ops) {
287            let folded = fold(&perm);
288            assert_eq!(folded, baseline, "fold must be order-independent");
289            assert_eq!(state_hash(&folded), baseline_hash);
290        }
291    }
292
293    #[test]
294    fn fold_is_idempotent_over_duplicated_ops() {
295        // Re-delivered ops (relay retransmission) dedup on op_id: folding the
296        // set twice-concatenated equals folding it once.
297        let ops = two_device_ops();
298        let mut doubled = ops.clone();
299        doubled.extend(ops.iter().cloned());
300        assert_eq!(fold(&doubled), fold(&ops));
301        // Re-folding the identical set is stable (idempotent re-fold).
302        assert_eq!(fold(&ops), fold(&ops));
303    }
304
305    #[test]
306    fn divergent_replica_union_matches_crdt_merge() {
307        // The overlap contract with the shipped car-state CRDT primitives:
308        // folding the UNION of two devices' ops must resolve a registry to
309        // exactly the state crdt_merge produces from the per-device exports.
310        let ops = two_device_ops();
311        let a_ops: Vec<OpRecord> = ops.iter().filter(|o| o.device_id == "device-a").cloned().collect();
312        let b_ops: Vec<OpRecord> = ops.iter().filter(|o| o.device_id == "device-b").cloned().collect();
313
314        let union_lww = registry_as_lww(&fold(&ops), &Surface::Declagent.tag());
315        let a_lww = registry_as_lww(&fold(&a_ops), &Surface::Declagent.tag());
316        let b_lww = registry_as_lww(&fold(&b_ops), &Surface::Declagent.tag());
317
318        let merged_ab = car_state::crdt::merge_maps(&a_lww, &b_lww);
319        let merged_ba = car_state::crdt::merge_maps(&b_lww, &a_lww);
320        assert_eq!(merged_ab, union_lww, "fold(union) == crdt_merge(exports)");
321        assert_eq!(merged_ba, union_lww, "in either merge order");
322
323        // And the winner is b's later write (b observed a first — higher HLC).
324        assert_eq!(union_lww["id:agent-1"].value["rev"], json!("b2"));
325        assert_eq!(union_lww["id:agent-1"].replica, "device-b");
326    }
327
328    #[test]
329    fn journal_round_trip_load_fold_verify() {
330        let dir = tempfile::tempdir().unwrap();
331        let path = dir.path().join("oplog.jsonl");
332        let ops = two_device_ops();
333        {
334            let mut journal = OplogJournal::open(&path).unwrap();
335            for op in &ops {
336                journal.append(op).unwrap();
337            }
338        }
339        let loaded = OplogJournal::load(&path).unwrap();
340        assert_eq!(loaded, ops);
341        verify_log(&loaded).expect("loaded log must chain-verify");
342        assert_eq!(state_hash(&fold(&loaded)), state_hash(&fold(&ops)));
343    }
344
345    /// Build a two-device op-set touching EVERY surface tier, with a valid
346    /// frontier cut at `split` (every op before it is HLC-≤ every device's
347    /// ack): grow-only entities, an LWW registry record overwritten across
348    /// the cut, and a routing observation multiset spanning the cut
349    /// (including a byte-identical repeat — the multiset trap).
350    fn all_surface_ops() -> (Vec<OpRecord>, usize) {
351        let mut a = DeviceLog::new("dev-a");
352        let mut b = DeviceLog::new("dev-b");
353        let mut ops = vec![
354            a.append(Scope::Personal, Surface::Knowledge, json!({"id": "f1", "timestamp": 10})),
355            a.append(Scope::Personal, Surface::Skill, json!({"id": "s1"})),
356            a.append(Scope::Personal, Surface::Conversation, json!({"speaker": "u", "text": "hi", "timestamp": 11})),
357            a.append(Scope::Personal, Surface::Run, json!({"id": "r1", "agent_id": "milo", "timestamp": 12})),
358            a.append(Scope::Personal, Surface::Trajectory, json!({"id": "t1", "timestamp": 13})),
359            a.append(Scope::Personal, Surface::Declagent, json!({"id": "agent-1", "rev": "a"})),
360            a.append(Scope::Shared { org: "acme".into() }, Surface::Registry { kind: "agents".into() }, json!({"id": "reg-1", "v": 1})),
361            a.append(Scope::Personal, Surface::Routing, json!({"sample": 1.0})),
362            a.append(Scope::Personal, Surface::Routing, json!({"sample": 1.0})), // byte-identical repeat
363        ];
364        for op in &ops {
365            b.observe(&op.hlc);
366        }
367        ops.push(b.append(Scope::Personal, Surface::Knowledge, json!({"id": "f2", "timestamp": 20})));
368        let split = ops.len();
369        // Tail: every tier mutates again, above the frontier.
370        ops.push(b.append(Scope::Personal, Surface::Conversation, json!({"speaker": "a", "text": "yo", "timestamp": 21})));
371        ops.push(b.append(Scope::Personal, Surface::Declagent, json!({"id": "agent-1", "rev": "b"}))); // LWW across the cut
372        ops.push(b.append(Scope::Personal, Surface::Routing, json!({"sample": 0.0})));
373        ops.push(b.append(Scope::Personal, Surface::Run, json!({"id": "r2", "agent_id": "milo", "timestamp": 22})));
374        for op in &ops[split..] {
375            a.observe(&op.hlc);
376        }
377        ops.push(a.append(Scope::Personal, Surface::Knowledge, json!({"id": "f1", "timestamp": 99}))); // grow-only collision across the cut
378        (ops, split)
379    }
380
381    fn acks_at(ops: &[OpRecord], split: usize) -> AckTable {
382        // Every device acks the max HLC of the prefix ("I have folded
383        // everything at or below this stamp"), so the stable frontier is
384        // exactly the cut.
385        let frontier = ops[..split].iter().map(|o| o.hlc.clone()).max().unwrap();
386        let mut acks = AckTable::new();
387        for op in ops {
388            acks.ack(op.device_id.clone(), frontier.clone());
389        }
390        acks
391    }
392
393    #[test]
394    fn compaction_equivalence_fold_full_equals_checkpoint_plus_tail() {
395        // THE invariant that makes compaction safe, per surface:
396        // fold(full log) == fold_onto(checkpoint.state, retained tail),
397        // byte-identical state AND state_hash — including the routing
398        // observation MULTISET and its order-sensitive replay.
399        let (ops, split) = all_surface_ops();
400        let acks = acks_at(&ops, split);
401        let plan = plan_compaction(&ops, &acks, &RetentionPolicy::keep_all(), None).unwrap();
402        assert_eq!(plan.dropped_ops, split);
403        assert_eq!(plan.retained_ops.len(), ops.len() - split);
404
405        let full = fold(&ops);
406        let reconstructed = fold_onto(&plan.checkpoint.state, &plan.retained_ops);
407        assert_eq!(reconstructed, full);
408        assert_eq!(state_hash(&reconstructed), state_hash(&full));
409
410        // Per-surface spot checks across the cut:
411        assert_eq!(
412            reconstructed.registries[&Surface::Declagent.tag()]["id:agent-1"].payload["rev"],
413            json!("b"),
414            "LWW: the tail's later write wins over the checkpointed one"
415        );
416        assert_eq!(
417            reconstructed.logs[&Surface::Knowledge.tag()]["id:f1"].payload["timestamp"],
418            json!(10),
419            "grow-only: the checkpointed earliest writer keeps the slot"
420        );
421        assert_eq!(
422            reconstructed.log_entries(&Surface::Routing.tag()).len(),
423            3,
424            "multiset: 2 checkpointed observations (incl. the repeat) + 1 tail"
425        );
426        let ema = |s: f64, rec: &FoldedRecord| {
427            0.7 * s + 0.3 * rec.payload["sample"].as_f64().unwrap()
428        };
429        assert_eq!(
430            reconstructed.replay(&Surface::Routing.tag(), 0.5_f64, ema),
431            full.replay(&Surface::Routing.tag(), 0.5_f64, ema),
432            "order-sensitive replay agrees across the compaction"
433        );
434
435        // And the composition is verifiable: the checkpoint anchors the tail.
436        verify_anchored(&plan.checkpoint, &plan.retained_ops).unwrap();
437    }
438
439    #[test]
440    fn retention_coherence_local_compaction_equals_global() {
441        // The proposal's "local compaction is just an eager application of
442        // the same retention the checkpoint applies globally — the two can
443        // never disagree": retention(fold_onto(retained ckpt, tail)) ==
444        // retention(fold(full)).
445        let (ops, split) = all_surface_ops();
446        let acks = acks_at(&ops, split);
447        let policy = RetentionPolicy::proposal_default(1, u64::MAX);
448        let as_of = 1_000u64;
449        let plan = plan_compaction(&ops, &acks, &policy, Some(as_of)).unwrap();
450        assert_eq!(plan.as_of_ms, as_of, "explicit as_of wins over the derived default");
451
452        let (global, _) = apply_retention(&fold(&ops), &policy, as_of).unwrap();
453        let (local, _) = apply_retention(
454            &fold_onto(&plan.checkpoint.state, &plan.retained_ops),
455            &policy,
456            as_of,
457        )
458        .unwrap();
459        assert_eq!(local, global);
460        assert_eq!(state_hash(&local), state_hash(&global));
461        // The retained checkpoint really did trim: only the newest turn
462        // survives conversations' last-1 rule (turns are content-hash-keyed
463        // — no id — so the trimmed one drops without a stub).
464        assert_eq!(plan.checkpoint.state.logs[&Surface::Conversation.tag()].len(), 1);
465    }
466
467    #[test]
468    fn retention_coherence_survives_cross_frontier_supersedes() {
469        // Kernel-review repro: LastN{1} knowledge drops f1 at compaction
470        // time; a LATER tail op f3 supersedes f1. Under
471        // preserve-only-what's-referenced-now, the global fold retained f1
472        // (it sees f3's reference) while the compacted device could not —
473        // divergence under identical policy + as_of. Universal tombstone
474        // stubs close the time hole: both sides hold the same f1 stub.
475        let mut a = DeviceLog::new("a");
476        let mut b = DeviceLog::new("b");
477        let mut ops = vec![
478            a.append(Scope::Personal, Surface::Knowledge, json!({"id": "f1", "timestamp": 1})),
479            a.append(Scope::Personal, Surface::Knowledge, json!({"id": "f2", "timestamp": 2})),
480        ];
481        let split = ops.len();
482        for op in &ops {
483            b.observe(&op.hlc);
484        }
485        ops.push(b.append(
486            Scope::Personal,
487            Surface::Knowledge,
488            json!({"id": "f3", "timestamp": 3, "supersedes": "f1"}),
489        ));
490
491        let acks = acks_at(&ops, split);
492        let mut policy = RetentionPolicy::keep_all();
493        policy
494            .rules
495            .insert("knowledge".to_string(), RetentionRule::LastN { n: 1 });
496        let plan = plan_compaction(&ops, &acks, &policy, Some(10)).unwrap();
497        assert_eq!(plan.dropped_ops, split);
498        let tag = Surface::Knowledge.tag();
499        // The checkpoint stubbed f1 BEFORE anything referenced it…
500        assert!(is_tombstone(&plan.checkpoint.state.logs[&tag]["id:f1"]));
501
502        // …and the coherence equivalence holds ACROSS the late reference.
503        let (global, _) = apply_retention(&fold(&ops), &policy, 10).unwrap();
504        let (local, _) = apply_retention(
505            &fold_onto(&plan.checkpoint.state, &plan.retained_ops),
506            &policy,
507            10,
508        )
509        .unwrap();
510        assert_eq!(local, global, "no divergence despite the cross-frontier supersedes");
511        assert_eq!(state_hash(&local), state_hash(&global));
512        // f3 is live, its supersedes target resolves against the f1 stub on
513        // BOTH sides — a tombstone, not a hole.
514        assert_eq!(global.logs[&tag]["id:f3"].payload["supersedes"], json!("f1"));
515        assert!(is_tombstone(&global.logs[&tag]["id:f1"]));
516        assert!(is_tombstone(&local.logs[&tag]["id:f1"]));
517    }
518
519    #[test]
520    fn crash_ordering_checkpoint_durable_first_then_truncate() {
521        // Simulate a crash between the two durable steps and prove no
522        // acknowledged data can be lost at any point.
523        let dir = tempfile::tempdir().unwrap();
524        let journal_path = dir.path().join("oplog.jsonl");
525        let ckpt_dir = dir.path().join("checkpoints");
526        let (ops, split) = all_surface_ops();
527        let acks = acks_at(&ops, split);
528        let policy = RetentionPolicy::keep_all();
529
530        {
531            let mut journal = OplogJournal::open(&journal_path).unwrap();
532            for op in &ops {
533                journal.append(op).unwrap();
534            }
535
536            // Step 1+2: plan and persist the checkpoint… then "crash"
537            // before truncation (we simply don't truncate).
538            let plan = plan_compaction(&OplogJournal::load(&journal_path).unwrap(), &acks, &policy, None).unwrap();
539            let ckpt_path = plan.checkpoint.save(&ckpt_dir).unwrap();
540
541            // Post-"crash" state: the journal is UNTOUCHED (full data,
542            // no truncation marker — the normal load path still works),
543            // and the checkpoint is valid but redundant. Nothing lost.
544            let survived = OplogJournal::load(&journal_path).unwrap();
545            assert_eq!(survived, ops, "journal intact after crash-before-truncate");
546            let ckpt = Checkpoint::load(&ckpt_path).unwrap();
547            assert_eq!(fold_onto(&ckpt.state, &plan.retained_ops), fold(&ops));
548        } // journal lock released — "process died"
549
550        // "Restart": rerun the whole compaction. Idempotent — the same
551        // frontier recomputes the same content-addressed checkpoint file —
552        // and now the truncation completes.
553        let mut journal = OplogJournal::open(&journal_path).unwrap();
554        let outcome = compact_and_truncate(&mut journal, &ckpt_dir, &acks, &policy, None).unwrap();
555        assert_eq!(outcome.plan.dropped_ops, split);
556
557        // The truncated journal is marked: the naive load path is a runtime
558        // error, and the marker names the covering checkpoint.
559        assert!(OplogJournal::load(&journal_path).is_err(), "naive load is fenced");
560        let (marker, tail) = OplogJournal::load_with_marker(&journal_path).unwrap();
561        assert_eq!(
562            marker.unwrap().checkpoint_hash,
563            outcome.plan.checkpoint.checkpoint_hash,
564            "marker names the covering checkpoint"
565        );
566        assert_eq!(tail, ops[split..].to_vec());
567        verify_log(&tail).expect("truncated journal verifies on its own (anchored non-zero start)");
568        let ckpt = Checkpoint::load(&outcome.checkpoint_path.unwrap()).unwrap();
569        verify_anchored(&ckpt, &tail).unwrap();
570        assert_eq!(fold_onto(&ckpt.state, &tail), fold(&ops), "nothing acknowledged was lost");
571
572        // Exactly one checkpoint file exists (the rerun deduped on content).
573        let count = std::fs::read_dir(&ckpt_dir).unwrap().count();
574        assert_eq!(count, 1);
575    }
576
577    #[test]
578    fn truncated_journal_resumes_and_keeps_verifying_end_to_end() {
579        let dir = tempfile::tempdir().unwrap();
580        let journal_path = dir.path().join("oplog.jsonl");
581        let ckpt_dir = dir.path().join("checkpoints");
582        let (ops, split) = all_surface_ops();
583        let acks = acks_at(&ops, split);
584
585        let mut journal = OplogJournal::open(&journal_path).unwrap();
586        for op in &ops {
587            journal.append(op).unwrap();
588        }
589        let outcome =
590            compact_and_truncate(&mut journal, &ckpt_dir, &acks, &RetentionPolicy::keep_all(), None)
591                .unwrap();
592        let ckpt = Checkpoint::load(&outcome.checkpoint_path.unwrap()).unwrap();
593
594        // Life goes on after truncation: resume the device chain from
595        // checkpoint + tail (never from seq 0 — DeviceLog::resume is fenced
596        // and refuses the truncated tail at runtime), append, journal,
597        // reload.
598        let (_, tail) = OplogJournal::load_with_marker(&journal_path).unwrap();
599        assert!(matches!(
600            DeviceLog::resume("dev-a", &tail),
601            Err(ChainError::TruncatedChain { .. })
602        ));
603        let mut dev_a = resume_anchored("dev-a", &ckpt, &tail).unwrap();
604        let next = dev_a.append(Scope::Personal, Surface::Knowledge, json!({"id": "f-new"}));
605        journal.append(&next).unwrap();
606
607        let (marker, reloaded) = OplogJournal::load_with_marker(&journal_path).unwrap();
608        assert!(marker.is_some(), "marker survives post-truncation appends");
609        verify_anchored(&ckpt, &reloaded).expect("checkpoint anchors the growing truncated log");
610        let full_plus = {
611            let mut v = ops.clone();
612            v.push(next);
613            v
614        };
615        assert_eq!(fold_onto(&ckpt.state, &reloaded), fold(&full_plus));
616    }
617
618    // ------------------------------------------------------------------
619    // B3 integration: relay transport + roster + eviction + re-entry.
620    // ------------------------------------------------------------------
621
622    use crate::session::SyncSession;
623    use std::sync::atomic::{AtomicU64, Ordering};
624    use std::sync::Arc;
625
626    fn manual_clock() -> (Arc<AtomicU64>, WallClock) {
627        let t = Arc::new(AtomicU64::new(0));
628        let reader = t.clone();
629        (t, Arc::new(move || reader.load(Ordering::SeqCst)))
630    }
631
632    fn session(device: &str, root: &std::path::Path, wall: WallClock) -> SyncSession {
633        SyncSession::open(
634            device,
635            &root.join(device).join("oplog.jsonl"),
636            &root.join(device).join("checkpoints"),
637            wall,
638        )
639        .unwrap()
640    }
641
642    #[test]
643    fn two_macs_converge_through_the_filesystem_loopback_relay() {
644        // The realistic single-user case: two DeviceLogs syncing through a
645        // shared directory, real HLC wall clocks with skew between them.
646        let tmp = tempfile::tempdir().unwrap();
647        let relay_dir = tmp.path().join("shared-relay");
648        let (ta, wall_a) = manual_clock();
649        let (tb, wall_b) = manual_clock();
650        let (tr, wall_r) = manual_clock();
651        ta.store(1_000, Ordering::SeqCst);
652        tb.store(940, Ordering::SeqCst); // 60ms of skew
653        tr.store(970, Ordering::SeqCst);
654
655        // Each Mac holds its own FsRelay handle on the shared dir — state
656        // travels through the files, never through shared memory.
657        let mut relay_a = FsRelay::open(&relay_dir, RelayConfig::default(), wall_r.clone()).unwrap();
658        let mut relay_b = FsRelay::open(&relay_dir, RelayConfig::default(), wall_r).unwrap();
659        let mut a = session("mac-a", tmp.path(), wall_a);
660        let mut b = session("mac-b", tmp.path(), wall_b);
661
662        a.append(Scope::Personal, Surface::Knowledge, json!({"id": "f1", "v": 1})).unwrap();
663        a.append(Scope::Personal, Surface::Declagent, json!({"id": "milo", "owner": "a"})).unwrap();
664        b.append(Scope::Personal, Surface::Routing, json!({"sample": 1.0})).unwrap();
665        b.append(Scope::Personal, Surface::Conversation, json!({"speaker": "u", "text": "hi", "timestamp": 5})).unwrap();
666
667        a.pump(&mut relay_a).unwrap();
668        b.pump(&mut relay_b).unwrap();
669        // b writes after folding a's record; despite b's slower wall clock
670        // the HLC orders it causally after (receive rule).
671        b.append(Scope::Personal, Surface::Declagent, json!({"id": "milo", "owner": "b"})).unwrap();
672        b.pump(&mut relay_b).unwrap();
673        a.pump(&mut relay_a).unwrap();
674
675        assert_eq!(a.state_hash(), b.state_hash());
676        assert_eq!(
677            a.state().registries[&Surface::Declagent.tag()]["id:milo"].payload["owner"],
678            json!("b"),
679            "causality beats wall-clock skew"
680        );
681        // The journals themselves verify end-to-end.
682        verify_log(a.ops()).unwrap();
683        verify_log(b.ops()).unwrap();
684    }
685
686    #[test]
687    fn straggler_eviction_and_lossless_cold_reentry() {
688        // The full stragglers arc from the proposal: three devices, c goes
689        // dark holding UNPUSHED local writes → evicted at the horizon →
690        // frontier unpinned → checkpoint + relay GC → c returns, its pull
691        // is FrontierTruncated → cold re-entry (checkpoint_get + pull since
692        // the checkpoint frontier + resume_anchored) carrying its unpushed
693        // ops → it pushes them (chain-valid) → everyone converges.
694        let tmp = tempfile::tempdir().unwrap();
695        let (t, wall) = manual_clock();
696        let mut relay = InMemoryRelay::new(
697            RelayConfig { eviction_horizon_ms: Some(1_000) },
698            wall.clone(),
699        );
700        let mut a = session("dev-a", tmp.path(), wall.clone());
701        let mut b = session("dev-b", tmp.path(), wall.clone());
702        let mut c = session("dev-c", tmp.path(), wall.clone());
703
704        // t=100: everyone writes, pumps, acks.
705        t.store(100, Ordering::SeqCst);
706        a.append(Scope::Personal, Surface::Knowledge, json!({"id": "a1", "timestamp": 100})).unwrap();
707        c.append(Scope::Personal, Surface::Knowledge, json!({"id": "c1", "timestamp": 100})).unwrap();
708        a.pump(&mut relay).unwrap();
709        c.pump(&mut relay).unwrap();
710        b.pump(&mut relay).unwrap();
711        a.pump(&mut relay).unwrap();
712        c.pump(&mut relay).unwrap();
713        assert_eq!(a.state_hash(), c.state_hash());
714
715        // t=500: c writes LOCALLY (journal-durable, never pushed) and goes
716        // dark.
717        t.store(500, Ordering::SeqCst);
718        let unpushed = c
719            .append(Scope::Personal, Surface::Knowledge, json!({"id": "c-dark", "timestamp": 500}))
720            .unwrap();
721
722        // t=800..2000: a and b keep working; c stays silent.
723        t.store(800, Ordering::SeqCst);
724        a.append(Scope::Personal, Surface::Knowledge, json!({"id": "a2", "timestamp": 800})).unwrap();
725        a.pump(&mut relay).unwrap();
726        b.pump(&mut relay).unwrap();
727        a.pump(&mut relay).unwrap();
728
729        // c's stale ack pins the frontier while it is still active.
730        let pinned = relay.stable_frontier().unwrap().unwrap();
731
732        // t=2000: past the horizon (last seen 500) — the sweep on any
733        // contact evicts c and the frontier advances past its stale ack.
734        t.store(2_000, Ordering::SeqCst);
735        a.pump(&mut relay).unwrap();
736        b.pump(&mut relay).unwrap();
737        let roster: std::collections::BTreeMap<String, RosterEntry> = relay
738            .roster()
739            .unwrap()
740            .into_iter()
741            .map(|e| (e.device_id.clone(), e))
742            .collect();
743        assert_eq!(roster["dev-c"].status, DeviceStatus::Evicted);
744        let unpinned = relay.stable_frontier().unwrap().unwrap();
745        assert!(unpinned > pinned, "the evicted device's ack no longer holds the frontier");
746
747        // a checkpoints at the stable frontier and the relay GCs. Before a
748        // covering checkpoint exists, NOTHING drops even below the frontier.
749        assert_eq!(relay.gc().unwrap().total(), 0, "no covering checkpoint → no GC");
750        let ckpt = a.publish_checkpoint(&mut relay).unwrap().unwrap();
751        let report = relay.gc().unwrap();
752        assert!(report.total() > 0, "covered + below-frontier ops now drop");
753        // Ops above the stable frontier never drop, covered or not.
754        let mut since = Frontier::new();
755        for (device, entry) in &ckpt.frontier {
756            since.insert(device.clone(), entry.seq);
757        }
758        for op in relay.pull("dev-a", &since).unwrap().ops {
759            assert!(op.hlc > unpinned || ckpt.frontier.get(&op.device_id).is_none_or(|e| op.seq > e.seq));
760        }
761
762        // t=3000: c returns. Its normal pump hits truncated space → the
763        // cold bootstrap signal. NOTE the pump pushes BEFORE it pulls, so
764        // even this failed round already delivered c's journal-durable
765        // unpushed op to the relay (chain-valid against c's GC'd chain
766        // anchor) — contract 1 makes that safe at any time.
767        t.store(3_000, Ordering::SeqCst);
768        let err = c.pump(&mut relay).unwrap_err();
769        assert!(
770            matches!(err, SessionError::Relay(RelayError::FrontierTruncated { .. })),
771            "got {err:?}"
772        );
773        assert!(
774            relay
775                .pull("dev-a", &{
776                    let mut f = since.clone();
777                    f.insert("dev-c".to_string(), 0);
778                    f
779                })
780                .unwrap()
781                .ops
782                .iter()
783                .any(|op| op.op_id == unpushed.op_id),
784            "the failed pump's push half already landed the unpushed op"
785        );
786
787        // Cold re-entry: rebase onto the checkpoint. The unpushed local op
788        // SURVIVES the rebase (uncovered by the checkpoint frontier)…
789        assert!(c.rebase(&mut relay).unwrap());
790        assert_eq!(c.base().unwrap().checkpoint_hash, ckpt.checkpoint_hash);
791        assert!(
792            c.ops().iter().any(|op| op.op_id == unpushed.op_id),
793            "the straggler's unpushed write survives cold re-entry"
794        );
795        // …and the naive resume path is fenced on c's rebased journal.
796        let c_journal = tmp.path().join("dev-c").join("oplog.jsonl");
797        assert!(OplogJournal::load(&c_journal).is_err(), "truncation marker fences load()");
798
799        // c pumps: its unpushed op is re-offered (the push cursor reset on
800        // rebase) and dedups against the failed round's delivery — pushed
801        // exactly once overall — then c acks at the new frontier →
802        // reinstated.
803        let report = c.pump(&mut relay).unwrap();
804        assert_eq!(
805            (report.pushed, report.push_deduped),
806            (0, 1),
807            "the unpushed op reached the relay exactly once"
808        );
809        let roster: std::collections::BTreeMap<String, RosterEntry> = relay
810            .roster()
811            .unwrap()
812            .into_iter()
813            .map(|e| (e.device_id.clone(), e))
814            .collect();
815        assert_eq!(roster["dev-c"].status, DeviceStatus::Active, "caught-up ack reinstates");
816
817        // c's late op has an OLD hlc (below the stable frontier) but is not
818        // GC-eligible: no checkpoint covers its seq yet.
819        assert!(unpushed.hlc < relay.stable_frontier().unwrap().unwrap());
820        assert_eq!(relay.gc().unwrap().total(), 0, "late op is safe until a checkpoint covers it");
821
822        // Everyone pulls c's late write and converges — lossless re-entry.
823        a.pump(&mut relay).unwrap();
824        b.pump(&mut relay).unwrap();
825        assert_eq!(a.state_hash(), b.state_hash());
826        assert_eq!(a.state_hash(), c.state_hash());
827        assert!(a
828            .state()
829            .logs[&Surface::Knowledge.tag()]
830            .contains_key("id:c-dark"));
831
832        // Chain validity end to end: every journal still proves itself.
833        verify_log(a.ops()).unwrap();
834        verify_log(b.ops()).unwrap();
835        verify_anchored(c.base().unwrap(), c.ops()).unwrap();
836    }
837
838    #[test]
839    fn replay_over_permuted_opsets_is_deterministic() {
840        // The routing rule ("sync the observations, not the result"): an
841        // order-sensitive injected fold (EMA-like) over the hlc-ordered
842        // observation stream yields the same value from any delivery order.
843        let mut a = DeviceLog::new("dev-a");
844        let mut b = DeviceLog::new("dev-b");
845        let mut ops = vec![
846            a.append(Scope::Personal, Surface::Routing, json!({"sample": 1.0})),
847            a.append(Scope::Personal, Surface::Routing, json!({"sample": 0.0})),
848        ];
849        for op in &ops {
850            b.observe(&op.hlc);
851        }
852        ops.push(b.append(Scope::Personal, Surface::Routing, json!({"sample": 1.0})));
853
854        let ema = |state: f64, rec: &FoldedRecord| {
855            0.7 * state + 0.3 * rec.payload["sample"].as_f64().unwrap()
856        };
857        let folded = fold(&ops);
858        // Multiset guard: the third observation is byte-identical to the
859        // first and must still be a distinct event (this test previously
860        // passed while silently losing it).
861        assert_eq!(folded.log_entries(&Surface::Routing.tag()).len(), 3);
862        let baseline = folded.replay(&Surface::Routing.tag(), 0.5_f64, ema);
863        // 0.5 →(1.0) 0.65 →(0.0) 0.455 →(1.0) 0.6185
864        assert!((baseline - 0.6185).abs() < 1e-12, "got {baseline}");
865        for perm in permutations(&ops) {
866            assert_eq!(fold(&perm).replay(&Surface::Routing.tag(), 0.5_f64, ema), baseline);
867        }
868    }
869}