From d2bfda8178247de978b7b7624720dfeb3f2f97c7 Mon Sep 17 00:00:00 2001 From: Dennis Kobert Date: Fri, 25 Sep 2026 08:55:07 +0000 Subject: [PATCH] Retire closed transactions per author on a policy instead of everything at the host's gesture, keeping open transactions hot --- document/format/src/lib.rs | 17 ++ document/format/src/network.rs | 6 + document/format/src/persist.rs | 156 ++++++++++---- document/graph-storage/src/crdt.rs | 3 + document/graph-storage/src/document.rs | 28 +-- document/graph-storage/src/session.rs | 191 +++++++++++++++--- .../graph-storage/src/tests/bookkeeping.rs | 90 ++++++++- document/graph-storage/src/tests/crdt.rs | 16 +- document/graph-storage/src/touched.rs | 2 +- document/peer-transport/tests/simulation.rs | 82 ++++++-- .../portfolio/document/document_history.rs | 20 +- .../document/document_message_handler.rs | 7 +- .../storage_tests/round_trip_tests.rs | 4 +- .../portfolio/sync/sync_message_handler.rs | 22 ++ 14 files changed, 538 insertions(+), 106 deletions(-) diff --git a/document/format/src/lib.rs b/document/format/src/lib.rs index 7e00d30fb9..34b72efbf8 100644 --- a/document/format/src/lib.rs +++ b/document/format/src/lib.rs @@ -98,6 +98,14 @@ pub struct Gdd { /// with the registry without rebuilding it. #[cfg(feature = "network")] pub(crate) remote_changes: network::RemoteChanges, + /// When each closed transaction was first seen here, by its marker, so the retirement policy can age + /// it. Not persisted: after a reopen everything pending is old enough. + pub(crate) transactions_seen: std::collections::HashMap, + /// When this peer last staged an op, so an open transaction the editor never closed can be closed + /// once it has gone quiet. + pub(crate) own_last_staged_ms: Option, + /// Whether an op of this peer's own was staged since the last policy tick. + pub(crate) own_staged_since_tick: bool, } /// Whole-file rewrites the sync path defers to the end of a poll, so one batch of remote packets costs @@ -126,6 +134,9 @@ impl Clone for Gdd { pending_persist: PendingPersist::default(), #[cfg(feature = "network")] remote_changes: network::RemoteChanges::default(), + transactions_seen: Default::default(), + own_last_staged_ms: None, + own_staged_since_tick: false, } } } @@ -221,6 +232,9 @@ impl Gdd { pending_persist: PendingPersist::default(), #[cfg(feature = "network")] remote_changes: network::RemoteChanges::default(), + transactions_seen: Default::default(), + own_last_staged_ms: None, + own_staged_since_tick: false, }) } @@ -250,6 +264,9 @@ impl Gdd { pending_persist: PendingPersist::default(), #[cfg(feature = "network")] remote_changes: network::RemoteChanges::default(), + transactions_seen: Default::default(), + own_last_staged_ms: None, + own_staged_since_tick: false, }) } } diff --git a/document/format/src/network.rs b/document/format/src/network.rs index 50cff2c52f..1d2050635e 100644 --- a/document/format/src/network.rs +++ b/document/format/src/network.rs @@ -49,7 +49,13 @@ impl Gdd { self.network = Some(Replica::guest(transport, self.session.peer(), user)); } + /// Leaves the room. A host retires every closed transaction first, so what peers finished is in + /// history before the retirer goes away. pub fn leave(&mut self) { + let closed = self.session.retirable(&self.session.closed_transactions()); + if let Err(error) = self.retire_transactions(&closed) { + log::error!("Retiring before leaving failed: {error}"); + } if let Some(mut replica) = self.network.take() { replica.leave(); } diff --git a/document/format/src/persist.rs b/document/format/src/persist.rs index 2a34dcbd42..51cff1bf11 100644 --- a/document/format/src/persist.rs +++ b/document/format/src/persist.rs @@ -102,6 +102,9 @@ impl Gdd { /// Every staged hot op takes this path, whether it came from a recorded batch, a whole-document diff or /// a raw op: the frame that survives a crash, then the broadcast that reaches the room. fn persist_staged(&mut self, hot_ops: &[HotOp]) -> Result<(), Error> { + if hot_ops.iter().any(|hot_op| !matches!(hot_op.op, RegistryDelta::EndTransaction)) { + self.own_staged_since_tick = true; + } for hot_op in hot_ops { self.append_hot_frame(hot_op)?; } @@ -112,17 +115,6 @@ impl Gdd { Ok(()) } - /// Retire every pending hot op into durable history as a single interaction (marking the batch's last - /// delta as the interaction boundary), then re-snapshot the registry. One interaction is one undo unit, - /// so the caller invokes this at each undo-step boundary and before any undo/redo. A no-op when there - /// are no pending hot ops. - pub fn retire_pending_interaction(&mut self) -> Result, Error> { - let Some(up_to) = self.session.hot_log().iter().map(|hot_op| hot_op.timestamp).max() else { - return Ok(Vec::new()); - }; - self.retire_inner(up_to, true) - } - /// Commit a runtime snapshot as one complete interaction: stage it, then immediately retire it into /// durable history. Convenience for callers that produce a whole interaction atomically (tests, and any /// one-shot commit). Equivalent to [`stage_runtime_snapshot`](Self::stage_runtime_snapshot) followed @@ -152,18 +144,28 @@ impl Gdd { Ok(()) } - /// Persist freshly-staged hot ops and immediately retire them into durable history. Appends each - /// hot frame (so a crash before retirement still recovers the work), then retires up to the last - /// staged timestamp, which drains exactly these ops and re-snapshots the registry. Returns the - /// retired `Rev`s. A no-op when nothing was staged. + /// Persist freshly-staged hot ops and immediately retire exactly them into durable history as one unit. + /// Appends each hot frame first, so a crash before retirement still recovers the work. Returns the + /// retired `Rev`s. A no-op when nothing was staged, and the ops stay hot on a peer that does not retire. pub(crate) fn append_and_retire(&mut self, hot_ops: &[HotOp], interaction_end: bool) -> Result, Error> { - let Some(last) = hot_ops.last() else { return Ok(Vec::new()) }; - + if hot_ops.is_empty() { + return Ok(Vec::new()); + } for hot_op in hot_ops { self.append_hot_frame(hot_op)?; } + if !self.retires_locally() { + return Ok(Vec::new()); + } - self.retire_inner(last.timestamp, interaction_end) + let ids: Vec<_> = hot_ops.iter().map(HotOp::id).collect(); + let revs = self.session.retire_hot_ops(&ids)?; + // Marked before the history frames are written, so the boundary is on disk with them. + if interaction_end && let Some(&last) = revs.last() { + self.session.mark_interaction_end(last); + } + self.finish_retirement(&revs, &ids)?; + Ok(revs) } /// Encode the history deltas identified by `revs` and append them to the history file. `revs` comes @@ -259,29 +261,108 @@ impl Gdd { Ok(()) } - /// Working-copy checkpoint: promote hot ops with timestamp `≤ up_to` into retired deltas, - /// append them to the history file, rewrite the hot log with remaining (unretired) ops, and - /// re-snapshot the registry. Synchronous. - pub fn retire(&mut self, up_to: TimeStamp) -> Result, Error> { - self.retire_inner(up_to, false) + /// How many closed transactions have to be waiting before they retire. Later retirement fuses more + /// of a gesture's ops into one delta and keeps more of what an undo can still rewind silently. + pub const RETIRE_AFTER_TRANSACTIONS: usize = 10; + /// How long a closed transaction sits before it may retire, so every peer has seen all of it. + pub const RETIRE_MIN_AGE_MS: f64 = 2_000.0; + /// How long anything waits at most: a quiet session still retires, and a transaction with a gap in + /// its author's run retires with what arrived. + pub const RETIRE_MAX_AGE_MS: f64 = 60_000.0; + + /// Closes this peer's open transaction, if it has one, with a marker that reaches the room like any + /// other hot op. The editor calls this at each undo-step boundary. + pub fn end_transaction(&mut self) -> Result<(), Error> { + if let Some(marker) = self.session.end_transaction()? { + self.persist_staged(&[marker])?; + } + Ok(()) } - /// `interaction_end`: mark the batch's last delta as an interaction boundary (one undo unit) before its - /// history frame is written, so the marker persists on reopen without a later frame rewrite. - fn retire_inner(&mut self, up_to: TimeStamp, interaction_end: bool) -> Result, Error> { + /// Retire every transaction the policy says is due at `now_ms`, on any monotonic millisecond clock the + /// caller keeps: closed transactions that have waited [`RETIRE_MIN_AGE_MS`](Self::RETIRE_MIN_AGE_MS), + /// once [`RETIRE_AFTER_TRANSACTIONS`](Self::RETIRE_AFTER_TRANSACTIONS) of them are waiting or the oldest + /// has waited [`RETIRE_MAX_AGE_MS`](Self::RETIRE_MAX_AGE_MS). An open transaction never retires, whoever + /// its author is. Called once a frame by the editor; a peer that does not retire only closes its own + /// transaction here once it has gone quiet for the minimum age. + pub fn retire_due(&mut self, now_ms: f64) -> Result, Error> { + // A gesture the editor never closed, or one interrupted by a reopen, closes on its own once quiet. + if self.own_staged_since_tick { + self.own_staged_since_tick = false; + self.own_last_staged_ms = Some(now_ms); + } else if self.own_last_staged_ms.is_some_and(|last| now_ms - last >= Self::RETIRE_MIN_AGE_MS) { + self.end_transaction()?; + self.own_last_staged_ms = None; + } if !self.retires_locally() { return Ok(Vec::new()); } - #[cfg(feature = "network")] - let retired_hot_ops = self.session.hot_ops_up_to(up_to); - let new_revs = self.session.retire(up_to)?; - - // Mark before `append_history_deltas` so the on-disk frame carries the boundary. - if interaction_end && let Some(&last) = new_revs.last() { - self.session.mark_interaction_end(last); + let closed = self.session.closed_transactions(); + let mut seen = std::mem::take(&mut self.transactions_seen); + let mut due = Vec::new(); + let mut oldest_age: f64 = 0.0; + for transaction in &closed { + let Some(&marker) = transaction.ops.last() else { continue }; + let age = now_ms - *seen.entry(marker).or_insert(now_ms); + if age >= Self::RETIRE_MIN_AGE_MS && (transaction.contiguous || age >= Self::RETIRE_MAX_AGE_MS) { + due.push(transaction.clone()); + oldest_age = oldest_age.max(age); + } } + seen.retain(|marker, _| closed.iter().any(|transaction| transaction.ops.last() == Some(marker))); + self.transactions_seen = seen; + let due = self.session.retirable(&due); + if due.len() >= Self::RETIRE_AFTER_TRANSACTIONS || oldest_age >= Self::RETIRE_MAX_AGE_MS { + self.retire_transactions(&due) + } else { + Ok(Vec::new()) + } + } + + /// Close this peer's open transaction and retire every closed transaction, whoever its author is, + /// leaving other authors' open ones hot. The undo path takes this before moving the cursor, so the + /// interaction being undone is in history; a peer that does not retire only closes its own. + pub fn retire_pending_interaction(&mut self) -> Result, Error> { + self.end_transaction()?; + self.own_last_staged_ms = None; + let closed = self.session.retirable(&self.session.closed_transactions()); + self.retire_transactions(&closed) + } + + /// Retire the given closed transactions, each as one interaction, in one history append and one + /// broadcast. A no-op for a peer that leaves retirement to the session host. + pub fn retire_transactions(&mut self, transactions: &[document_graph_storage::ClosedTransaction]) -> Result, Error> { + if !self.retires_locally() || transactions.is_empty() { + return Ok(Vec::new()); + } + let mut revs = Vec::new(); + let mut retired_hot_ops = Vec::new(); + for transaction in transactions { + revs.extend(self.session.retire_transaction(transaction)?); + retired_hot_ops.extend(transaction.ops.iter().copied()); + } + self.finish_retirement(&revs, &retired_hot_ops)?; + Ok(revs) + } + + /// Working-copy checkpoint over a timestamp: promote every hot op stamped at or before `up_to` into + /// retired deltas, whatever its author and whether or not its transaction is closed. For callers + /// that own the whole log; a session retires by [`retire_transactions`](Self::retire_transactions). + pub fn retire(&mut self, up_to: TimeStamp) -> Result, Error> { + if !self.retires_locally() { + return Ok(Vec::new()); + } + let retired_hot_ops = self.session.hot_ops_up_to(up_to); + let revs = self.session.retire(up_to)?; + self.finish_retirement(&revs, &retired_hot_ops)?; + Ok(revs) + } + + /// What every retirement ends with: the published frontier moves, the deltas reach the history file, + /// the hot log and snapshot are rewritten, and the room hears about it. + fn finish_retirement(&mut self, new_revs: &[Rev], retired_hot_ops: &[document_graph_storage::HotOpId]) -> Result<(), Error> { // In a session these deltas are about to reach peers, so the published frontier moves with them. // Rewinding a commit peers already hold would diverge from them for good, with nothing on the wire // to tell them, so undo past this point has to go through forward inverse ops instead. Set before @@ -294,7 +375,7 @@ impl Gdd { } if !new_revs.is_empty() { - self.append_history_deltas(&new_revs)?; + self.append_history_deltas(new_revs)?; } self.rewrite_hot_log()?; @@ -304,12 +385,13 @@ impl Gdd { #[cfg(feature = "network")] if let Some(replica) = &mut self.network { let deltas: Vec<_> = new_revs.iter().filter_map(|&rev| self.session.delta(rev).cloned()).collect(); - replica.broadcast_retired(&deltas, &retired_hot_ops)?; + replica.broadcast_retired(&deltas, retired_hot_ops)?; } + #[cfg(not(feature = "network"))] + let _ = retired_hot_ops; - Ok(new_revs) + Ok(()) } - /// Guests leave retirement to the session host and keep their hot ops until the host's retired /// deltas arrive. fn retires_locally(&self) -> bool { diff --git a/document/graph-storage/src/crdt.rs b/document/graph-storage/src/crdt.rs index 888e60dab2..f06d865881 100644 --- a/document/graph-storage/src/crdt.rs +++ b/document/graph-storage/src/crdt.rs @@ -206,6 +206,9 @@ pub enum RegistryDelta { Merge { extra_parents: Vec, }, + /// The last op of its author's transaction. Changes nothing; retirement takes an author's ops through + /// one of these as one unit and drops the marker itself. See [`Session::closed_transactions`](crate::Session::closed_transactions). + EndTransaction, // Allow for future delta types without a model change Other(serde_json::Value), } diff --git a/document/graph-storage/src/document.rs b/document/graph-storage/src/document.rs index 67c4b45638..8bcd47a10b 100644 --- a/document/graph-storage/src/document.rs +++ b/document/graph-storage/src/document.rs @@ -139,10 +139,14 @@ impl Document { } /// 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. + /// ahead of the delta carrying the op into history, stranding its effect in the working registry. A + /// transaction marker is the exception: no delta ever carries it, so its mark is all there is. 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)); + self.hot_log.retain(|hot_op| { + let marker = matches!(hot_op.op, RegistryDelta::EndTransaction); + !(self.history.contains_timestamp(hot_op.timestamp) || (marker && self.retired.covers(hot_op.id()))) + }); before != self.hot_log.len() } @@ -334,20 +338,19 @@ impl Document { } RegistryDelta::AddSource { id, key, source } => { upsert_resource(registry, id, timestamp, force, |entry| { - let value = SourceValue { source, timestamp }; + let value = SourceValue { source, timestamp, deleted: false }; if force { entry.force_set_source(key, value) } else { entry.set_source(key, value) } }); } RegistryDelta::RemoveSource { id, key } => { - // A source removal names nothing to create the entry from; one for an entry never seen is dropped. - let missing = || CrdtError::ResourceDoesNotExist(id); - let _ = write(&mut registry.resources, &mut registry.removed_resources, id, timestamp, force, missing, |entry| { + // An upsert like the other single-source ops: a removal for an entry never seen leaves the + // source's tombstone in a fresh entry, so the addition it answers is recognised as older. + upsert_resource(registry, id, timestamp, force, |entry| { if force { entry.force_remove_source(&key); } else { entry.remove_source(&key, timestamp); } - Ok(()) }); } RegistryDelta::AddResource { id, entry } => { @@ -367,7 +370,7 @@ impl Document { apply_attribute_delta(delta, timestamp, force, &mut registry.attributes, TimeStamp::ORIGIN); } // Merge is a structural sync point only; it mutates no registry state. - RegistryDelta::Merge { .. } | RegistryDelta::Other(_) => {} + RegistryDelta::Merge { .. } | RegistryDelta::EndTransaction | RegistryDelta::Other(_) => {} } Ok(()) } @@ -474,6 +477,7 @@ impl Document { RegistryDelta::AddResource { id, entry: snapshot } } RegistryDelta::Merge { extra_parents } => RegistryDelta::Merge { extra_parents: extra_parents.clone() }, + RegistryDelta::EndTransaction => RegistryDelta::EndTransaction, &RegistryDelta::Other(_) => RegistryDelta::Other(serde_json::Value::Null), }) } @@ -566,18 +570,14 @@ impl Presence for ResourceEntry { fn stamp_all(&mut self, at: TimeStamp) { self.presence = at; self.hash_timestamp = at; - for (_, value) in &mut self.sources { - value.timestamp = at; - } + self.stamp_sources(at); } fn merge(&mut self, other: Self) { if other.hash_timestamp > self.hash_timestamp { self.hash = other.hash; self.hash_timestamp = other.hash_timestamp; } - for (key, value) in other.sources { - self.set_source(key, value); - } + self.merge_sources(other.sources, other.sources_timestamp); self.presence = self.presence.max(other.presence); } } diff --git a/document/graph-storage/src/session.rs b/document/graph-storage/src/session.rs index 5606df463f..8d2a8e7b0b 100644 --- a/document/graph-storage/src/session.rs +++ b/document/graph-storage/src/session.rs @@ -276,19 +276,6 @@ impl Session { self.document.replay_hot_op(hot_op) } - /// The hot ops a `retire(up_to)` call would drain. Sent with the deltas for peers to drop exactly - /// these; the cutoff alone doesn't transfer, a lagging op can arrive below it afterwards. - pub fn hot_ops_up_to(&self, up_to: TimeStamp) -> Vec { - self.document.hot_log[..self.retirement_prefix(up_to)].iter().map(HotOp::id).collect() - } - - /// How much of the hot log `retire(up_to)` drains: everything through the last op stamped at or - /// before `up_to`. A prefix of the log rather than the ops under the cutoff, so retirement commits - /// them in the order the working registry applied them. An op stamped later that sits earlier in the log goes with the prefix. - fn retirement_prefix(&self, up_to: TimeStamp) -> usize { - self.document.hot_log.iter().rposition(|hot_op| hot_op.timestamp <= up_to).map_or(0, |last| last + 1) - } - /// Drop hot ops another peer has retired without retiring them locally. The registries need nothing: /// each op's effect is a function of its timestamp, so the working registry holds the same fold with /// or without the hot copy of an op whose delta has landed. @@ -400,22 +387,128 @@ impl Session { Ok(outcome) } - /// Promote the hot-log prefix through the last op stamped at or before `up_to` into retired deltas, - /// each keeping the timestamp it was authored at. See [`retirement_prefix`](Self::retirement_prefix) - /// for why the prefix and not the ops under the cutoff. - /// - /// 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 prefix = self.retirement_prefix(up_to); - let drained: Vec = self.document.hot_log.drain(..prefix).collect(); - self.document.mark_retired(drained.iter().map(HotOp::id)); + /// Closes this peer's open transaction with a [`RegistryDelta::EndTransaction`] marker, so the retirer + /// can take the ops before it as one unit. `None` when nothing is open: an author's transaction is + /// open once it has an op past its last marker. + pub fn end_transaction(&mut self) -> Result, CrdtError> { + let peer = self.document.peer; + let open = self + .document + .hot_log + .iter() + .rev() + .find(|hot_op| hot_op.timestamp.peer == peer) + .is_some_and(|hot_op| !matches!(hot_op.op, RegistryDelta::EndTransaction)); + if !open { + return Ok(None); + } + Ok(self.stage_ops([RegistryDelta::EndTransaction])?.pop()) + } - let revs = self.commit_ops_authored_at(drained.into_iter().map(|hot_op| (hot_op.op, Some(hot_op.timestamp))), true)?; + /// Every author's closed transactions in the hot log, the earliest closed first. An author's ops past + /// its last marker are its open transaction and never appear here, whoever the author is, so a gesture + /// in progress stays hot while a later one from someone else retires: every op commutes, so the order + /// transactions retire in does not bear on the registry. + pub fn closed_transactions(&self) -> Vec { + let mut by_author: HashMap> = HashMap::new(); + for hot_op in &self.document.hot_log { + by_author.entry(hot_op.timestamp.peer).or_default().push(hot_op); + } + let mut closed = Vec::new(); + for (author, mut ops) in by_author { + ops.sort_by_key(|hot_op| hot_op.sequence); + let mut expected = self.document.retired.retired_up_to.get(&author).copied().unwrap_or(HotSequence::NONE).next(); + let mut current = Vec::new(); + let mut contiguous = true; + for hot_op in ops { + // An op retired past a gap is not in the log and not missing either. + while expected < hot_op.sequence && self.document.retired.covers(HotOpId { peer: author, sequence: expected }) { + expected = expected.next(); + } + contiguous &= hot_op.sequence == expected; + expected = hot_op.sequence.next(); + current.push(hot_op.id()); + if matches!(hot_op.op, RegistryDelta::EndTransaction) { + closed.push(ClosedTransaction { + author, + ops: std::mem::take(&mut current), + closed_at: hot_op.timestamp, + contiguous, + }); + contiguous = true; + } + } + } + closed.sort_by_key(|transaction| transaction.closed_at); + closed + } + + /// The subsequence of `closed` that can retire now, in order: a transaction is held back while it + /// refers to an entity the retired snapshot has never seen and no transaction ahead of it adds, + /// which is one still sitting in another author's open transaction. Applying it would land a write + /// on an unknown target, the one thing the registry defers rather than resolves. + pub fn retirable(&self, closed: &[ClosedTransaction]) -> Vec { + let snapshot = &self.document.retired_snapshot; + let mut nodes: HashSet = snapshot.node_instances.keys().chain(snapshot.removed_nodes.keys()).copied().collect(); + let mut networks: HashSet = snapshot.networks.keys().chain(snapshot.removed_networks.keys()).copied().collect(); + let by_id: HashMap = self.document.hot_log.iter().map(|hot_op| (hot_op.id(), hot_op)).collect(); + + let mut retirable = Vec::new(); + for transaction in closed { + let mut nodes_after = nodes.clone(); + let mut networks_after = networks.clone(); + let ops = transaction.ops.iter().filter_map(|id| by_id.get(id)).map(|hot_op| &hot_op.op); + if ops.clone().all(|op| op_referents_known(op, &mut nodes_after, &mut networks_after)) { + nodes = nodes_after; + networks = networks_after; + retirable.push(transaction.clone()); + } + } + retirable + } + /// Retire one closed transaction as one interaction: its ops become retired deltas in the author's + /// order, each keeping its authoring stamp, the marker commits nothing, and the last delta is marked as + /// the interaction's end. Returns the new revs. + pub fn retire_transaction(&mut self, transaction: &ClosedTransaction) -> Result, CrdtError> { + let revs = self.retire_hot_ops(&transaction.ops)?; + if let Some(&last) = revs.last() { + self.mark_interaction_end(last); + } Ok(revs) } + /// The hot ops stamped at or before `up_to`, which is what [`retire`](Self::retire) drains. Sent with + /// the deltas for peers to drop exactly these; the cutoff alone doesn't transfer, a lagging op can + /// arrive below it afterwards. + pub fn hot_ops_up_to(&self, up_to: TimeStamp) -> Vec { + self.document.hot_log.iter().filter(|hot_op| hot_op.timestamp <= up_to).map(HotOp::id).collect() + } + + /// Promote the given hot ops into retired deltas, in hot-log order, each keeping the timestamp it was + /// authored at. Markers commit nothing. Ops not in the log are ignored. + /// + /// Today: one retired delta per hot op. Coarsening is a future step. + pub fn retire_hot_ops(&mut self, ids: &[HotOpId]) -> Result, CrdtError> { + let wanted: HashSet = ids.iter().copied().collect(); + let (drained, kept): (Vec, Vec) = self.document.hot_log.drain(..).partition(|hot_op| wanted.contains(&hot_op.id())); + self.document.hot_log = kept; + self.document.mark_retired(drained.iter().map(HotOp::id)); + + let ops = drained + .into_iter() + .filter(|hot_op| !matches!(hot_op.op, RegistryDelta::EndTransaction)) + .map(|hot_op| (hot_op.op, Some(hot_op.timestamp))); + self.commit_ops_authored_at(ops, true) + } + + /// Promote every hot op stamped at or before `up_to`, whatever its author and whether or not its + /// transaction is closed. For callers that own the whole log, tests mostly; a session retires by + /// [`retire_transaction`](Self::retire_transaction). + pub fn retire(&mut self, up_to: TimeStamp) -> Result, CrdtError> { + let ids = self.hot_ops_up_to(up_to); + self.retire_hot_ops(&ids) + } /// Mark a retired delta as the end of a user interaction, so the undo cursor treats it as a checkpoint. /// Called once per interaction by the editor-facing commit path (not by resource/internal commits). pub fn mark_interaction_end(&mut self, rev: Rev) { @@ -856,3 +949,53 @@ pub enum CrdtError { #[error("Delta stored under {stored} hashes to {expected}")] RevMismatch { stored: Rev, expected: Rev }, } + +/// Whether every entity `op` writes to or refers to is in the sets, adding what the op itself brings into +/// being. Mirrors the cases in which [`Document::apply_op_with`] errors on an entity never seen. +fn op_referents_known(op: &RegistryDelta, nodes: &mut HashSet, networks: &mut HashSet) -> bool { + let input_known = |input: &crate::NodeInput, nodes: &HashSet| match input { + crate::NodeInput::Node { id, .. } => nodes.contains(id), + _ => true, + }; + match op { + RegistryDelta::AddNode { id, node } => { + let known = networks.contains(&node.network); + nodes.insert(*id); + known + } + RegistryDelta::RemoveNode { id, .. } => { + nodes.insert(*id); + true + } + RegistryDelta::SetNodeInputs { id, inputs } => nodes.contains(id) && inputs.iter().all(|slot| input_known(&slot.input, nodes)), + RegistryDelta::ChangeNodeInput { id, new_input, .. } => nodes.contains(id) && input_known(new_input, nodes), + RegistryDelta::SetNodeImplementation { id, implementation } => { + nodes.contains(id) + && match implementation { + Implementation::Network(network) => networks.contains(network), + Implementation::ProtoNode(_) => true, + } + } + RegistryDelta::ChangeNodeAttribute { id, .. } | RegistryDelta::ChangeNodeInputAttribute { id, .. } => nodes.contains(id), + RegistryDelta::SetNetworkExport { id, export, .. } => networks.contains(id) && export.as_ref().is_none_or(|input| input_known(input, nodes)), + RegistryDelta::AddNetwork { id, .. } | RegistryDelta::RemoveNetwork { id, .. } => { + networks.insert(*id); + true + } + RegistryDelta::ChangeNetworkAttribute { id, .. } => networks.contains(id), + _ => true, + } +} + +/// An author's closed transaction sitting in the hot log, as [`Session::closed_transactions`] lists them. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ClosedTransaction { + pub author: PeerId, + /// Every op of the transaction in the author's order, the closing marker last. + pub ops: Vec, + /// When the author closed it: the marker's stamp. + pub closed_at: TimeStamp, + /// Whether every op from the author's retired frontier through the marker is here. One with a gap is + /// waiting on a re-announcement; retiring it anyway commits what arrived. + pub contiguous: bool, +} diff --git a/document/graph-storage/src/tests/bookkeeping.rs b/document/graph-storage/src/tests/bookkeeping.rs index 9b6153f924..01a6f4de3e 100644 --- a/document/graph-storage/src/tests/bookkeeping.rs +++ b/document/graph-storage/src/tests/bookkeeping.rs @@ -120,11 +120,10 @@ fn a_batch_off_an_earlier_delta_is_sorted_into_place() { assert_eq!(a.document.history.tips(), scanned_tips(&a.document.history)); } -/// Retirement takes a prefix of the hot log, in the order the working registry applied it, rather than -/// every op under the cutoff. An op stamped later than the cutoff but applied earlier goes with the -/// prefix, so the snapshot folds in the same order and the zones agree. +/// Retirement takes the ops under the cutoff whatever order the log applied them in: every op commutes, +/// so the snapshot folds to the working registry's values with a later-stamped op left hot. #[test] -fn retirement_drains_a_hot_log_prefix_in_applied_order() { +fn retirement_takes_the_ops_under_the_cutoff_in_any_applied_order() { let mut host = Session::with_peer(PeerId(1)); // A guest's op stamped late sits first in the log, ahead of an op stamped earlier: the log is in // arrival order, and stamps are the authors' clocks, not the arrival order. @@ -138,14 +137,89 @@ fn retirement_drains_a_hot_log_prefix_in_applied_order() { timestamp: crate::TimeStamp { counter: 20, peer: PeerId(3) }, sequence: crate::HotSequence(1), }; - host.apply_hot_op(late).expect("the late-stamped op lands first"); + host.apply_hot_op(late.clone()).expect("the late-stamped op lands first"); host.apply_hot_op(own.clone()).expect("the earlier-stamped op lands second"); - let would_retire = host.hot_ops_up_to(own.timestamp); - assert_eq!(would_retire.len(), 2, "the prefix through the earlier-stamped op includes the later-stamped op before it"); + assert_eq!(host.hot_ops_up_to(own.timestamp).len(), 1, "only the op under the cutoff retires"); host.retire(own.timestamp).expect("retire"); + assert_eq!(host.hot_log().len(), 1, "the later-stamped op stays hot"); + assert!(!host.retired_registry().networks.contains_key(&NetworkId(9))); + assert!(host.registry().networks.contains_key(&NetworkId(9))); + assert!(host.retired_registry().attributes.get("x").is_some_and(|value| !value.deleted)); + + host.retire(late.timestamp).expect("retire the rest"); assert!(host.hot_log().is_empty()); assert!(host.registry().value_equal(host.retired_registry())); - assert!(host.retired_registry().networks.contains_key(&NetworkId(9))); +} + +/// A transaction closes with a marker its author stages, and only closed transactions retire: an author's +/// ops past its last marker stay hot however old they are, while a later transaction from someone else +/// retires around them. +#[test] +fn only_closed_transactions_retire_and_an_open_one_stays_hot() { + let mut host = Session::with_peer(PeerId(1)); + let guest_op = |counter: u64, sequence: u64, op: RegistryDelta| crate::HotOp { + op, + timestamp: crate::TimeStamp { counter, peer: PeerId(2) }, + sequence: crate::HotSequence(sequence), + }; + + assert!(host.end_transaction().expect("nothing to close").is_none(), "no op of this peer is open"); + + // The guest opens a transaction and leaves it open, stamped earlier than everything the host does. + host.apply_hot_op(guest_op(10, 1, add_network(9))).expect("guest op"); + host.apply_hot_op(guest_op(11, 2, set_attribute("guest", 1))).expect("guest op"); + + host.stage_ops([set_attribute("host", 1)]).expect("host op"); + let marker = host.end_transaction().expect("close").expect("the host's transaction was open"); + assert!(matches!(marker.op, RegistryDelta::EndTransaction)); + assert!(host.end_transaction().expect("nothing more to close").is_none(), "closing twice stages nothing"); + + let closed = host.closed_transactions(); + assert_eq!(closed.len(), 1, "the guest's open transaction is not listed: {closed:?}"); + assert_eq!(closed[0].author, PeerId(1)); + assert!(closed[0].contiguous); + assert_eq!(closed[0].ops.len(), 3, "RegisterPeer, the attribute write and the marker"); + + let revs = host.retire_transaction(&closed[0]).expect("retire"); + assert_eq!(revs.len(), 2, "the marker commits no delta"); + assert!(host.history().any(|delta| delta.id == revs[1] && delta.is_interaction_end()), "the transaction is one interaction"); + assert_eq!(host.hot_log().len(), 2, "the guest's ops stay hot"); + assert!(host.hot_log().iter().all(|hot_op| hot_op.timestamp.peer == PeerId(2))); + assert!(!host.retired_registry().networks.contains_key(&NetworkId(9))); + assert!(host.registry().networks.contains_key(&NetworkId(9))); + + // The guest closes: its transaction retires after the host's although it is stamped before it. + host.apply_hot_op(guest_op(12, 3, RegistryDelta::EndTransaction)).expect("guest marker"); + let closed = host.closed_transactions(); + assert_eq!(closed.len(), 1); + assert_eq!(closed[0].author, PeerId(2)); + host.retire_transaction(&closed[0]).expect("retire"); + assert!(host.hot_log().is_empty()); + assert!(host.registry().value_equal(host.retired_registry())); + assert!(host.document.history.extends_canonically(0), "retirement order is the parent chain, so history stays append-only"); +} + +/// A transaction with a gap in its author's run is listed as not contiguous, so the retirer can wait for +/// the re-announcement, and closes normally once the gap fills. +#[test] +fn a_transaction_with_a_gap_is_not_contiguous_until_the_gap_fills() { + let mut host = Session::with_peer(PeerId(1)); + let guest_op = |counter: u64, sequence: u64, op: RegistryDelta| crate::HotOp { + op, + timestamp: crate::TimeStamp { counter, peer: PeerId(2) }, + sequence: crate::HotSequence(sequence), + }; + host.apply_hot_op(guest_op(10, 1, add_network(9))).expect("guest op"); + host.apply_hot_op(guest_op(12, 3, RegistryDelta::EndTransaction)).expect("guest marker, op 2 still in flight"); + + let closed = host.closed_transactions(); + assert_eq!(closed.len(), 1); + assert!(!closed[0].contiguous); + + host.apply_hot_op(guest_op(11, 2, set_attribute("guest", 1))).expect("the late op"); + let closed = host.closed_transactions(); + assert!(closed[0].contiguous); + assert_eq!(closed[0].ops.len(), 3); } diff --git a/document/graph-storage/src/tests/crdt.rs b/document/graph-storage/src/tests/crdt.rs index 76ac4fec36..a0745ccae5 100644 --- a/document/graph-storage/src/tests/crdt.rs +++ b/document/graph-storage/src/tests/crdt.rs @@ -570,7 +570,10 @@ fn remove_source_reverse_restores_prior() { } document.apply_op(RD::RemoveSource { id, key }, ts(5, 1)).unwrap(); - assert!(document.working_registry.resources.get(&id).unwrap().sources.is_empty(), "source removed"); + assert!( + document.working_registry.resources.get(&id).unwrap().live_sources().next().is_none(), + "source removed, a tombstone left" + ); // Applying the reverse restores the chain. document.apply_op(reverse, ts(6, 1)).unwrap(); @@ -631,7 +634,15 @@ use crate::{ResourceEntry, ResourceStore, SourceValue}; fn entry_with_source(priority: f64, peer: u64, body: serde_json::Value, hash: Option) -> ResourceEntry { ResourceEntry { presence: ts(1, peer), - sources: vec![(source_key(priority, peer), SourceValue { source: body, timestamp: ts(1, peer) })], + sources: vec![( + source_key(priority, peer), + SourceValue { + source: body, + timestamp: ts(1, peer), + deleted: false, + }, + )], + sources_timestamp: TimeStamp::ORIGIN, hash, hash_timestamp: ts(1, peer), } @@ -682,6 +693,7 @@ fn compute_deltas_diffs_resources_and_round_trips() { SourceValue { source: serde_json::json!("url"), timestamp: ts(1, 1), + deleted: false, }, ); to.insert(kept, kept_entry); diff --git a/document/graph-storage/src/touched.rs b/document/graph-storage/src/touched.rs index d6145cd18d..340bc65d8b 100644 --- a/document/graph-storage/src/touched.rs +++ b/document/graph-storage/src/touched.rs @@ -52,7 +52,7 @@ impl Touched { RegistryDelta::AddResource { .. } | RegistryDelta::SetResourceHash { .. } | RegistryDelta::RemoveResource { .. } | RegistryDelta::AddSource { .. } | RegistryDelta::RemoveSource { .. } => { self.resources = true; } - RegistryDelta::RegisterPeer { .. } | RegistryDelta::ChangeDocumentAttribute { .. } | RegistryDelta::Merge { .. } | RegistryDelta::Other(_) => {} + RegistryDelta::RegisterPeer { .. } | RegistryDelta::ChangeDocumentAttribute { .. } | RegistryDelta::Merge { .. } | RegistryDelta::EndTransaction | RegistryDelta::Other(_) => {} } } diff --git a/document/peer-transport/tests/simulation.rs b/document/peer-transport/tests/simulation.rs index 672be856fa..31882ec962 100644 --- a/document/peer-transport/tests/simulation.rs +++ b/document/peer-transport/tests/simulation.rs @@ -4,8 +4,8 @@ //! Inspect one run with `SEED= GUESTS= cargo test -p peer-transport --test simulation inspect_seed -- --ignored --nocapture`. use document_graph_storage::{ - AttributeDelta, Delta, HotOp, HotOpId, Implementation, Network, NetworkId, Node, NodeId, NodeInput, PeerId, Priority, Registry, RegistryDelta, ResourceHash, ResourceId, RetiredHotOps, Rev, - Session, SourceKey, TimeStamp, UserId, + AttributeDelta, Delta, HotOp, HotOpId, HotSequence, Implementation, Network, NetworkId, Node, NodeId, NodeInput, PeerId, Priority, Registry, RegistryDelta, ResourceHash, ResourceId, + RetiredHotOps, Rev, Session, SourceKey, TimeStamp, UserId, }; use peer_transport::mock::{MockEndpoint, MockNetwork}; use peer_transport::{Event, Replica, Role, SyncTarget, TargetError, TransportPeerId}; @@ -133,6 +133,9 @@ struct Peer { transport: TransportPeerId, /// Gone for good, unlike a rejoin. Its document stops taking part and stops being asserted on. departed: bool, + /// The sequence of the marker closing this peer's latest transaction, `NONE` before the first. Nothing + /// past it may ever retire. + last_closed: HotSequence, } impl Peer { @@ -150,6 +153,7 @@ impl Peer { user, transport, departed: false, + last_closed: HotSequence::NONE, } } @@ -201,16 +205,31 @@ impl Peer { self.retire_up_to(up_to); } - /// Retire only part of the hot log, leaving newer ops live. A later op of one author can then retire - /// while an earlier one is still in flight, which is what puts entries above the retired prefix. - fn retire_prefix(&mut self, nth: usize) { - let mut timestamps: Vec = self.target.session.hot_log().iter().map(|hot_op| hot_op.timestamp).collect(); - if timestamps.is_empty() { + /// Close this peer's open transaction, the way the editor does at an undo-step boundary. + fn end_transaction(&mut self) { + if let Some(marker) = self.target.session.end_transaction().expect("end transaction") { + self.last_closed = marker.sequence; + self.replica.broadcast_hot_ops(&[marker]).expect("broadcast"); + } + } + + /// Retire up to `count` of the closed transactions in the hot log, the earliest closed first, as the + /// policy does. Open transactions stay hot, so a later transaction of one author retires while an + /// earlier one of another is still in progress. + fn retire_closed(&mut self, count: usize) { + let contiguous: Vec<_> = self.target.session.closed_transactions().into_iter().filter(|transaction| transaction.contiguous).collect(); + let closed: Vec<_> = self.target.session.retirable(&contiguous).into_iter().take(count).collect(); + let mut revs = Vec::new(); + let mut retired_hot_ops = Vec::new(); + for transaction in &closed { + revs.extend(self.target.session.retire_transaction(transaction).expect("retire")); + retired_hot_ops.extend(transaction.ops.iter().copied()); + } + if retired_hot_ops.is_empty() { return; } - timestamps.sort(); - - self.retire_up_to(timestamps[nth.min(timestamps.len() - 1)]); + let deltas: Vec<_> = revs.iter().filter_map(|&rev| self.target.session.delta(rev).cloned()).collect(); + self.replica.broadcast_retired(&deltas, &retired_hot_ops).expect("broadcast retired"); } fn retire_up_to(&mut self, up_to: TimeStamp) { @@ -440,6 +459,10 @@ fn simulate(seed: u64, guest_count: usize, steps: usize) -> (MockNetwork, Vec { let op = random_op(&mut network, &peers[index].target); peers[index].stage(op); + // A gesture is a few ops long; closing it is what lets it retire. + if network.random_below(3) == 0 { + peers[index].end_transaction(); + } } // A small pool of distinct payloads, so peers sometimes introduce the same resource // concurrently and sometimes one nobody else can serve. @@ -448,10 +471,12 @@ fn simulate(seed: u64, guest_count: usize, steps: usize) -> (MockNetwork, Vec {} - // Mostly a partial retire, so the host's history lags its hot log the way a real one does. + // A few closed transactions at a time, so the host's history lags its hot log the way a real one + // does, and never an open one. 3 => { - let nth = network.random_below(4); - peers[0].retire_prefix(nth); + let count = 1 + network.random_below(4); + peers[0].retire_closed(count); + assert_open_transactions_stay_hot(seed, &peers); } 4..=7 => { network.step(); @@ -473,6 +498,14 @@ fn simulate(seed: u64, guest_count: usize, steps: usize) -> (MockNetwork, Vec> for DocumentMes } // Note: A transaction should never be started in a scope that mutates the network interface, since it will only be run after that scope ends. DocumentMessage::StartTransaction => { - self.retire_storage_interaction(); + self.end_storage_transaction(); self.network_interface.start_transaction(); self.history.push_undo(self.network_interface.clone()); @@ -2039,6 +2039,11 @@ impl DocumentMessageHandler { self.refresh_resource_registry(); } + /// Close the open storage transaction at an undo-step boundary. + pub(crate) fn end_storage_transaction(&mut self) { + self.history.end_storage_transaction(); + } + /// Retire the pending staged hot ops into durable Gdd history as one undo unit. pub(crate) fn retire_storage_interaction(&mut self) { self.history.retire_storage_interaction(); diff --git a/editor/src/messages/portfolio/document/storage_tests/round_trip_tests.rs b/editor/src/messages/portfolio/document/storage_tests/round_trip_tests.rs index 0e1a4c1e07..09aec67ee2 100644 --- a/editor/src/messages/portfolio/document/storage_tests/round_trip_tests.rs +++ b/editor/src/messages/portfolio/document/storage_tests/round_trip_tests.rs @@ -716,8 +716,10 @@ async fn demo_artwork_edit_autosaves_and_round_trips() { let after_edit = editor.active_document().network_interface.document_network().clone(); assert_ne!(before_edit, after_edit, "drawing a rectangle should change the document network"); - // Second autosave: again verifies the round-trip, and the edit must produce new retired history. + // Second autosave: again verifies the round-trip, and the edit, once its transaction is closed and + // retired, must produce new retired history. Retirement follows a policy rather than the commit. editor.active_document_mut().commit_storage_snapshot(&byte_store, true); + editor.active_document_mut().retire_storage_interaction(); let history_after_edit = editor.active_document().storage().unwrap().session().history().count(); assert!( history_after_edit > history_after_open, diff --git a/editor/src/messages/portfolio/sync/sync_message_handler.rs b/editor/src/messages/portfolio/sync/sync_message_handler.rs index f5aa074a5c..18ca416c63 100644 --- a/editor/src/messages/portfolio/sync/sync_message_handler.rs +++ b/editor/src/messages/portfolio/sync/sync_message_handler.rs @@ -102,6 +102,13 @@ impl MessageHandler> for SyncMessageHandler SyncMessage::Poll => { let resources = resource_storage.resources_mut(); for (&document_id, document) in documents.iter_mut() { + // Retirement follows the working copy's policy on every document, in a session or not: closed + // transactions retire once enough have waited long enough, never on a gesture. + if let Some(gdd) = document.storage_mut() + && let Err(error) = gdd.retire_due(now_ms()) + { + log::error!("Retirement failed: {error}"); + } if document.storage().is_none_or(|gdd| gdd.role().is_none()) { continue; } @@ -228,3 +235,18 @@ fn random_token_bytes() -> [u8; 16] { bytes[8..].copy_from_slice(&generate_uuid().to_le_bytes()); bytes } + +/// A monotonic-enough millisecond clock for the retirement policy, which only ever compares differences. +fn now_ms() -> f64 { + #[cfg(target_arch = "wasm32")] + { + js_sys::Date::now() + } + #[cfg(not(target_arch = "wasm32"))] + { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|elapsed| elapsed.as_secs_f64() * 1000.) + .unwrap_or(0.) + } +}