Index history for tips, timestamps and resource hashes, fast-forward chained merges, and fold snapshots in place

This commit is contained in:
Dennis Kobert committed 2026-09-24 20:07:18 +00:00
1 parent 710487160c
commit b12b692a2d
5 files changed
+300 -36

No files matched your search

+55 -1
View File
@@ -48,6 +48,18 @@ pub struct Document {
/// Counts the refolds that changed the working registry's values. See
/// [`Session::working_rederivations`](crate::Session::working_rederivations).
pub(crate) working_rederivations: u64,
/// Counts every refold run, changed values or not, for the tests that pin when one is skipped.
pub(crate) refolds: u64,
/// Set while [`fold_snapshot_from_history`](Self::fold_snapshot_from_history) replays, bounding what
/// resurrection may see.
pub(crate) fold: Option<FoldScope>,
}
/// What a fold in progress has in view: `head`'s ancestry, up to the delta being replayed.
#[derive(Clone, Debug)]
pub(crate) struct FoldScope {
pub(crate) reachable: std::collections::HashSet<Rev>,
pub(crate) horizon: usize,
}
impl Document {
@@ -80,12 +92,54 @@ impl Document {
/// The last match in canonical history order, over everything reachable from `head` or any tip. Not a
/// walk from `head`: peers sit on different merge revs, and resurrection must pick the same delta.
///
/// Inside a fold only the deltas already replayed are in view, so resurrection picks what it picked
/// when each delta first landed rather than a removal the replay has not reached.
fn find_in_ancestry(&self, predicate: impl Fn(&Delta) -> bool) -> Option<Delta> {
let reachable = self.history.ancestors(self.head.into_iter().chain(self.history.tips()));
if let Some(fold) = &self.fold {
return self
.history
.iter()
.take(fold.horizon)
.filter(|delta| fold.reachable.contains(&delta.id) && predicate(delta))
.last()
.cloned();
}
let reachable = self.history.ancestors(self.head.into_iter().chain(self.history.tips()));
self.history.iter().filter(|delta| reachable.contains(&delta.id) && predicate(delta)).last().cloned()
}
/// Folds `head`'s ancestry, in canonical order, into a fresh snapshot in place: no copy of history is
/// made, and the working registry, hot log and cursor are left alone. An undone delta stays in the DAG
/// for redo to find, and folding all of history would restore work the user undid.
pub(crate) fn fold_snapshot_from_history(&mut self) -> Result<Registry, CrdtError> {
let previous = std::mem::take(&mut self.retired_snapshot);
self.fold = Some(FoldScope {
reachable: self.history.ancestors(self.head),
horizon: 0,
});
let mut outcome = Ok(());
for position in 0..self.history.len() {
let delta = self.history.at(position).expect("position is in range");
let Some(fold) = &mut self.fold else { break };
if !fold.reachable.contains(&delta.id) {
continue;
}
fold.horizon = position;
let (kind, timestamp) = (delta.kind.clone(), delta.timestamp);
if let Err(error) = self.apply_op_with(RegistryTarget::Snapshot, kind, timestamp, ApplyMode::Idempotent) {
outcome = Err(error);
break;
}
}
self.fold = None;
let folded = std::mem::replace(&mut self.retired_snapshot, previous);
outcome.map(|()| folded)
}
/// Apply a delta's `reverse` as the new forward op (silent-zone undo). Force-applied: structural
/// ops are idempotent, and LWW arms assign the reverse value unconditionally even though it carries
/// the same timestamp as the forward op it undoes.
+61 -6
View File
@@ -10,14 +10,25 @@
use std::collections::{HashMap, HashSet};
use crate::{AttributesWrite, CrdtError, Delta, Rev, TimeStamp};
use crate::{AttributesWrite, CrdtError, Delta, RegistryDelta, ResourceHash, Rev, TimeStamp};
/// The indexes are maintained by every mutator, so the questions the per-frame and per-interaction
/// paths ask (is this timestamp retired, what are the tips, which hashes does history name) are probes
/// rather than scans of a history that only ever grows.
#[derive(Clone, Debug, Default)]
pub struct History {
/// Deltas in topological order. Mutated only via [`push`](Self::push).
deltas: Vec<Delta>,
/// `Rev` to its position in `deltas`. Kept in sync with `deltas` by every mutator.
index: HashMap<Rev, usize>,
/// The timestamps the deltas were authored at.
timestamps: HashSet<TimeStamp>,
/// Every rev some delta names as a parent.
referenced: HashSet<Rev>,
/// Deltas no other delta names as a parent.
tips: HashSet<Rev>,
/// Content hashes the deltas name, from resource additions and removals.
resource_hashes: HashSet<ResourceHash>,
}
impl History {
@@ -27,8 +38,11 @@ impl History {
/// Build from deltas already in topological order (the on-disk load path), indexing them in place.
pub fn from_ordered(deltas: Vec<Delta>) -> Self {
let index = deltas.iter().enumerate().map(|(position, delta)| (delta.id, position)).collect();
Self { deltas, index }
let mut history = Self::default();
for delta in deltas {
history.push(delta);
}
history
}
pub fn get(&self, rev: Rev) -> Option<&Delta> {
@@ -41,7 +55,31 @@ impl History {
/// Whether history holds a delta authored at `timestamp`.
pub fn contains_timestamp(&self, timestamp: TimeStamp) -> bool {
self.deltas.iter().any(|delta| delta.timestamp == timestamp)
self.timestamps.contains(&timestamp)
}
/// The content hashes named by any resource addition or removal in history.
pub fn resource_hashes(&self) -> &HashSet<ResourceHash> {
&self.resource_hashes
}
/// Whether the deltas from `from` on extend the canonical order as they stand: a chain, each the
/// first's child in turn, hanging off the last delta before them. Such a tail is what every
/// retirement in a hosted session appends, and needs no re-sort.
///
/// The sort emits, among the deltas whose parents are all out, the lowest rev. A chain on the last
/// delta is alone in that set at every step, so it sorts where it was appended. A tail whose root
/// hangs off an earlier delta competes with that delta's later siblings and may sort before them.
pub fn extends_canonically(&self, from: usize) -> bool {
let Some(tail) = self.deltas.get(from..) else { return true };
let mut previous = from.checked_sub(1).map(|position| self.deltas[position].id);
for delta in tail {
if delta.parent != previous || matches!(delta.kind, RegistryDelta::Merge { .. }) {
return false;
}
previous = Some(delta.id);
}
true
}
pub fn len(&self) -> usize {
@@ -56,10 +94,23 @@ impl History {
/// (idempotent re-apply) overwrites the existing entry in place rather than appending, so the
/// order and index are unchanged.
pub fn push(&mut self, delta: Delta) {
self.timestamps.insert(delta.timestamp);
match &delta.kind {
RegistryDelta::AddResource { entry, .. } => self.resource_hashes.extend(entry.hash),
RegistryDelta::RemoveResource { snapshot, .. } => self.resource_hashes.extend(snapshot.hash),
_ => {}
}
if let Some(&position) = self.index.get(&delta.id) {
self.deltas[position] = delta;
return;
}
for parent in delta.all_parents() {
self.referenced.insert(parent);
self.tips.remove(&parent);
}
if !self.referenced.contains(&delta.id) {
self.tips.insert(delta.id);
}
self.index.insert(delta.id, self.deltas.len());
self.deltas.push(delta);
}
@@ -69,6 +120,11 @@ impl History {
self.deltas.iter()
}
/// The delta at `position` in topological order.
pub fn at(&self, position: usize) -> Option<&Delta> {
self.deltas.get(position)
}
/// Re-order `deltas` into the canonical topological order and rebuild the index: parents precede
/// children, and among deltas whose parents are all emitted the lowest `Rev` goes first. O(V + E).
///
@@ -162,8 +218,7 @@ impl History {
/// The current tips: revs that no other delta lists as a parent (the divergent heads). A linear
/// history has exactly one tip; concurrent branches have several. Sorted ascending for determinism.
pub fn tips(&self) -> Vec<Rev> {
let referenced: std::collections::HashSet<Rev> = self.deltas.iter().flat_map(|delta| delta.all_parents()).collect();
let mut tips: Vec<Rev> = self.deltas.iter().map(|delta| delta.id).filter(|rev| !referenced.contains(rev)).collect();
let mut tips: Vec<Rev> = self.tips.iter().copied().collect();
tips.sort_unstable();
tips
}
+1
View File
@@ -42,6 +42,7 @@ pub use to_runtime::{Declarations, ProjectedNetwork, ProjectedNode, RuntimeProje
#[cfg(test)]
mod tests {
mod bookkeeping;
mod crdt;
mod projection;
mod round_trip;
+38 -29
View File
@@ -49,6 +49,8 @@ impl Session {
next_hot_sequence: HotSequence::NONE,
refold_owed: false,
working_rederivations: 0,
refolds: 0,
fold: None,
},
remote_tips: HashMap::new(),
runtime_base: None,
@@ -269,6 +271,8 @@ impl Session {
next_hot_sequence: HotSequence::NONE,
refold_owed: false,
working_rederivations: 0,
refolds: 0,
fold: None,
},
remote_tips: HashMap::new(),
runtime_base: None,
@@ -309,7 +313,8 @@ impl Session {
/// [`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()));
let retired_ids: HashSet<HotOpId> = retired.iter().copied().collect();
self.document.hot_log.retain(|hot_op| !retired_ids.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());
@@ -349,27 +354,18 @@ impl Session {
/// takes the last removal in canonical order, and with the whole history in view that can be one past
/// the replay position, whose snapshot places the entity in a network the replay has not created yet.
pub fn snapshot_from_history(&self) -> Result<Registry, CrdtError> {
let reachable = self.document.history.ancestors(self.document.head);
let mut folded = self.clone();
folded.document.retired_snapshot = Registry::default();
folded.document.history = History::new();
for delta in self.document.history.iter().filter(|delta| reachable.contains(&delta.id)) {
folded.document.apply_op_with(RegistryTarget::Snapshot, delta.kind.clone(), delta.timestamp, ApplyMode::Idempotent)?;
folded.document.history.push(delta.clone());
}
Ok(folded.document.retired_snapshot)
// The oracle for tests and the simulation; the live path folds in place through `refold_registries`.
self.clone().document.fold_snapshot_from_history()
}
/// Rebuild both registries from canonical history, then re-layer the hot tail. A full replay; callers
/// check it is needed first.
fn refold_registries(&mut self) -> Result<(), CrdtError> {
self.document.refolds += 1;
// Cleared only on the way out. The deltas are in history either way, and a failure here leaves the
// registries derived from an older one until something retries.
self.document.refold_owed = true;
self.document.retired_snapshot = self.snapshot_from_history()?;
self.document.retired_snapshot = self.document.fold_snapshot_from_history()?;
// One left unapplicable is kept, not dropped: a later delta or hot op can still supply its referent.
let previous = std::mem::replace(&mut self.document.working_registry, self.document.retired_snapshot.clone());
@@ -403,6 +399,15 @@ impl Session {
self.document.working_rederivations
}
/// How many refolds have run, whatever they produced.
pub fn refolds(&self) -> u64 {
self.document.refolds
}
pub fn history_len(&self) -> usize {
self.document.history.len()
}
/// Integrate `incoming` retired deltas (in causal order) from another peer. Moves `head` forward
/// without a new delta when the incoming history extends it, otherwise joins `head` and the
/// incoming tips with a [`RegistryDelta::Merge`].
@@ -433,17 +438,29 @@ impl Session {
return Ok(MergeOutcome::NoOp);
}
self.document.history.canonical_sort();
// A batch that chains off the last delta is already in canonical order, which is every retirement
// a host sends, and costs nothing to place. Anything else is sorted into place, over all of history.
let extends = self.document.history.extends_canonically(length_before);
if !extends {
self.document.history.canonical_sort();
}
// The loop folds in arrival order, and concurrent ops do not all commute: a remove and a change to
// the same target resolve by whichever lands second.
let folded_in_canonical_order = self.document.history.iter().skip(length_before).map(|delta| delta.id).eq(arrival_order.iter().copied());
let folded_in_canonical_order = extends || self.document.history.iter().skip(length_before).map(|delta| delta.id).eq(arrival_order.iter().copied());
let history = &self.document.history;
let mut candidates: Vec<Rev> = history.tips().into_iter().filter(|tip| absorbed_ids.contains(tip)).collect();
candidates.extend(self.document.head);
let is_dominated = |candidate: Rev| candidates.iter().any(|&other| other != candidate && history.is_ancestor(candidate, other));
let parents: Vec<Rev> = candidates.iter().copied().filter(|&candidate| !is_dominated(candidate)).collect();
let last_before = length_before.checked_sub(1).and_then(|position| history.at(position)).map(|delta| delta.id);
let parents: Vec<Rev> = if extends && self.document.head == last_before {
// The chain hangs off `head`, so `head` is its ancestor and the chain's end is the one tip.
vec![history.at(history.len() - 1).expect("the batch is non-empty").id]
} else {
let mut candidates: Vec<Rev> = history.tips().into_iter().filter(|tip| absorbed_ids.contains(tip)).collect();
candidates.extend(self.document.head);
let is_dominated = |candidate: Rev| candidates.iter().any(|&other| other != candidate && history.is_ancestor(candidate, other));
candidates.iter().copied().filter(|&candidate| !is_dominated(candidate)).collect()
};
let outcome = match parents.as_slice() {
[tip] => MergeOutcome::FastForward(*tip),
@@ -661,15 +678,7 @@ impl Session {
/// bytes. Walks current resources plus each delta's `AddResource`/`RemoveResource` snapshot.
pub fn all_referenced_resource_hashes(&self) -> HashSet<ResourceHash> {
let mut hashes: HashSet<ResourceHash> = self.document.working_registry.resources.values().filter_map(|entry| entry.hash).collect();
for delta in self.document.history.iter() {
match &delta.kind {
RegistryDelta::AddResource { entry, .. } => hashes.extend(entry.hash),
RegistryDelta::RemoveResource { snapshot, .. } => hashes.extend(snapshot.hash),
_ => {}
}
}
hashes.extend(self.document.history.resource_hashes());
hashes
}
@@ -0,0 +1,145 @@
use std::collections::HashSet;
use crate::{AttributeDelta, Delta, History, MergeOutcome, Network, NetworkId, PeerId, RegistryDelta, ResourceEntry, ResourceHash, ResourceId, Rev, Session};
fn set_attribute(key: &str, value: u32) -> RegistryDelta {
RegistryDelta::ChangeDocumentAttribute {
delta: AttributeDelta {
key: key.to_string(),
value: Some(serde_json::json!(value)),
},
}
}
fn add_network(id: u64) -> RegistryDelta {
RegistryDelta::AddNetwork {
id: NetworkId(id),
network: Network::default(),
}
}
/// The tips as a scan finds them, for checking the maintained set against.
fn scanned_tips(history: &History) -> Vec<Rev> {
let referenced: HashSet<Rev> = history.iter().flat_map(|delta| delta.all_parents()).collect();
let mut tips: Vec<Rev> = history.iter().map(|delta| delta.id).filter(|rev| !referenced.contains(rev)).collect();
tips.sort_unstable();
tips
}
/// Two peers that branch from a shared base, so their histories hold two tips until merged.
fn branched_pair() -> (Session, Session) {
let mut a = Session::with_peer(PeerId(1));
a.commit_op_for_test(set_attribute("base", 0)).expect("base");
let mut b = a.clone();
b.document.peer = PeerId(2);
b.document.clock = crate::LamportClock::new(PeerId(2));
a.commit_op_for_test(set_attribute("a", 1)).expect("a edit");
b.commit_op_for_test(set_attribute("b", 2)).expect("b edit");
(a, b)
}
#[test]
fn the_tip_set_follows_pushes_merges_and_sorts() {
let (mut a, b) = branched_pair();
assert_eq!(a.document.history.tips(), scanned_tips(&a.document.history));
a.merge(b.cloned_deltas()).expect("merge");
assert_eq!(a.document.history.tips(), scanned_tips(&a.document.history), "after a merge joining two branches");
assert_eq!(a.document.history.tips().len(), 1, "the merge delta is the one tip");
a.commit_op_for_test(set_attribute("after", 3)).expect("edit after the merge");
assert_eq!(a.document.history.tips(), scanned_tips(&a.document.history));
// A reload builds the same indexes from the ordered deltas.
let reloaded = History::from_ordered(a.cloned_deltas());
assert_eq!(reloaded.tips(), a.document.history.tips());
for delta in a.history() {
assert!(reloaded.contains_timestamp(delta.timestamp));
}
}
#[test]
fn history_names_the_resource_hashes_it_carries() {
let hash = ResourceHash::from(b"bytes".as_slice());
let id = ResourceId::new();
let mut session = Session::with_peer(PeerId(1));
session
.commit_op_for_test(RegistryDelta::AddResource {
id,
entry: ResourceEntry::embedded(hash, PeerId(1), crate::TimeStamp::ORIGIN),
})
.expect("add");
assert!(session.document.history.resource_hashes().contains(&hash));
let entry = session.retired_registry().resources[&id].clone();
session.commit_op_for_test(RegistryDelta::RemoveResource { id, snapshot: entry }).expect("remove");
assert!(session.all_referenced_resource_hashes().contains(&hash), "a removed resource's hash is still referenced from history");
}
/// A retirement from the host chains off the guest's last delta, so it is placed without a sort and
/// without walking ancestry, and the result is exactly what the sort would have produced.
#[test]
fn a_chain_off_the_last_delta_fast_forwards_without_sorting() {
let mut host = Session::with_peer(PeerId(1));
host.commit_op_for_test(set_attribute("base", 0)).expect("base");
let mut guest = host.clone();
guest.document.peer = PeerId(2);
host.commit_op_for_test(set_attribute("x", 1)).expect("x");
host.commit_op_for_test(add_network(5)).expect("network");
host.commit_op_for_test(set_attribute("y", 2)).expect("y");
let incoming: Vec<Delta> = host.cloned_deltas().into_iter().filter(|delta| guest.delta(delta.id).is_none()).collect();
assert!(guest.document.history.extends_canonically(guest.history_len()), "an empty tail extends trivially");
let refolds = guest.refolds();
let outcome = guest.merge(incoming).expect("merge");
assert!(matches!(outcome, MergeOutcome::FastForward(rev) if Some(rev) == host.head_rev()), "{outcome:?}");
assert_eq!(guest.refolds(), refolds, "a fast-forward folds nothing again");
assert_eq!(guest.history().map(|delta| delta.id).collect::<Vec<_>>(), host.history().map(|delta| delta.id).collect::<Vec<_>>());
let mut sorted = guest.document.history.clone();
sorted.canonical_sort();
assert_eq!(
sorted.iter().map(|delta| delta.id).collect::<Vec<_>>(),
guest.history().map(|delta| delta.id).collect::<Vec<_>>(),
"the appended order was already canonical"
);
assert!(guest.retired_registry().value_equal(host.retired_registry()));
}
#[test]
fn a_batch_off_an_earlier_delta_is_sorted_into_place() {
let (mut a, b) = branched_pair();
let before = a.history_len();
let incoming: Vec<Delta> = b.cloned_deltas().into_iter().filter(|delta| a.delta(delta.id).is_none()).collect();
a.merge(incoming).expect("merge");
assert!(!a.document.history.extends_canonically(before), "b's delta hangs off the base, not off a's last delta");
let mut sorted = a.document.history.clone();
sorted.canonical_sort();
assert_eq!(sorted.iter().map(|delta| delta.id).collect::<Vec<_>>(), a.history().map(|delta| delta.id).collect::<Vec<_>>());
assert_eq!(a.document.history.tips(), scanned_tips(&a.document.history));
}
/// The in-place fold leaves everything but the snapshot alone and agrees with the cloning oracle.
#[test]
fn the_in_place_fold_matches_the_oracle_and_touches_nothing_else() {
let mut session = Session::with_peer(PeerId(1));
session.commit_op_for_test(add_network(3)).expect("network");
session.commit_op_for_test(set_attribute("x", 1)).expect("x");
session.stage_ops(vec![set_attribute("hot", 9)]).expect("a hot op on top");
let oracle = session.snapshot_from_history().expect("oracle");
let working_before = session.registry().clone();
let hot_before = session.hot_log().to_vec();
let head_before = session.head_rev();
let folded = session.document.fold_snapshot_from_history().expect("fold");
assert!(folded.value_equal(&oracle));
assert!(session.registry().value_equal(&working_before), "the working registry is untouched");
assert_eq!(session.hot_log().len(), hot_before.len());
assert_eq!(session.head_rev(), head_before);
assert!(session.document.fold.is_none(), "the scope is cleared on the way out");
}