//! DAG (Directed Acyclic Graph) is a common data structure in distributed system. //! //! This mod contains the DAGs in our CRDT. It's not a general DAG, it has some specific properties that //! we used to optimize the speed: //! - Each node has lamport clock. //! - Each node has its ID (client_id, counter). //! - We use ID to refer to node rather than content addressing (hash) //! use std::{ borrow::Cow, collections::{BinaryHeap, HashMap}, fmt::Debug, }; use loro_common::{IdSpanVector, LoroError, LoroResult}; use rle::{HasLength, Sliceable}; use rustc_hash::{FxHashMap, FxHashSet}; mod iter; pub(crate) use iter::DagCausalIter; mod mermaid; #[cfg(feature = "test_utils")] mod test; #[cfg(feature = "test_utils")] pub use test::{fuzz_alloc_tree, Interaction}; use crate::{ change::Lamport, diff_calc::DiffMode, id::{Counter, PeerID, ID}, span::{CounterSpan, HasId, HasIdSpan, HasLamport, HasLamportSpan, IdSpan}, version::{Frontiers, VersionVector, VersionVectorDiff}, }; use self::{ iter::{iter_dag, iter_dag_with_vv, DagIterator, DagIteratorVV}, mermaid::dag_to_mermaid, }; pub(crate) trait DagNode: HasLamport + HasId + HasLength + Debug + Sliceable { fn deps(&self) -> &Frontiers; #[allow(unused)] #[inline] fn get_lamport_from_counter(&self, c: Counter) -> Lamport { self.lamport() + c as Lamport - self.id_start().counter as Lamport } } /// Dag (Directed Acyclic Graph). /// /// We have following invariance in DAG /// - All deps' lamports are smaller than current node's lamport pub(crate) trait Dag: Debug { type Node: DagNode; fn get(&self, id: ID) -> Option; fn try_get(&self, id: ID) -> LoroResult> { Ok(self.get(id)) } #[allow(unused)] fn frontier(&self) -> &Frontiers; fn vv(&self) -> &VersionVector; fn contains(&self, id: ID) -> bool; } /// Whether the meet of two versions can serve as the replay base between them. #[derive(Debug)] pub(crate) enum MeetAsBase { /// The meet is a valid replay base for the returned diff mode. That makes /// it a critical version only in non-`Checkout` modes (spec S3). In /// `Checkout` mode it is just the meet, and ops above it may be concurrent /// with one of its heads; checkout consumers accept that (spec Q7). Valid(Frontiers), /// A concurrent branch crosses the meet, so replaying from it would /// leave concurrency unadjudicated. The caller must retreat to a critical /// version below it (see `docs/critical-version-spec.md`). NeedsCriticalRetreat, } pub(crate) trait DagUtils: Dag { /// The replay base for diffing `a_id` into `b_id`: the meet when it is a /// valid base for the diff mode, else the latest single-head critical /// version. /// /// This is NOT always a critical version: in `DiffMode::Checkout` it may be /// a meet with concurrent ops above it (see [`MeetAsBase::Valid`]). Callers /// that need every other op to be before or after the result, such as the /// shallow snapshot root, must use /// [`Self::latest_single_head_critical_version`] (loro-dev/loro#1095). /// /// Only the DAG tests call it: the tree calculator used to, and now takes its /// window from the two versions (`context/tree-checkout-window.md`). #[cfg(test)] fn find_replay_base(&self, a_id: &Frontiers, b_id: &Frontiers) -> (Frontiers, DiffMode); /// Like `find_replay_base`, but leaves the conservative /// fallback to the caller: on [`MeetAsBase::NeedsCriticalRetreat`] the /// caller must retreat to a critical version (via /// [`Self::latest_single_head_critical_version`], or a cheaper multi-head /// one it can find itself). Finding the single-head cut walks the whole /// DAG, so callers that usually have a better answer should not pay for /// it up front. #[cfg(test)] fn find_meet_and_mode(&self, a_id: &Frontiers, b_id: &Frontiers) -> (MeetAsBase, DiffMode) { self.try_find_meet_and_mode(a_id, b_id).unwrap() } fn try_find_meet_and_mode( &self, a_id: &Frontiers, b_id: &Frontiers, ) -> LoroResult<(MeetAsBase, DiffMode)>; #[cfg(test)] fn latest_single_head_critical_version(&self, a_id: &Frontiers, b_id: &Frontiers) -> Frontiers { self.try_latest_single_head_critical_version(a_id, b_id) .unwrap() } fn try_latest_single_head_critical_version( &self, a_id: &Frontiers, b_id: &Frontiers, ) -> LoroResult; /// Slow, should probably only use on dev #[allow(unused)] fn get_vv(&self, id: ID) -> VersionVector; #[allow(unused)] fn find_path(&self, from: &Frontiers, to: &Frontiers) -> VersionVectorDiff { self.try_find_path(from, to).unwrap() } fn try_find_path(&self, from: &Frontiers, to: &Frontiers) -> LoroResult; #[cfg(test)] fn iter_causal(&self, from: Frontiers, target: IdSpanVector) -> DagCausalIter<'_, Self> where Self: Sized; #[allow(unused)] fn iter(&self) -> DagIterator<'_, Self::Node> where Self: Sized; #[allow(unused)] fn iter_with_vv(&self) -> DagIteratorVV<'_, Self::Node> where Self: Sized; #[allow(unused)] fn mermaid(&self) -> String where Self: Sized; } impl DagUtils for T { #[cfg(test)] #[inline] fn find_replay_base(&self, a_id: &Frontiers, b_id: &Frontiers) -> (Frontiers, DiffMode) { // TODO: perf: make it also return the spans to reach the replay base let (meet, mode) = self.find_meet_and_mode(a_id, b_id); let base = match meet { MeetAsBase::Valid(meet) => meet, MeetAsBase::NeedsCriticalRetreat => { self.latest_single_head_critical_version(a_id, b_id) } }; (base, mode) } #[inline] fn try_find_meet_and_mode( &self, a_id: &Frontiers, b_id: &Frontiers, ) -> LoroResult<(MeetAsBase, DiffMode)> { find_meet_and_mode(&|id| self.try_get(id), a_id, b_id) } #[inline] fn try_latest_single_head_critical_version( &self, a_id: &Frontiers, b_id: &Frontiers, ) -> LoroResult { latest_single_head_critical_version(&|id| self.try_get(id), a_id, b_id) } #[inline] fn get_vv(&self, id: ID) -> VersionVector { get_version_vector(&|id| self.get(id), id) } fn try_find_path(&self, from: &Frontiers, to: &Frontiers) -> LoroResult { let mut ans = VersionVectorDiff::default(); if from == to { return Ok(ans); } if from.len() == 1 && to.len() == 1 { let from = from.as_single().unwrap(); let to = to.as_single().unwrap(); if from.peer == to.peer { let from_span = self .try_get(from)? .ok_or(LoroError::FrontiersNotFound(from))?; let to_span = self.try_get(to)?.ok_or(LoroError::FrontiersNotFound(to))?; if from_span.id_start() == to_span.id_start() { if from.counter < to.counter { ans.forward.insert( from.peer, CounterSpan::new(from.counter + 1, to.counter + 1), ); } else { ans.retreat.insert( from.peer, CounterSpan::new(to.counter + 1, from.counter + 1), ); } return Ok(ans); } if from_span.deps().len() == 1 && to_span.contains_id(from_span.deps().as_single().unwrap()) { ans.retreat.insert( from.peer, CounterSpan::new(to.counter + 1, from.counter + 1), ); return Ok(ans); } if to_span.deps().len() == 1 && from_span.contains_id(to_span.deps().as_single().unwrap()) { ans.forward.insert( from.peer, CounterSpan::new(from.counter + 1, to.counter + 1), ); return Ok(ans); } } } _walk_to_meet( &|v| self.try_get(v), from, to, &mut |span, node_type| match node_type { NodeType::A => ans.merge_left(span), NodeType::B => ans.merge_right(span), NodeType::Shared => { ans.subtract_start_left(span); ans.subtract_start_right(span); } }, true, )?; Ok(ans) } #[inline(always)] fn iter_with_vv(&self) -> DagIteratorVV<'_, Self::Node> where Self: Sized, { iter_dag_with_vv(self) } #[inline(always)] #[cfg(test)] fn iter_causal(&self, from: Frontiers, target: IdSpanVector) -> DagCausalIter<'_, Self> where Self: Sized, { DagCausalIter::new(self, from, target) } #[inline(always)] fn iter(&self) -> DagIterator<'_, Self::Node> where Self: Sized, { iter_dag(self) } /// You can visualize and generate img link at https://mermaid.live/ #[inline] fn mermaid(&self) -> String where Self: Sized, { dag_to_mermaid(self) } } #[allow(dead_code)] fn get_version_vector<'a, Get, D>(get: &'a Get, id: ID) -> VersionVector where Get: Fn(ID) -> Option, D: DagNode + 'a, { let mut vv = VersionVector::new(); let mut visited: FxHashSet = FxHashSet::default(); vv.insert(id.peer, id.counter + 1); let node = get(id).unwrap(); if node.deps().is_empty() { return vv; } let mut stack = Vec::with_capacity(node.deps().len()); for dep in node.deps().iter() { stack.push(dep); } while let Some(node_id) = stack.pop() { let node = get(node_id).unwrap(); let node_id_start = node.id_start(); vv.try_update_last(node_id); if !visited.contains(&node_id_start) { for dep in node.deps().iter() { if !visited.contains(&dep) { stack.push(dep); } } visited.insert(node_id_start); } } vv } #[derive(Debug, PartialEq, Eq)] struct OrdIdSpan<'a> { id: ID, lamport: Lamport, len: usize, deps: Cow<'a, Frontiers>, } impl HasLength for OrdIdSpan<'_> { fn content_len(&self) -> usize { self.len } } impl HasId for OrdIdSpan<'_> { fn id_start(&self) -> ID { self.id } } impl HasLamport for OrdIdSpan<'_> { fn lamport(&self) -> Lamport { self.lamport } } impl PartialOrd for OrdIdSpan<'_> { fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } impl Ord for OrdIdSpan<'_> { fn cmp(&self, other: &Self) -> std::cmp::Ordering { self.lamport_last() .cmp(&other.lamport_last()) .then(self.id.peer.cmp(&other.id.peer)) // If they have the same last id, we want the shorter one to be greater; // Otherwise, find_replay_base won't work correctly. Because we may // lazily load the dag node, so sometimes the longer one should be broken // into smaller pieces but it's already pushed to the queue. .then(other.len.cmp(&self.len)) } } #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)] enum NodeType { A, B, Shared, } impl<'a> OrdIdSpan<'a> { #[inline] fn from_dag_node(id: ID, get: &'a F) -> LoroResult>> where D: DagNode + 'a, F: Fn(ID) -> LoroResult>, { let Some(span) = get(id)? else { return Ok(None); }; let span_id = span.id_start(); Ok(Some(OrdIdSpan { id: span_id, lamport: span.lamport(), deps: Cow::Owned(span.deps().clone()), len: (id.counter - span_id.counter) as usize + 1, })) } #[inline] fn get_min(&self) -> OrdIdSpan<'a> { OrdIdSpan { id: self.id, lamport: self.lamport, deps: Cow::Owned(Default::default()), len: 1, } } } #[inline(always)] fn find_meet_and_mode<'a, F, D>( get: &'a F, a_id: &Frontiers, b_id: &Frontiers, ) -> LoroResult<(MeetAsBase, DiffMode)> where D: DagNode + 'a, F: Fn(ID) -> LoroResult>, { if b_id.is_empty() { return Ok((MeetAsBase::Valid(Default::default()), DiffMode::Checkout)); } _find_meet_and_mode(get, a_id, b_id) } /// - deep whether keep searching until the min of non-shared node is found fn _walk_to_meet<'a, F, D, G>( get: &'a F, a_ids: &Frontiers, b_ids: &Frontiers, notify: &mut G, find_path: bool, ) -> LoroResult> where D: DagNode + 'a, F: Fn(ID) -> LoroResult>, G: FnMut(IdSpan, NodeType), { let mut ans: FxHashMap = Default::default(); let mut queue: BinaryHeap<(OrdIdSpan, NodeType)> = BinaryHeap::new(); for id in a_ids.iter() { queue.push((OrdIdSpan::from_dag_node(id, get)?.unwrap(), NodeType::A)); } for id in b_ids.iter() { queue.push((OrdIdSpan::from_dag_node(id, get)?.unwrap(), NodeType::B)); } let mut visited: HashMap = FxHashMap::default(); // invariants in this method: // // - visited's (client, counters) are subset of max(version_vector_a, version_vector_b) // - visited's node type reflecting whether we found the shared node of this client // - ans's client id never repeat // - nodes with the same id will only be visited once // - we may visit nodes that are before the meet // type count in the queue. if both are zero, we can stop let mut a_count = a_ids.len(); let mut b_count = b_ids.len(); let mut min = None; while let Some((node, mut node_type)) = queue.pop() { match node_type { NodeType::A => a_count -= 1, NodeType::B => b_count -= 1, NodeType::Shared => {} } if node_type != NodeType::Shared { if let Some(min) = &mut min { let node_start = node.get_min(); if node_start < *min { *min = node_start; } } else { min = Some(node.get_min()) } } // pop the same node in the queue while let Some((other_node, other_type)) = queue.peek() { if node.id_span() == other_node.id_span() { if node_type == *other_type { match node_type { NodeType::A => a_count -= 1, NodeType::B => b_count -= 1, NodeType::Shared => {} } } else { if node_type != NodeType::Shared { if visited.get(&node.id.peer).map(|(_, t)| *t) != Some(NodeType::Shared) { ans.insert(node.id.peer, other_node.id_last().counter); } node_type = NodeType::Shared; } match other_type { NodeType::A => a_count -= 1, NodeType::B => b_count -= 1, NodeType::Shared => {} } } queue.pop(); } else { break; } } // detect whether client is visited by other if let Some((ctr, visited_type)) = visited.get_mut(&node.id.peer) { debug_assert!(*ctr >= node.id_last().counter); if *visited_type == NodeType::Shared { node_type = NodeType::Shared; } else if *visited_type != node_type { // if node_type is shared, ans should already contains it or its descendance if node_type != NodeType::Shared { ans.insert(node.id.peer, node.id_last().counter); } *visited_type = NodeType::Shared; node_type = NodeType::Shared; } } else { visited.insert(node.id.peer, (node.id_last().counter, node_type)); } // if this is not shared, the end of the span must be only reachable from A, or only reachable from B. // but the begin of the span may be reachable from both A and B notify(node.id_span(), node_type); match node_type { NodeType::A => a_count += node.deps.len(), NodeType::B => b_count += node.deps.len(), NodeType::Shared => {} } if a_count == 0 && b_count == 0 && (min.is_none() || &node <= min.as_ref().unwrap()) { if node_type != NodeType::Shared { ans.clear(); } break; } for dep_id in node.deps.as_ref().iter() { queue.push((OrdIdSpan::from_dag_node(dep_id, get)?.unwrap(), node_type)); } if node_type != NodeType::Shared { if queue.is_empty() { ans.clear(); break; } if node.deps.is_empty() && !find_path { if node.len == 1 { ans.clear(); break; } match node_type { NodeType::A => a_count += 1, NodeType::B => b_count += 1, NodeType::Shared => {} } queue.push(( OrdIdSpan { deps: Cow::Owned(Default::default()), id: node.id, len: 1, lamport: node.lamport, }, node_type, )); } } } Ok(ans) } /// Resolves each frontier id to the span of its containing node, truncated at /// that id. Returns `None` when an id is unavailable (trimmed history). fn ids_to_ord_id_spans<'a, D: DagNode + 'a, F: Fn(ID) -> LoroResult>>( ids: &Frontiers, get: &'a F, ) -> LoroResult>>> { let mut ans = Vec::with_capacity(ids.len()); for id in ids.iter() { if let Some(node) = OrdIdSpan::from_dag_node(id, get)? { ans.push(node); } else { return Ok(None); } } Ok(Some(ans)) } /// The parent set of a span's first op: the node's explicit deps plus the /// implicit same-peer predecessor when it is not already covered by one of them. fn deps_to_ord_id_spans<'a, D: DagNode + 'a, F: Fn(ID) -> LoroResult>>( node: &OrdIdSpan<'a>, get: &'a F, ) -> LoroResult>>> { let Some(mut deps) = ids_to_ord_id_spans(node.deps.as_ref(), get)? else { return Ok(None); }; if node.id.counter > 0 { let prev = node.id.inc(-1); if let Some(prev) = OrdIdSpan::from_dag_node(prev, get)? { if !deps.iter().any(|dep| dep.contains_id(prev.id_last())) { deps.push(prev); } } } Ok(Some(deps)) } /// The latest single-head critical version (Eg-walker §3.5/§3.6) of the /// union graph `ancestry(left) ∪ ancestry(right)`: the newest event `v` /// such that every other event in the union is an ancestor of `v` or /// causally after `v`. Replaying from `{v}` is safe because no concurrency /// crosses it, and it skips the fully-synced prefix of common history that /// the old `∅` fallback would replay. /// /// Method: a one-colour descent from both frontiers using the same /// coalesce/align machinery as the main walk. The pending heap is always a /// cut of the unexplored region, so the first moment it narrows to a /// single span, that span's `id_last` is the latest such `v`. If a chain /// dies at a root or at trimmed history while other chains remain, its /// endpoint is concurrent with everything below the current level, so no /// later singleton can be valid — bail out to the empty version, which is /// the old behaviour. fn latest_single_head_critical_version<'a, D: DagNode + 'a, F: Fn(ID) -> LoroResult>>( get: &'a F, left: &Frontiers, right: &Frontiers, ) -> LoroResult { let mut queue: BinaryHeap = BinaryHeap::new(); let Some(spans) = ids_to_ord_id_spans(left, get)? else { return Ok(Default::default()); }; queue.extend(spans); let Some(spans) = ids_to_ord_id_spans(right, get)? else { return Ok(Default::default()); }; queue.extend(spans); while let Some(mut node) = queue.pop() { while let Some(other) = queue.peek() { if node == *other || node.id_last() == other.id_last() { queue.pop(); } else { break; } } if queue.is_empty() { return Ok(node.id_last().into()); } if let Some(other) = queue.peek() { if node.contains_id(other.id_last()) { node.len = (other.id_last().counter - node.id.counter + 1) as usize; queue.push(node); continue; } if node.len > 1 { node.len = if other.lamport_last() >= node.lamport { (other.lamport_last() - node.lamport + 1).min(node.len as u32 - 1) as usize } else { 1 }; queue.push(node); continue; } } match deps_to_ord_id_spans(&node, get)? { Some(deps) if !deps.is_empty() => { for dep in deps { queue.push(dep); } } _ => return Ok(Default::default()), } } Ok(Default::default()) } /// Finds the replay base and diff mode for the transition `left -> right`. /// /// Contract (see `docs/critical-version-spec.md` for definitions and proofs): /// - S1: every id in the returned frontier is in the causal past of both sides; /// - S2: the returned frontier is an antichain; /// - S3: a non-`Checkout` mode additionally guarantees that the base equals /// `left` and that EVERY newly imported event is causally after every head /// of `left` (i.e. `left` is a critical version of the union graph in the /// Eg-walker sense, arXiv:2409.14252 §3.5) — enforced for multi-head `left` /// by `new_region_after_all_left_heads`; /// - when a genuinely concurrent branch invalidates the candidate base, the /// base retreats to the latest single-head critical version /// (`latest_single_head_critical_version`), or to the empty version when no /// such cut exists. /// /// Downstream consumers rely on these guarantees to skip CRDT adjudication /// (tree/map fast paths) and to bound their replay windows (tree checkout); /// see the comment in `diff_calc/tree.rs::checkout_diff`. fn _find_meet_and_mode<'a, F, D>( get: &'a F, left: &Frontiers, right: &Frontiers, ) -> LoroResult<(MeetAsBase, DiffMode)> where D: DagNode + 'a, F: Fn(ID) -> LoroResult>, { if right.is_empty() { return Ok((MeetAsBase::Valid(Default::default()), DiffMode::Checkout)); } if left.is_empty() { if right.len() == 1 { let mut node_id = right.as_single().unwrap(); let mut node = get(node_id)?.unwrap(); while node.deps().len() == 1 { node_id = node.deps().as_single().unwrap(); let Some(next) = get(node_id)? else { return Ok(( MeetAsBase::Valid(Default::default()), DiffMode::ImportGreaterUpdates, )); }; node = next; } if node.deps().is_empty() { return Ok((MeetAsBase::Valid(Default::default()), DiffMode::Linear)); } } return Ok(( MeetAsBase::Valid(Default::default()), DiffMode::ImportGreaterUpdates, )); } if left.len() == 1 && right.len() == 1 { let left = left.as_single().unwrap(); let right = right.as_single().unwrap(); if left.peer == right.peer { let left_span = get(left)?.unwrap(); let right_span = get(right)?.unwrap(); if left_span.id_start() == right_span.id_start() { if left.counter < right.counter { return Ok((MeetAsBase::Valid(left.into()), DiffMode::Linear)); } else { return Ok((MeetAsBase::Valid(right.into()), DiffMode::Checkout)); } } if left_span.deps().len() == 1 && right_span.contains_id(left_span.deps().as_single().unwrap()) { return Ok((MeetAsBase::Valid(right.into()), DiffMode::Checkout)); } if right_span.deps().len() == 1 && left_span.contains_id(right_span.deps().as_single().unwrap()) { return Ok((MeetAsBase::Valid(left.into()), DiffMode::Linear)); } } } let mut is_linear = left.len() <= 1 && right.len() == 1; let mut is_right_greater = true; let mut unmatched_branches = FxHashSet::default(); let mut has_unresolved_unmatched_branch = false; let mut ans: Frontiers = Default::default(); fn shrink_ancestor_frontiers<'a, D: DagNode + 'a, F: Fn(ID) -> LoroResult>>( ids: &Frontiers, get: &'a F, ) -> LoroResult { if ids.len() <= 1 { return Ok(ids.clone()); } let mut ids = ids_to_ord_id_spans(ids, get)?.expect("meet candidates should be in dag"); ids.sort_unstable(); let mut frontiers = Vec::with_capacity(ids.len()); for id in ids.iter().rev() { let mut should_insert = true; for frontier in frontiers.iter().rev() { if contains_in_ancestors(get, *frontier, id)? { should_insert = false; break; } } if should_insert { frontiers.push(id.id_last()); } } Ok(frontiers.into_iter().collect()) } fn has_trimmed_history_deps<'a, D: DagNode + 'a, F: Fn(ID) -> LoroResult>>( ids: &Frontiers, get: &'a F, ) -> LoroResult { for id in ids.iter() { let Some(node) = OrdIdSpan::from_dag_node(id, get)? else { return Ok(true); }; if ids_to_ord_id_spans(node.deps.as_ref(), get)?.is_none() { return Ok(true); } } Ok(false) } /// Whether every tip in `tips` is contained in the ancestors of `frontiers` /// (the tip itself counts). One walk answers all tips: it starts from every /// frontier with a shared visited set and prunes by the lowest lamport among /// the still-unproven tips, so the ancestor region is traversed at most once /// per call instead of once per (tip, frontier) pair. fn all_tips_covered_by_ancestors<'a, D: DagNode + 'a, F: Fn(ID) -> LoroResult>>( get: &'a F, frontiers: &Frontiers, tips: &FxHashSet, ) -> LoroResult { let mut remaining = Vec::with_capacity(tips.len()); for id in tips.iter() { let Some(span) = OrdIdSpan::from_dag_node(*id, get)? else { return Ok(false); }; remaining.push(span); } if remaining.is_empty() { return Ok(true); } let mut min_lamport = remaining .iter() .map(|tip| tip.lamport_last()) .min() .unwrap(); let mut visited = FxHashSet::default(); let mut pending = Vec::new(); for frontier in frontiers.iter() { if let Some(node) = OrdIdSpan::from_dag_node(frontier, get)? { pending.push(node); } } while let Some(node) = pending.pop() { let len_before = remaining.len(); remaining.retain(|tip| !node.contains_id(tip.id_last())); if remaining.is_empty() { return Ok(true); } if remaining.len() != len_before { min_lamport = remaining .iter() .map(|tip| tip.lamport_last()) .min() .unwrap(); } // Ancestors of `node` all have lamport strictly below the node's // start, so nothing below `min_lamport` can contain a remaining tip. if node.lamport_last() < min_lamport { continue; } if !visited.insert(node.id_start()) { continue; } if let Some(deps) = deps_to_ord_id_spans(&node, get)? { for dep in deps { pending.push(dep); } } } Ok(false) } /// Verifies the `ImportGreaterUpdates` contract for a multi-head `left`: /// every event in `Events(right) − Events(left)` must be causally after /// every member of `left` (i.e. `left` must be a critical version of the /// union graph). The main walk only proves version inclusion, which is /// weaker: a new branch can enter old history through one left head while /// staying concurrent with another, and the tree calculator's fast path /// applies such updates without adjudication (see /// `docs/critical-version-spec.md` §4.1). /// /// Method: descend from `right` over new changes only. A change whose /// causal parents (explicit deps plus the implicit same-peer predecessor) /// are all old is an entry point of the new region; its parents must /// causally cover every left head. Non-entry changes inherit coverage /// through their new parents. The common healthy shape — a change whose /// deps equal the left frontier — passes with a set comparison and no /// graph walk. Trimmed history fails conservatively. fn new_region_after_all_left_heads<'a, D: DagNode + 'a, F: Fn(ID) -> LoroResult>>( get: &'a F, left: &Frontiers, right: &Frontiers, ) -> LoroResult { let left_ids: FxHashSet = left.iter().collect(); let is_old = |id: ID| -> LoroResult { if left_ids.contains(&id) { return Ok(true); } let mut single = FxHashSet::default(); single.insert(id); all_tips_covered_by_ancestors(get, left, &single) }; let mut visited: FxHashSet = FxHashSet::default(); let mut stack: Vec = Vec::new(); for id in right.iter() { if is_old(id)? { continue; } let Some(span) = OrdIdSpan::from_dag_node(id, get)? else { return Ok(false); }; stack.push(span); } while let Some(span) = stack.pop() { if !visited.insert(span.id_start()) { continue; } let Some(parents) = deps_to_ord_id_spans(&span, get)? else { return Ok(false); }; let mut entry_point = true; let mut old_parents = Frontiers::default(); for parent in parents { let pid = parent.id_last(); if is_old(pid)? { old_parents.push(pid); } else { entry_point = false; stack.push(parent); } } if entry_point { if &old_parents == left { continue; } if !all_tips_covered_by_ancestors(get, &old_parents, &left_ids)? { return Ok(false); } } } Ok(true) } fn contains_in_ancestors<'a, D: DagNode + 'a, F: Fn(ID) -> LoroResult>>( get: &'a F, frontier: ID, target: &OrdIdSpan<'_>, ) -> LoroResult { let mut visited = FxHashSet::default(); let mut pending = Vec::new(); let Some(node) = OrdIdSpan::from_dag_node(frontier, get)? else { return Ok(false); }; pending.push(node); while let Some(node) = pending.pop() { if node.contains_id(target.id_last()) { return Ok(true); } if node.lamport_last() < target.lamport_last() { continue; } if !visited.insert(node.id_start()) { continue; } if let Some(deps) = deps_to_ord_id_spans(&node, get)? { for dep in deps { pending.push(dep); } } } Ok(false) } // The third tuple item carries the dependency tips at which this path first // split from its sibling paths. If the path dies without meeting the other // side, those tips tell us whether it was a real concurrent branch or merely // a redundant route into an ancestor we already found. let mut queue: BinaryHeap<(OrdIdSpan, NodeType, Vec)> = BinaryHeap::new(); for span in ids_to_ord_id_spans(left, get)?.unwrap() { let branch_tips = if left.len() > 1 { vec![span.id_last()] } else { Vec::new() }; queue.push((span, NodeType::A, branch_tips)); } for span in ids_to_ord_id_spans(right, get)?.unwrap() { let branch_tips = if right.len() > 1 { vec![span.id_last()] } else { Vec::new() }; queue.push((span, NodeType::B, branch_tips)); } while let Some((mut node, mut node_type, mut branch_tips)) = queue.pop() { while let Some((other_node, other_type, _)) = queue.peek() { if node == *other_node || node.id_last() == other_node.id_last() { if node_type != *other_type { node_type = NodeType::Shared; } let (_, _, other_branch_tips) = queue.pop().unwrap(); // Union, not concatenation. On criss-cross histories the same // tips arrive from both parents at every re-merge; concatenating // doubles the vec per sync round, and the per-dep clone below // then makes the walk O(2^rounds). Distinct tips stay few: they // are only minted for multi-head initial frontiers and at each // side's first split. for tip in other_branch_tips { if !branch_tips.contains(&tip) { branch_tips.push(tip); } } } else { break; } } if node_type == NodeType::Shared { ans.push(node.id_last()); continue; } if queue.is_empty() { if branch_tips.is_empty() { unmatched_branches.insert(node.id_last()); } else { unmatched_branches.extend(branch_tips); } break; } // if node_type is A, then the left side is greater or parallel to the right side if node_type == NodeType::A { is_right_greater = false; } if let Some(other) = queue.peek() { if node.contains_id(other.0.id_last()) && node_type != other.1 { node.len = (other.0.id_last().counter - node.id.counter + 1) as usize; queue.push((node, node_type, branch_tips)); continue; } if node.len > 1 { // The `min(..., len - 1)` cap guarantees strict progress when // lamports tie: aligning to the other's lamport alone would // re-push the span unchanged and loop forever. It is also what // makes the termination measure decrease on this branch. node.len = if other.0.lamport_last() >= node.lamport { (other.0.lamport_last() - node.lamport + 1).min(node.len as u32 - 1) as usize } else { 1 }; queue.push((node, node_type, branch_tips)); continue; } } if let Some(deps) = deps_to_ord_id_spans(&node, get)? { if !deps.is_empty() { let starts_new_branches = branch_tips.is_empty() && deps.len() > 1; for dep in deps { let child_branch_tips = if starts_new_branches { vec![dep.id_last()] } else { branch_tips.clone() }; queue.push((dep, node_type, child_branch_tips)); } is_linear = false; continue; } } else { // The dependency is on trimmed shallow history. The exact ancestor is // not representable in the current DAG, so fall back to a conservative // checkout base. No tip needs recording: this flag short-circuits the // coverage check entirely. has_unresolved_unmatched_branch = true; continue; } { // Some checkout calculators still require replaying from a base that // includes every branch whose operation positions may affect the diff. // In non-linear checkout mode, an earlier version in the causal past of // both sides is a valid conservative base even when it is not the meet. if branch_tips.is_empty() { unmatched_branches.insert(node.id_last()); } else { unmatched_branches.extend(branch_tips); } continue; } } ans = shrink_ancestor_frontiers(&ans, get)?; // A branch can look unmatched merely because a shared node was found first // and was therefore not expanded. In that case another queued path may still // walk into one of the shared node's ancestors. That path is redundant, not a // concurrent branch. Only fall back when an unmatched tip is not causally // covered by the meet candidates we found. let has_uncovered_unmatched_branch = has_unresolved_unmatched_branch || !all_tips_covered_by_ancestors(get, &ans, &unmatched_branches)?; // A genuine concurrent branch invalidates the meet as a replay base. The // caller has to retreat to a critical version; which one is its choice, so // it can try a cheap multi-head cut before paying for the full-DAG // single-head descent. let mut needs_critical_retreat = has_uncovered_unmatched_branch && !has_trimmed_history_deps(&ans, get)?; if has_uncovered_unmatched_branch { is_right_greater = false; } else if &ans == left { // An A-only path may also have been a redundant path into `ans`. Once all // such paths are proved covered, equality with `left` is the exact proof // that `right` causally includes `left`. is_right_greater = true; } if is_right_greater && left.len() > 1 && !new_region_after_all_left_heads(get, left, right)? { // Version inclusion holds, but part of the new region entered old // history through a strict subset of the left heads and is therefore // concurrent with the others. `ImportGreaterUpdates` promises "no // update is concurrent to the current version", so claiming it here // lets fast paths (notably the tree calculator's) apply the new ops // without adjudicating against the concurrent existing branch, and the // materialized state diverges from a full replay. Demote to the // conservative mode and retreat the base to a safe cut so the // competing branches are replayed together. is_right_greater = false; needs_critical_retreat = true; } let mode = if is_right_greater { if ans.len() <= 1 { debug_assert_eq!(&ans, left); } if is_linear { debug_assert!(ans.len() <= 1); DiffMode::Linear } else { DiffMode::ImportGreaterUpdates } } else { DiffMode::Checkout }; let meet = if needs_critical_retreat { MeetAsBase::NeedsCriticalRetreat } else { MeetAsBase::Valid(ans) }; Ok((meet, mode)) } pub fn remove_included_frontiers(frontiers: &mut VersionVector, new_change_deps: &[ID]) { for dep in new_change_deps.iter() { if let Some(last) = frontiers.get_last(dep.peer) { if last <= dep.counter { frontiers.remove(&dep.peer); } } } } #[cfg(test)] mod tests { use std::collections::BTreeMap; use loro_common::{HasId, HasIdSpan}; use rand::{rngs::StdRng, Rng, SeedableRng}; use super::*; #[derive(Clone, Debug)] struct TestNode { id: ID, len: usize, lamport: Lamport, deps: Frontiers, } impl DagNode for TestNode { fn deps(&self) -> &Frontiers { &self.deps } } impl HasId for TestNode { fn id_start(&self) -> ID { self.id } } impl HasLamport for TestNode { fn lamport(&self) -> Lamport { self.lamport } } impl HasLength for TestNode { fn content_len(&self) -> usize { self.len } } impl Sliceable for TestNode { fn slice(&self, from: usize, to: usize) -> Self { Self { id: self.id.inc(from as i32), len: to - from, lamport: self.lamport + from as Lamport, deps: if from == 0 { self.deps.clone() } else { self.id.inc(from as i32 - 1).into() }, } } } #[derive(Debug)] struct TestDag { nodes: BTreeMap, vv: VersionVector, frontier: Frontiers, } impl TestDag { fn new(nodes: impl IntoIterator, frontier: Frontiers) -> Self { let mut vv = VersionVector::default(); let nodes = nodes .into_iter() .map(|node| { vv.set_end(node.id_end()); (node.id_start(), node) }) .collect(); Self { nodes, vv, frontier, } } } impl Dag for TestDag { type Node = TestNode; fn get(&self, id: ID) -> Option { self.nodes .range(..=id) .rev() .find(|(_, node)| node.contains_id(id)) .map(|(_, node)| node.clone()) } fn frontier(&self) -> &Frontiers { &self.frontier } fn vv(&self) -> &VersionVector { &self.vv } fn contains(&self, id: ID) -> bool { self.get(id).is_some() } } fn node( peer: PeerID, counter: Counter, len: usize, lamport: Lamport, deps: Frontiers, ) -> TestNode { TestNode { id: ID::new(peer, counter), len, lamport, deps, } } fn ancestors_of_frontiers(dag: &TestDag, frontiers: &Frontiers) -> FxHashSet { let mut ans = FxHashSet::default(); for id in frontiers.iter() { collect_ancestors(dag, id, &mut ans); } ans } fn collect_ancestors(dag: &TestDag, id: ID, ans: &mut FxHashSet) { let mut stack = vec![id]; let mut visited_targets = FxHashSet::default(); while let Some(id) = stack.pop() { if !visited_targets.insert(id) { continue; } for node in dag.nodes.values() { if node.id_start().peer != id.peer || node.id_start().counter > id.counter { continue; } let end = node.id_last().counter.min(id.counter); for counter in node.id_start().counter..=end { ans.insert(ID::new(node.id_start().peer, counter)); } for dep in node.deps().iter() { stack.push(dep); } } } } fn is_ancestor(dag: &TestDag, ancestor: ID, descendant: ID) -> bool { let mut ancestors = FxHashSet::default(); collect_ancestors(dag, descendant, &mut ancestors); ancestors.contains(&ancestor) } fn maximal_frontiers(dag: &TestDag, ids: impl IntoIterator) -> Frontiers { let mut ids = Vec::::from_iter(ids); ids.sort_by_key(|id| dag.get(*id).unwrap().get_lamport_from_counter(id.counter)); let mut frontiers = Vec::new(); for id in ids.into_iter().rev() { if frontiers .iter() .any(|frontier| is_ancestor(dag, id, *frontier)) { continue; } frontiers.retain(|frontier| !is_ancestor(dag, *frontier, id)); frontiers.push(id); } frontiers.into_iter().collect() } fn oracle_meet(dag: &TestDag, left: &Frontiers, right: &Frontiers) -> Frontiers { let left_ancestors = ancestors_of_frontiers(dag, left); let right_ancestors = ancestors_of_frontiers(dag, right); maximal_frontiers( dag, left_ancestors .into_iter() .filter(|id| right_ancestors.contains(id)), ) } fn assert_replay_base_valid_against_oracle(dag: &TestDag, left: &Frontiers, right: &Frontiers) { let (actual, mode) = dag.find_replay_base(left, right); let expected = oracle_meet(dag, left, right); let left_ancestors = ancestors_of_frontiers(dag, left); let right_ancestors = ancestors_of_frontiers(dag, right); for id in actual.iter() { assert!( left_ancestors.contains(&id) && right_ancestors.contains(&id), "every replay-base id {id} must be common: left={left:?} right={right:?} actual={actual:?} expected={expected:?} mode={mode:?}\ndag={dag:?}", ); } for a in actual.iter() { for b in actual.iter() { if a != b { assert!( !is_ancestor(dag, a, b), "the replay base must be a minimal frontier set: left={left:?} right={right:?} actual={actual:?} expected={expected:?} mode={mode:?}\ndag={dag:?}", ); } } } if !matches!(mode, DiffMode::Checkout) { assert_eq!( actual, expected, "non-checkout mode should use the meet: left={left:?} right={right:?} mode={mode:?}\ndag={dag:?}", ); assert_eq!( &actual, left, "non-checkout mode must use left as the replay base: left={left:?} right={right:?} mode={mode:?}" ); for id in left.iter() { assert!( right_ancestors.contains(&id), "non-checkout mode requires right to include left id {id}; left={left:?} right={right:?} mode={mode:?}", ); } } } fn all_ids(dag: &TestDag) -> Vec { dag.nodes .values() .flat_map(|node| { (0..node.content_len()).map(|offset| node.id_start().inc(offset as Counter)) }) .collect() } fn random_frontiers(dag: &TestDag, ids: &[ID], rng: &mut impl Rng) -> Frontiers { if ids.is_empty() || rng.gen_bool(0.1) { return Frontiers::default(); } let len = rng.gen_range(1..=ids.len().min(4)); maximal_frontiers(dag, (0..len).map(|_| ids[rng.gen_range(0..ids.len())])) } fn random_dag(seed: u64, node_count: usize) -> TestDag { let mut rng = StdRng::seed_from_u64(seed); let mut next_counter = [0 as Counter; 8]; let mut nodes = Vec::new(); let mut existing_ids = Vec::new(); for i in 0..node_count { let peer = rng.gen_range(1..next_counter.len() as PeerID); let counter = next_counter[peer as usize]; let len = rng.gen_range(1..=3); next_counter[peer as usize] += len as Counter; let dep_count = if existing_ids.is_empty() { 0 } else { rng.gen_range(0..=existing_ids.len().min(3)) }; let deps = maximal_frontiers( &TestDag::new(nodes.clone(), Frontiers::default()), (0..dep_count).map(|_| existing_ids[rng.gen_range(0..existing_ids.len())]), ); let node = node(peer, counter, len, i as Lamport * 4, deps); existing_ids.extend((0..len).map(|offset| node.id_start().inc(offset as Counter))); nodes.push(node); } let dag = TestDag::new(nodes, Frontiers::default()); let frontier = maximal_frontiers(&dag, existing_ids); TestDag::new(dag.nodes.into_values(), frontier) } fn layered_merge_dag() -> TestDag { let root = node(1, 0, 3, 0, Frontiers::default()); let left = node(1, 3, 2, 4, ID::new(1, 2).into()); let right = node(2, 0, 3, 5, ID::new(1, 1).into()); let late_right = node(2, 3, 2, 9, ID::new(2, 2).into()); let third = node(3, 0, 2, 6, ID::new(1, 2).into()); let merge_left_right = node( 4, 0, 1, 12, Frontiers::from([left.id_last(), right.id_last()]), ); let merge_all = node( 5, 0, 2, 16, Frontiers::from([ merge_left_right.id_last(), late_right.id_last(), third.id_last(), ]), ); let independent = node(6, 0, 2, 20, Frontiers::default()); let final_merge = node( 7, 0, 1, 25, Frontiers::from([merge_all.id_last(), independent.id_last()]), ); TestDag::new( vec![ root, left, right, late_right, third, merge_left_right, merge_all, independent, final_merge.clone(), ], final_merge.id_last().into(), ) } #[test] fn replay_base_handles_empty_linear_same_span_and_parent_child_cases() { let first = node(1, 0, 2, 0, Frontiers::default()); let second = node(1, 2, 2, 2, ID::new(1, 1).into()); let dag = TestDag::new(vec![first, second], ID::new(1, 3).into()); assert_eq!( dag.find_replay_base(&Frontiers::default(), &ID::new(1, 3).into()), (Frontiers::default(), DiffMode::Linear) ); assert_eq!( dag.find_replay_base(&ID::new(1, 3).into(), &Frontiers::default()), (Frontiers::default(), DiffMode::Checkout) ); assert_eq!( dag.find_replay_base(&ID::new(1, 0).into(), &ID::new(1, 1).into()), (ID::new(1, 0).into(), DiffMode::Linear) ); assert_eq!( dag.find_replay_base(&ID::new(1, 1).into(), &ID::new(1, 0).into()), (ID::new(1, 0).into(), DiffMode::Checkout) ); assert_eq!( dag.find_replay_base(&ID::new(1, 1).into(), &ID::new(1, 3).into()), (ID::new(1, 1).into(), DiffMode::Linear) ); } #[test] fn replay_base_left_empty_stops_linear_scan_at_missing_shallow_dependency() { let visible = node(1, 1, 1, 1, ID::new(1, 0).into()); let dag = TestDag::new(vec![visible], ID::new(1, 1).into()); assert_eq!( dag.find_replay_base(&Frontiers::default(), &ID::new(1, 1).into()), (Frontiers::default(), DiffMode::ImportGreaterUpdates) ); } #[test] fn replay_base_of_parallel_branches_is_shared_dependency() { let root = node(1, 0, 1, 0, Frontiers::default()); let left = node(2, 0, 1, 1, root.id.into()); let right = node(3, 0, 1, 2, root.id.into()); let merge = node(4, 0, 1, 3, Frontiers::from([left.id, right.id])); let dag = TestDag::new( vec![root.clone(), left.clone(), right.clone(), merge.clone()], merge.id.into(), ); let (ancestor, mode) = dag.find_replay_base(&left.id.into(), &right.id.into()); assert_eq!(ancestor, root.id.into()); assert_eq!(mode, DiffMode::Checkout); let (ancestor, _) = dag.find_replay_base(&root.id.into(), &merge.id.into()); assert_eq!(ancestor, root.id.into()); } #[test] fn replay_base_falls_back_before_independent_branch() { let left = node(1, 0, 1, 0, Frontiers::default()); let independent = node(2, 0, 1, 1, Frontiers::default()); let merge = node(3, 0, 1, 2, Frontiers::from([left.id, independent.id])); let dag = TestDag::new( vec![left.clone(), independent, merge.clone()], merge.id.into(), ); let (ancestor, mode) = dag.find_replay_base(&left.id.into(), &merge.id.into()); assert_eq!(ancestor, Frontiers::default()); assert_eq!(mode, DiffMode::Checkout); } #[test] fn replay_base_falls_back_before_unmatched_branch_with_multiple_left_frontiers() { let left_a = node(1, 0, 1, 0, Frontiers::default()); let left_b = node(2, 0, 1, 1, Frontiers::default()); let independent = node(3, 0, 1, 2, Frontiers::default()); let left_frontiers = Frontiers::from([left_a.id, left_b.id]); let merge = node( 4, 0, 1, 3, Frontiers::from([left_a.id, left_b.id, independent.id]), ); let dag = TestDag::new( vec![left_a.clone(), left_b.clone(), independent, merge.clone()], merge.id.into(), ); let (ancestor, mode) = dag.find_replay_base(&left_frontiers, &merge.id.into()); assert_eq!(ancestor, Frontiers::default()); assert_eq!(mode, DiffMode::Checkout); } #[test] fn replay_base_marks_cross_peer_direct_dependency_as_greater_update() { let left = node(1, 0, 1, 0, Frontiers::default()); let right = node(2, 0, 1, 1, left.id.into()); let dag = TestDag::new(vec![left.clone(), right.clone()], right.id.into()); let (ancestor, mode) = dag.find_replay_base(&left.id.into(), &right.id.into()); assert_eq!(ancestor, left.id.into()); assert_eq!(mode, DiffMode::ImportGreaterUpdates); } #[test] fn replay_base_ignores_implicit_predecessor_covered_by_explicit_dependency() { let peer_one_previous = node(1, 0, 1, 0, Frontiers::default()); let relay = node(2, 0, 1, 1, peer_one_previous.id.into()); // This is peer 1's next change, so it implicitly depends on // `peer_one_previous`. Its explicit dependency on `relay` already covers // that predecessor, though, so the two paths are not concurrent. let peer_one_next = node(1, 1, 1, 2, relay.id.into()); let dag = TestDag::new( vec![peer_one_previous, relay.clone(), peer_one_next.clone()], peer_one_next.id.into(), ); let (ancestor, mode) = dag.find_replay_base(&relay.id.into(), &peer_one_next.id.into()); assert_eq!(ancestor, relay.id.into()); assert_eq!(mode, DiffMode::ImportGreaterUpdates); } #[test] fn replay_base_ignores_implicit_predecessor_covered_transitively() { let peer_one_previous = node(1, 0, 1, 0, Frontiers::default()); let first_relay = node(2, 0, 1, 1, peer_one_previous.id.into()); let current_frontier = node(3, 0, 1, 2, first_relay.id.into()); let peer_one_next = node(1, 1, 1, 3, current_frontier.id.into()); let dag = TestDag::new( vec![ peer_one_previous, first_relay, current_frontier.clone(), peer_one_next.clone(), ], peer_one_next.id.into(), ); let (ancestor, mode) = dag.find_replay_base(¤t_frontier.id.into(), &peer_one_next.id.into()); assert_eq!(ancestor, current_frontier.id.into()); assert_eq!(mode, DiffMode::ImportGreaterUpdates); } #[test] fn replay_base_keeps_uncovered_implicit_predecessor_conservative() { let peer_one_previous = node(1, 0, 1, 0, Frontiers::default()); let concurrent = node(2, 0, 1, 1, Frontiers::default()); let peer_one_next = node(1, 1, 1, 2, concurrent.id.into()); let dag = TestDag::new( vec![peer_one_previous, concurrent.clone(), peer_one_next.clone()], peer_one_next.id.into(), ); let (ancestor, mode) = dag.find_replay_base(&concurrent.id.into(), &peer_one_next.id.into()); assert_eq!(ancestor, Frontiers::default()); assert_eq!(mode, DiffMode::Checkout); } #[test] fn replay_base_falls_back_when_right_adds_concurrent_branch_from_shared_root() { let root = node(1, 0, 1, 0, Frontiers::default()); let root_id = root.id; let left = node(2, 0, 1, 1, root.id.into()); let concurrent = node(3, 0, 1, 2, root.id.into()); let merge = node(4, 0, 1, 3, Frontiers::from([left.id, concurrent.id])); let dag = TestDag::new( vec![root, left.clone(), concurrent, merge.clone()], merge.id.into(), ); let (ancestor, mode) = dag.find_replay_base(&left.id.into(), &merge.id.into()); // The conservative base retreats to the latest single-head critical // version below both sides — here the shared root — instead of the // beginning of history. assert_eq!(ancestor, root_id.into()); assert_eq!(mode, DiffMode::Checkout); } #[test] fn replay_base_falls_back_when_right_frontiers_add_concurrent_branch() { let root = node(1, 0, 1, 0, Frontiers::default()); let left = node(2, 0, 1, 1, root.id.into()); let concurrent = node(3, 0, 1, 2, root.id.into()); let right = Frontiers::from([left.id, concurrent.id]); let dag = TestDag::new(vec![root, left.clone(), concurrent], right.clone()); let (ancestor, mode) = dag.find_replay_base(&left.id.into(), &right); // Conservative base = the shared root (latest single-head critical // version), not the beginning of history. assert_eq!(ancestor, ID::new(1, 0).into()); assert_eq!(mode, DiffMode::Checkout); } #[test] fn replay_base_falls_back_when_left_frontiers_add_concurrent_branch() { let root = node(1, 0, 1, 0, Frontiers::default()); let shared = node(2, 0, 1, 1, root.id.into()); let concurrent = node(3, 0, 1, 2, root.id.into()); let left = Frontiers::from([shared.id, concurrent.id]); let dag = TestDag::new(vec![root, shared.clone(), concurrent], left.clone()); // The concurrent left head walks below `shared` without ever meeting the // right side. Only the tip seeded for the multi-element left frontier can // prove it uncovered; the deep node it dies at is itself covered. let (ancestor, mode) = dag.find_replay_base(&left, &shared.id.into()); // Conservative base = the shared root (latest single-head critical // version), not the beginning of history. assert_eq!(ancestor, ID::new(1, 0).into()); assert_eq!(mode, DiffMode::Checkout); } #[test] fn replay_base_falls_back_when_walk_reaches_trimmed_history() { // Peer 9's changes are not present in the DAG, as after shallow trimming. // Both sides die at the missing dependency inside the main walk, which // must force the conservative empty base regardless of tip coverage. let a = node(1, 0, 1, 5, ID::new(9, 5).into()); let b = node(2, 0, 1, 6, ID::new(9, 7).into()); let dag = TestDag::new(vec![a.clone(), b.clone()], Frontiers::from([a.id, b.id])); let (ancestor, mode) = dag.find_replay_base(&a.id.into(), &b.id.into()); assert_eq!(ancestor, Frontiers::default()); assert_eq!(mode, DiffMode::Checkout); } #[test] fn import_greater_updates_requires_new_ops_after_all_left_heads() { // Movable-tree staleness issue shape: B3 → B4..B6 and B3 → A0 → A1..A3. // from = {A0, B6}, to = {A3, B6}. Version inclusion holds // (vv(to) ⊇ vv(from)), yet A1..A3 are concurrent with the left head B6, // so ImportGreaterUpdates must not be claimed: the tree calculator's // fast path would apply A1..A3 without adjudicating against B4..B6. // The base must retreat to the latest critical version {B3}. let b_creates = node(2, 0, 4, 0, Frontiers::default()); let b_moves = node(2, 4, 3, 4, ID::new(2, 3).into()); let a0 = node(1, 0, 1, 4, ID::new(2, 3).into()); let a_moves = node(1, 1, 3, 5, ID::new(1, 0).into()); let dag = TestDag::new( vec![b_creates, b_moves, a0, a_moves], Frontiers::from([ID::new(1, 3), ID::new(2, 6)]), ); let left = Frontiers::from([ID::new(1, 0), ID::new(2, 6)]); let right = Frontiers::from([ID::new(1, 3), ID::new(2, 6)]); let (ancestor, mode) = dag.find_replay_base(&left, &right); assert_eq!(ancestor, ID::new(2, 3).into()); assert_eq!(mode, DiffMode::Checkout); } #[test] fn import_greater_updates_kept_when_new_ops_depend_on_all_left_heads() { // Healthy multi-head import: the new change's deps equal the whole // left frontier, so every new op is causally after all of it and the // fast path must be preserved (entry check passes by set equality). let root = node(1, 0, 1, 0, Frontiers::default()); let x = node(2, 0, 1, 1, ID::new(1, 0).into()); let y = node(3, 0, 1, 1, ID::new(1, 0).into()); let merge = node(4, 0, 1, 2, Frontiers::from([ID::new(2, 0), ID::new(3, 0)])); let dag = TestDag::new(vec![root, x, y, merge], ID::new(4, 0).into()); let left = Frontiers::from([ID::new(2, 0), ID::new(3, 0)]); let (ancestor, mode) = dag.find_replay_base(&left, &ID::new(4, 0).into()); assert_eq!(ancestor, left); assert_eq!(mode, DiffMode::ImportGreaterUpdates); } #[test] fn replay_base_criss_cross_ladder_stays_linear() { // Two peers that each merge both previous heads every round — the shape // ordinary bidirectional sync produces. Branch tips re-merge at every // rung; without deduplication in the tip union the walk is O(2^rounds) // (~minutes at this depth), with it the walk is linear (~microseconds). const ROUNDS: usize = 26; let root = node(3, 0, 1, 0, Frontiers::default()); let mut a_head = node(1, 0, 1, 1, root.id.into()); let mut b_head = node(2, 0, 1, 1, root.id.into()); let mut nodes = vec![root.clone(), a_head.clone(), b_head.clone()]; for k in 1..=ROUNDS { let deps = Frontiers::from([a_head.id_last(), b_head.id_last()]); let lamport = (k as Lamport) * 2; let next_a = node(1, k as Counter, 1, lamport, deps.clone()); let next_b = node(2, k as Counter, 1, lamport, deps); nodes.push(next_a.clone()); nodes.push(next_b.clone()); a_head = next_a; b_head = next_b; } let frontier = Frontiers::from([a_head.id_last(), b_head.id_last()]); let dag = TestDag::new(nodes, frontier.clone()); let start = std::time::Instant::now(); let (ancestor, mode) = dag.find_replay_base(&root.id.into(), &frontier); assert_eq!(ancestor, root.id.into()); assert_eq!(mode, DiffMode::ImportGreaterUpdates); // Generous 4-orders-of-magnitude margin over the fixed cost; the broken // exponential path needs minutes here even in release mode. assert!( start.elapsed() < std::time::Duration::from_secs(10), "criss-cross walk took {:?}; branch-tip growth is no longer linear", start.elapsed() ); } #[test] fn replay_base_keeps_target_when_checking_out_to_ancestor_with_extra_branch() { let root = node(1, 0, 1, 0, Frontiers::default()); let left = node(2, 0, 2, 1, root.id.into()); let right = node(3, 0, 2, 3, root.id.into()); let extra = node( 4, 0, 1, 5, Frontiers::from([left.id_last(), right.id_last()]), ); let dag = TestDag::new( vec![root, left.clone(), right.clone(), extra.clone()], extra.id.into(), ); let target = Frontiers::from([ID::new(2, 0), ID::new(3, 0)]); let current = Frontiers::from([extra.id, left.id_last(), right.id_last()]); let (ancestor, mode) = dag.find_replay_base(¤t, &target); assert_eq!(ancestor, target); assert_eq!(mode, DiffMode::Checkout); } #[test] fn replay_base_does_not_keep_ancestor_of_shared_descendant() { let root = node(1, 0, 1, 0, Frontiers::default()); let shared = node(2, 0, 1, 1, root.id.into()); let left_only = node(3, 0, 1, 2, root.id.into()); let right_only = node(4, 0, 1, 3, root.id.into()); let dag = TestDag::new( vec![root, shared.clone(), left_only.clone(), right_only.clone()], Frontiers::from([shared.id, left_only.id, right_only.id]), ); let (ancestor, mode) = dag.find_replay_base( &Frontiers::from([shared.id, left_only.id]), &Frontiers::from([shared.id, right_only.id]), ); assert_eq!(ancestor, shared.id.into()); assert_eq!(mode, DiffMode::Checkout); } #[test] fn replay_base_valid_against_slow_oracle_on_random_dags() { for seed in 0..128 { let mut rng = StdRng::seed_from_u64(seed); let dag = random_dag(seed, rng.gen_range(1..=18)); let ids = all_ids(&dag); for _ in 0..64 { let left = random_frontiers(&dag, &ids, &mut rng); let right = random_frontiers(&dag, &ids, &mut rng); assert_replay_base_valid_against_oracle(&dag, &left, &right); } } } #[test] fn replay_base_valid_against_slow_oracle_on_all_pairs_in_small_random_dags() { for seed in 1000..1020 { let dag = random_dag(seed, 8); let ids = all_ids(&dag); let mut frontiers = vec![Frontiers::default()]; frontiers.extend(ids.iter().copied().map(Frontiers::from)); for chunk in ids.chunks(3) { frontiers.push(maximal_frontiers(&dag, chunk.iter().copied())); } for left in frontiers.iter() { for right in frontiers.iter() { assert_replay_base_valid_against_oracle(&dag, left, right); } } } } #[test] fn replay_base_valid_against_slow_oracle_on_layered_merge_dag() { let dag = layered_merge_dag(); let ids = all_ids(&dag); let mut frontiers = vec![Frontiers::default(), dag.frontier().clone()]; frontiers.extend(ids.iter().copied().map(Frontiers::from)); frontiers.extend([ Frontiers::from([ID::new(1, 4), ID::new(2, 2)]), Frontiers::from([ID::new(1, 4), ID::new(3, 1)]), Frontiers::from([ID::new(4, 0), ID::new(2, 4), ID::new(3, 1)]), Frontiers::from([ID::new(5, 1), ID::new(6, 1)]), ]); for left in frontiers.iter() { for right in frontiers.iter() { assert_replay_base_valid_against_oracle(&dag, left, right); } } } #[test] fn replay_base_valid_against_slow_oracle_on_branchy_random_dags() { for seed in 2000..2064 { let mut rng = StdRng::seed_from_u64(seed); let dag = random_dag(seed, rng.gen_range(20..=36)); let ids = all_ids(&dag); for _ in 0..96 { let left = random_frontiers(&dag, &ids, &mut rng); let right = random_frontiers(&dag, &ids, &mut rng); assert_replay_base_valid_against_oracle(&dag, &left, &right); } } } #[test] fn find_path_reports_forward_and_retreat_spans_for_linear_and_branch_paths() { let first = node(1, 0, 2, 0, Frontiers::default()); let second = node(1, 2, 2, 2, ID::new(1, 1).into()); let side = node(2, 0, 1, 1, ID::new(1, 1).into()); let dag = TestDag::new( vec![first, second, side], Frontiers::from([ID::new(1, 3), ID::new(2, 0)]), ); let forward = dag.find_path(&ID::new(1, 0).into(), &ID::new(1, 3).into()); assert!(forward.retreat.is_empty()); assert_eq!(forward.forward.get(&1), Some(&CounterSpan::new(1, 4))); let retreat = dag.find_path(&ID::new(1, 3).into(), &ID::new(1, 0).into()); assert!(retreat.forward.is_empty()); assert_eq!(retreat.retreat.get(&1), Some(&CounterSpan::new(1, 4))); let branch = dag.find_path(&ID::new(2, 0).into(), &ID::new(1, 3).into()); assert_eq!(branch.retreat.get(&2), Some(&CounterSpan::new(0, 1))); assert_eq!(branch.forward.get(&1), Some(&CounterSpan::new(2, 4))); } #[test] fn get_version_vector_walks_dependencies_once_and_tracks_dep_ids_inside_spans() { let base = node(1, 0, 3, 0, Frontiers::default()); let left = node(2, 0, 1, 4, ID::new(1, 1).into()); let right = node(3, 0, 1, 5, ID::new(1, 2).into()); let merge = node(4, 0, 1, 6, Frontiers::from([left.id, right.id])); let dag = TestDag::new(vec![base, left, right, merge.clone()], merge.id.into()); let vv = dag.get_vv(merge.id); assert_eq!(vv.get_last(1), Some(2)); assert_eq!(vv.get_last(2), Some(0)); assert_eq!(vv.get_last(3), Some(0)); assert_eq!(vv.get_last(4), Some(0)); } #[test] fn remove_included_frontiers_drops_only_dependencies_at_or_after_recorded_frontiers() { let mut vv = VersionVector::default(); vv.set_last(ID::new(1, 3)); vv.set_last(ID::new(2, 4)); vv.set_last(ID::new(3, 1)); remove_included_frontiers(&mut vv, &[ID::new(1, 3), ID::new(2, 2), ID::new(4, 0)]); assert_eq!(vv.get_last(1), None); assert_eq!(vv.get_last(2), Some(4)); assert_eq!(vv.get_last(3), Some(1)); } #[test] fn ord_id_span_orders_by_last_lamport_peer_and_shorter_overlapping_span() { let short = OrdIdSpan { id: ID::new(1, 1), lamport: 1, len: 1, deps: Cow::Owned(Frontiers::default()), }; let long = OrdIdSpan { id: ID::new(1, 0), lamport: 0, len: 2, deps: Cow::Owned(Frontiers::default()), }; let later_peer = OrdIdSpan { id: ID::new(2, 0), lamport: 1, len: 1, deps: Cow::Owned(Frontiers::default()), }; assert!(short > long); assert!(later_peer > short); assert_eq!(long.get_min().len, 1); } }