Retire closed transactions per author on a policy instead of everything at the host's gesture, keeping open transactions hot

This commit is contained in:
Dennis Kobert committed 2026-09-25 08:55:07 +00:00
1 parent f18becb21b
commit d2bfda8178
14 files changed
+538 -106

No files matched your search

+17
View File
@@ -98,6 +98,14 @@ pub struct Gdd<L: Layout = GddV1Layout> {
/// 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<document_graph_storage::HotOpId, f64>,
/// 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<f64>,
/// 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<L: Layout + Clone> Clone for Gdd<L> {
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<L: Layout> Gdd<L> {
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<L: Layout> Gdd<L> {
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,
})
}
}
+6
View File
@@ -49,7 +49,13 @@ impl<L: Layout> Gdd<L> {
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();
}
+119 -37
View File
@@ -102,6 +102,9 @@ impl<L: Layout> Gdd<L> {
/// 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<L: Layout> Gdd<L> {
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<Vec<Rev>, 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<L: Layout> Gdd<L> {
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<Vec<Rev>, 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<L: Layout> Gdd<L> {
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<Vec<Rev>, 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<Vec<Rev>, 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<Vec<Rev>, 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<Vec<Rev>, 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<Vec<Rev>, 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<Vec<Rev>, 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<L: Layout> Gdd<L> {
}
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<L: Layout> Gdd<L> {
#[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 {
+3
View File
@@ -206,6 +206,9 @@ pub enum RegistryDelta {
Merge {
extra_parents: Vec<Rev>,
},
/// 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),
}
+14 -14
View File
@@ -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);
}
}
+167 -24
View File
@@ -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<HotOpId> {
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<Vec<Rev>, 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<HotOp> = 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<Option<HotOp>, 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<ClosedTransaction> {
let mut by_author: HashMap<PeerId, Vec<&HotOp>> = 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<ClosedTransaction> {
let snapshot = &self.document.retired_snapshot;
let mut nodes: HashSet<NodeId> = snapshot.node_instances.keys().chain(snapshot.removed_nodes.keys()).copied().collect();
let mut networks: HashSet<NetworkId> = snapshot.networks.keys().chain(snapshot.removed_networks.keys()).copied().collect();
let by_id: HashMap<HotOpId, &HotOp> = 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<Vec<Rev>, 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<HotOpId> {
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<Vec<Rev>, CrdtError> {
let wanted: HashSet<HotOpId> = ids.iter().copied().collect();
let (drained, kept): (Vec<HotOp>, Vec<HotOp>) = 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<Vec<Rev>, 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<NodeId>, networks: &mut HashSet<NetworkId>) -> bool {
let input_known = |input: &crate::NodeInput, nodes: &HashSet<NodeId>| 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<HotOpId>,
/// 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,
}
@@ -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);
}
+14 -2
View File
@@ -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<ResourceHash>) -> 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);
+1 -1
View File
@@ -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(_) => {}
}
}
+69 -13
View File
@@ -4,8 +4,8 @@
//! Inspect one run with `SEED=<n> GUESTS=<n> 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<TimeStamp> = 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<Pe
0..=2 if peers[index].replica.is_synced() => {
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<Pe
peers[index].stage_resource(bytes);
}
0..=2 | 8 => {}
// 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<Pe
}
quiesce(&mut network, &mut peers);
for peer in peers.iter_mut().filter(|peer| !peer.departed) {
peer.end_transaction();
}
quiesce(&mut network, &mut peers);
peers[0].retire_closed(usize::MAX);
assert_open_transactions_stay_hot(seed, &peers);
quiesce(&mut network, &mut peers);
// What departed peers left open retires with everything else, so the end state is checked in full.
peers[0].retire();
quiesce(&mut network, &mut peers);
@@ -515,6 +548,29 @@ fn dump_if_requested(seed: u64, peers: &[Peer]) {
/// orders, the working registry in arrival order and the snapshot in canonical history order, and
/// structural ops carry no timestamp to arbitrate that, so whatever drops a hot op the snapshot now
/// covers owes a refold. Compared by value, since a refold re-stamps what it replays.
/// Nothing past an author's last closing marker is in any peer's retired marks: an open transaction stays
/// hot however old it is and however many later ones from other authors retired around it.
fn assert_open_transactions_stay_hot(seed: u64, peers: &[Peer]) {
for (index, peer) in peers.iter().enumerate().filter(|(_, peer)| !peer.departed) {
let marks = peer.session().retired_marks();
for author in peers {
let through = marks.retired_up_to.get(&author.peer).copied().unwrap_or(HotSequence::NONE);
let beyond = marks
.retired_beyond
.get(&author.peer)
.and_then(|runs| runs.iter().map(|&(_, end)| end).max())
.unwrap_or(HotSequence::NONE);
assert!(
through <= author.last_closed && beyond <= author.last_closed,
"seed {seed}: peer {index} retired op {:?} of {:?} past its last closed transaction {:?}",
through.max(beyond),
author.peer,
author.last_closed
);
}
}
}
fn assert_zones_agree(seed: u64, peers: &[Peer]) {
for (index, peer) in peers.iter().enumerate().filter(|(_, peer)| !peer.departed) {
if !peer.session().hot_log().is_empty() {
@@ -117,9 +117,19 @@ impl DocumentHistory {
self.needs_whole_document_stage = true;
}
/// Retire the pending staged hot ops into durable Gdd history as one undo unit. Called at each undo-step
/// boundary (a new `StartTransaction`) and before undo/redo, so the per-`CommitTransaction` staging
/// coalesces into one interaction aligned with the legacy step. No-op while unmounted.
/// Close the open storage transaction at an undo-step boundary (a new `StartTransaction`), so the
/// per-`CommitTransaction` staging since the last boundary is one unit for retirement and undo, aligned
/// with the legacy step. Retirement itself follows the working copy's policy. No-op while unmounted.
pub fn end_storage_transaction(&mut self) {
let Some(storage) = self.storage.as_mut() else { return };
if let Err(error) = storage.end_transaction() {
log::error!("Closing the storage transaction failed: {error}");
}
}
/// Close this peer's open transaction and retire every closed one into durable Gdd history, so the
/// interaction being undone is in history. Called before undo/redo and after the first commit of a
/// newly mounted document. No-op while unmounted.
pub fn retire_storage_interaction(&mut self) {
let Some(storage) = self.storage.as_mut() else { return };
if let Err(error) = storage.retire_pending_interaction() {
@@ -129,8 +139,8 @@ impl DocumentHistory {
/// Stage a `CommitTransaction` into the `Gdd` working copy: the first commit writes the whole document,
/// every later one stages the `deltas` the store recorded. No-op while unmounted. Proto-node declaration
/// bytes go into `byte_store` (the app-global resource cache). The staged hot ops are retired by
/// [`retire_storage_interaction`](Self::retire_storage_interaction) at undo-step boundaries.
/// bytes go into `byte_store` (the app-global resource cache). The staged hot ops are closed into one
/// transaction by [`end_storage_transaction`](Self::end_storage_transaction) at undo-step boundaries.
pub fn stage_snapshot(
&mut self,
deltas: &[EditorDelta],
@@ -1355,7 +1355,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> 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();
@@ -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,
@@ -102,6 +102,13 @@ impl MessageHandler<SyncMessage, SyncMessageContext<'_>> 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.)
}
}