From dc4fa940122db1d08eb13a03fdfecb4758600036 Mon Sep 17 00:00:00 2001 From: Dennis Kobert Date: Thu, 24 Sep 2026 00:36:01 +0200 Subject: [PATCH] Make a peer's working registry agree with its own retired snapshot --- document/graph-storage/src/document.rs | 19 +++++--- document/graph-storage/src/history.rs | 5 ++ document/graph-storage/src/session.rs | 56 ++++++++++++++++----- document/graph-storage/src/tests/crdt.rs | 62 ++++++++++++++++++++++++ 4 files changed, 123 insertions(+), 19 deletions(-) diff --git a/document/graph-storage/src/document.rs b/document/graph-storage/src/document.rs index b37b5330f3..dfda39e184 100644 --- a/document/graph-storage/src/document.rs +++ b/document/graph-storage/src/document.rs @@ -141,18 +141,21 @@ impl Document { self.drop_retired_hot_ops(); } - /// Take on a peer's retirement marks as well as this peer's. - pub(crate) fn absorb_retired(&mut self, remote: &RetiredHotOps) { + /// Take on a peer's retirement marks as well as this peer's. Returns whether a hot op was dropped, + /// which owes the caller a refold. + pub(crate) fn absorb_retired(&mut self, remote: &RetiredHotOps) -> bool { self.retired.absorb(remote); - self.drop_retired_hot_ops(); + self.drop_retired_hot_ops() } - /// Drop hot ops history already covers, whatever path put them in the log. - fn drop_retired_hot_ops(&mut self) { - let retired = std::mem::take(&mut self.retired); - self.hot_log.retain(|hot_op| !retired.covers(hot_op.id())); - self.retired = retired; + /// Drop hot ops the retired snapshot already accounts for. A mark alone will not do: it can arrive + /// ahead of the delta carrying the op into history, stranding its effect in the working registry. + fn drop_retired_hot_ops(&mut self) -> bool { + let before = self.hot_log.len(); + self.hot_log.retain(|hot_op| !self.history.contains_timestamp(hot_op.timestamp)); + + before != self.hot_log.len() } /// Apply a retired commit. Idempotent on structural ops (AddNode/AddNetwork on existing diff --git a/document/graph-storage/src/history.rs b/document/graph-storage/src/history.rs index fafa4a9e9c..941aef16b4 100644 --- a/document/graph-storage/src/history.rs +++ b/document/graph-storage/src/history.rs @@ -39,6 +39,11 @@ impl History { self.index.contains_key(&rev) } + /// Whether history holds a delta authored at `timestamp`. + pub fn contains_timestamp(&self, timestamp: TimeStamp) -> bool { + self.deltas.iter().any(|delta| delta.timestamp == timestamp) + } + pub fn len(&self) -> usize { self.deltas.len() } diff --git a/document/graph-storage/src/session.rs b/document/graph-storage/src/session.rs index 04765bfd90..eef3bb943c 100644 --- a/document/graph-storage/src/session.rs +++ b/document/graph-storage/src/session.rs @@ -196,11 +196,18 @@ impl Session { /// `idempotent`: pass `true` when the snapshot already reflects the op (retirement of an already- /// applied hot op) so duplicate structural inserts no-op rather than error. fn commit_ops(&mut self, ops: impl IntoIterator, idempotent: bool) -> Result, CrdtError> { + self.commit_ops_authored_at(ops.into_iter().map(|op| (op, None)), idempotent) + } + + /// [`commit_ops`](Self::commit_ops) for ops authored elsewhere, paired with the timestamp they were + /// authored at (`None` to mint one). The delta's timestamp is what the registry resolves LWW on, so + /// retirement passes the op's own; a coarsened delta passes the newest it fuses. + fn commit_ops_authored_at(&mut self, ops: impl IntoIterator)>, idempotent: bool) -> Result, CrdtError> { let target = RegistryTarget::Snapshot; let ops = ops.into_iter(); let mut produced = Vec::with_capacity(ops.size_hint().0); - for op in ops { + for (op, authored_at) in ops { // A new edit abandons any undone-forward branch: those revs stay in the DAG but are no // longer reachable via redo. (Mirrors the legacy editor clearing its redo history on // commit.) Done on the first real op so a no-op commit doesn't silently disable redo. @@ -211,9 +218,9 @@ impl Session { // The reverse must read the pre-op value of a target that may have been concurrently removed. self.document.ensure_referenced_exist(target, &op)?; let reverse = self.document.compute_reverse_delta(target, &op)?; - let timestamp = self.document.clock.tick(); + let timestamp = authored_at.unwrap_or_else(|| self.document.clock.tick()); let parent = self.document.head; - let author = self.document.peer; + let author = timestamp.peer; let delta = Delta::new(parent, author, timestamp, op, reverse); let rev = delta.id; @@ -296,11 +303,19 @@ impl Session { self.document.hot_log.iter().filter(|hot_op| hot_op.timestamp <= up_to).map(HotOp::id).collect() } - /// Drop hot ops another peer has retired without retiring them locally. - pub fn discard_hot_ops(&mut self, retired: &[HotOpId]) { + /// Drop hot ops another peer has retired without retiring them locally. Refolds like + /// [`absorb_retired_marks`](Self::absorb_retired_marks). + pub fn discard_hot_ops(&mut self, retired: &[HotOpId]) -> Result<(), CrdtError> { + let before = self.document.hot_log.len(); self.document.hot_log.retain(|hot_op| !retired.contains(&hot_op.id())); // How a peer that did not retire these learns they are in history now. self.document.mark_retired(retired.iter().copied()); + + if before != self.document.hot_log.len() { + self.refold_registries()?; + } + + Ok(()) } /// Which hot ops history already covers, for a peer catching up. See [`RetiredHotOps`]. @@ -308,9 +323,14 @@ impl Session { &self.document.retired } - /// See [`RetiredHotOps::absorb`]. - pub fn absorb_retired_marks(&mut self, remote: &RetiredHotOps) { - self.document.absorb_retired(remote); + /// See [`RetiredHotOps::absorb`]. A drop owes a refold, since the working registry holds the op's + /// effect in hot-log order where the snapshot holds it in canonical order. + pub fn absorb_retired_marks(&mut self, remote: &RetiredHotOps) -> Result<(), CrdtError> { + if self.document.absorb_retired(remote) { + self.refold_registries()?; + } + + Ok(()) } /// Replay a persisted hot op. Idempotent on structural ops, suitable for crash recovery @@ -431,25 +451,39 @@ impl Session { Ok(outcome) } - /// Promote hot ops with timestamp `≤ up_to` into retired deltas, re-applied with fresh - /// retirement timestamps so LWW arms bump field timestamps to `T_retire`. + /// Promote hot ops with timestamp `≤ up_to` into retired deltas, each keeping the timestamp it was + /// authored at. /// /// Today: one retired delta per hot op. Coarsening is a future step. pub fn retire(&mut self, up_to: TimeStamp) -> Result, CrdtError> { // Hot-log order is causal, so the deltas commit in an order their references survive. let mut drained = Vec::new(); let mut remaining = Vec::with_capacity(self.document.hot_log.len()); + + // Retiring by timestamp reorders against the hot-log order the working registry applied: past a + // skipped op, everything drained was applied here before it. + let mut skipped = false; + let mut reordered = false; for hot_op in self.document.hot_log.drain(..) { if hot_op.timestamp <= up_to { + reordered |= skipped; drained.push(hot_op); } else { + skipped = true; remaining.push(hot_op); } } self.document.hot_log = remaining; self.document.mark_retired(drained.iter().map(HotOp::id)); - self.commit_ops(drained.into_iter().map(|hot_op| hot_op.op), true) + let revs = self.commit_ops_authored_at(drained.into_iter().map(|hot_op| (hot_op.op, Some(hot_op.timestamp))), true)?; + + // Structural ops have no timestamp to arbitrate, so the reorder changes the outcome. + if reordered { + self.refold_registries()?; + } + + Ok(revs) } /// Mark a retired delta as the end of a user interaction, so the undo cursor treats it as a checkpoint. diff --git a/document/graph-storage/src/tests/crdt.rs b/document/graph-storage/src/tests/crdt.rs index e025cd1d9b..cb04ed8ab2 100644 --- a/document/graph-storage/src/tests/crdt.rs +++ b/document/graph-storage/src/tests/crdt.rs @@ -1194,3 +1194,65 @@ fn a_permanent_gap_accumulates_every_later_op() { } assert!(!marks.covers(id(1)), "the lost op is not claimed"); } + +/// A retired delta keeps its op's authoring timestamp, so the snapshot resolves LWW on the same stamps +/// the live view did rather than on retirement order. +#[test] +fn retirement_preserves_the_live_lww_winner() { + let mut host = Session::with_peer(PeerId(1)); + + // Same key from two authors, the newer op arriving first, so LWW keeps it and discards the older. + let newer = HotOp { + op: set_document_attribute("k", 1), + timestamp: TimeStamp { counter: 10, peer: PeerId(2) }, + sequence: crate::HotSequence(1), + }; + let older = HotOp { + op: set_document_attribute("k", 2), + timestamp: TimeStamp { counter: 5, peer: PeerId(3) }, + sequence: crate::HotSequence(1), + }; + host.apply_hot_op(newer.clone()).expect("apply newer"); + host.apply_hot_op(older).expect("apply older"); + + let live = host.registry().attributes.get("k").cloned(); + host.retire(newer.timestamp).expect("retire"); + + assert_eq!(host.registry().attributes.get("k"), live.as_ref(), "retirement must not move the live value"); + assert_eq!( + host.retired_registry().attributes.get("k").map(|attribute| &attribute.value), + live.as_ref().map(|attribute| &attribute.value), + "the snapshot has to record the value the live view settled on" + ); +} + +/// A straggler LWW discarded still retires, and must not return by doing so: stamped at retirement it +/// would outrank the op that beat it, putting the discarded value into history itself. +#[test] +fn retiring_a_straggler_leaves_the_discarded_value_behind() { + let mut host = Session::with_peer(PeerId(1)); + + let winner = HotOp { + op: set_document_attribute("k", 1), + timestamp: TimeStamp { counter: 10, peer: PeerId(2) }, + sequence: crate::HotSequence(1), + }; + host.apply_hot_op(winner.clone()).expect("apply winner"); + host.retire(winner.timestamp).expect("retire winner"); + + // Arriving behind the winner, this op loses in the live view and its value is dropped. + let straggler = HotOp { + op: set_document_attribute("k", 2), + timestamp: TimeStamp { counter: 5, peer: PeerId(3) }, + sequence: crate::HotSequence(1), + }; + host.apply_hot_op(straggler.clone()).expect("apply straggler"); + host.retire(straggler.timestamp).expect("retire straggler"); + + let value = |registry: &crate::Registry| registry.attributes.get("k").map(|attribute| attribute.value.clone()); + assert_eq!(value(host.registry()), Some(serde_json::json!(1)), "the live view keeps the winner"); + assert_eq!(value(host.retired_registry()), Some(serde_json::json!(1)), "and retiring the straggler must not overwrite it"); + + let replayed = host.snapshot_from_history().expect("refold"); + assert_eq!(value(&replayed), Some(serde_json::json!(1)), "nor may history replay to the discarded value"); +}