project_note
Clone
https://git.tahinli.com/Tahinli/project_note.git
0 watching·0 forks·Rust·3.6 MiB·c49f5e7·Tahinli·1 month ago·2 commits
| 1 | //! DAG (Directed Acyclic Graph) is a common data structure in distributed system. |
| 2 | //! |
| 3 | //! This mod contains the DAGs in our CRDT. It's not a general DAG, it has some specific properties that |
| 4 | //! we used to optimize the speed: |
| 5 | //! - Each node has lamport clock. |
| 6 | //! - Each node has its ID (client_id, counter). |
| 7 | //! - We use ID to refer to node rather than content addressing (hash) |
| 8 | //! |
| 9 | use std::{ |
| 10 | borrow::Cow, |
| 11 | collections::{BinaryHeap, HashMap}, |
| 12 | fmt::Debug, |
| 13 | }; |
| 14 | |
| 15 | use loro_common::{IdSpanVector, LoroError, LoroResult}; |
| 16 | use rle::{HasLength, Sliceable}; |
| 17 | use rustc_hash::{FxHashMap, FxHashSet}; |
| 18 | mod iter; |
| 19 | pub(crate) use iter::DagCausalIter; |
| 20 | mod mermaid; |
| 21 | #[cfg(feature = "test_utils")] |
| 22 | mod test; |
| 23 | #[cfg(feature = "test_utils")] |
| 24 | pub use test::{fuzz_alloc_tree, Interaction}; |
| 25 | |
| 26 | use crate::{ |
| 27 | change::Lamport, |
| 28 | diff_calc::DiffMode, |
| 29 | id::{Counter, PeerID, ID}, |
| 30 | span::{CounterSpan, HasId, HasIdSpan, HasLamport, HasLamportSpan, IdSpan}, |
| 31 | version::{Frontiers, VersionVector, VersionVectorDiff}, |
| 32 | }; |
| 33 | |
| 34 | use self::{ |
| 35 | iter::{iter_dag, iter_dag_with_vv, DagIterator, DagIteratorVV}, |
| 36 | mermaid::dag_to_mermaid, |
| 37 | }; |
| 38 | |
| 39 | pub(crate) trait DagNode: HasLamport + HasId + HasLength + Debug + Sliceable { |
| 40 | fn deps(&self) -> &Frontiers; |
| 41 | |
| 42 | #[allow(unused)] |
| 43 | #[inline] |
| 44 | fn get_lamport_from_counter(&self, c: Counter) -> Lamport { |
| 45 | self.lamport() + c as Lamport - self.id_start().counter as Lamport |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | /// Dag (Directed Acyclic Graph). |
| 50 | /// |
| 51 | /// We have following invariance in DAG |
| 52 | /// - All deps' lamports are smaller than current node's lamport |
| 53 | pub(crate) trait Dag: Debug { |
| 54 | type Node: DagNode; |
| 55 | |
| 56 | fn get(&self, id: ID) -> Option<Self::Node>; |
| 57 | fn try_get(&self, id: ID) -> LoroResult<Option<Self::Node>> { |
| 58 | Ok(self.get(id)) |
| 59 | } |
| 60 | #[allow(unused)] |
| 61 | fn frontier(&self) -> &Frontiers; |
| 62 | fn vv(&self) -> &VersionVector; |
| 63 | fn contains(&self, id: ID) -> bool; |
| 64 | } |
| 65 | |
| 66 | /// Whether the meet of two versions can serve as the replay base between them. |
| 67 | #[derive(Debug)] |
| 68 | pub(crate) enum MeetAsBase { |
| 69 | /// The meet is a valid replay base for the returned diff mode. That makes |
| 70 | /// it a critical version only in non-`Checkout` modes (spec S3). In |
| 71 | /// `Checkout` mode it is just the meet, and ops above it may be concurrent |
| 72 | /// with one of its heads; checkout consumers accept that (spec Q7). |
| 73 | Valid(Frontiers), |
| 74 | /// A concurrent branch crosses the meet, so replaying from it would |
| 75 | /// leave concurrency unadjudicated. The caller must retreat to a critical |
| 76 | /// version below it (see `docs/critical-version-spec.md`). |
| 77 | NeedsCriticalRetreat, |
| 78 | } |
| 79 | |
| 80 | pub(crate) trait DagUtils: Dag { |
| 81 | /// The replay base for diffing `a_id` into `b_id`: the meet when it is a |
| 82 | /// valid base for the diff mode, else the latest single-head critical |
| 83 | /// version. |
| 84 | /// |
| 85 | /// This is NOT always a critical version: in `DiffMode::Checkout` it may be |
| 86 | /// a meet with concurrent ops above it (see [`MeetAsBase::Valid`]). Callers |
| 87 | /// that need every other op to be before or after the result, such as the |
| 88 | /// shallow snapshot root, must use |
| 89 | /// [`Self::latest_single_head_critical_version`] (loro-dev/loro#1095). |
| 90 | /// |
| 91 | /// Only the DAG tests call it: the tree calculator used to, and now takes its |
| 92 | /// window from the two versions (`context/tree-checkout-window.md`). |
| 93 | #[cfg(test)] |
| 94 | fn find_replay_base(&self, a_id: &Frontiers, b_id: &Frontiers) -> (Frontiers, DiffMode); |
| 95 | /// Like `find_replay_base`, but leaves the conservative |
| 96 | /// fallback to the caller: on [`MeetAsBase::NeedsCriticalRetreat`] the |
| 97 | /// caller must retreat to a critical version (via |
| 98 | /// [`Self::latest_single_head_critical_version`], or a cheaper multi-head |
| 99 | /// one it can find itself). Finding the single-head cut walks the whole |
| 100 | /// DAG, so callers that usually have a better answer should not pay for |
| 101 | /// it up front. |
| 102 | #[cfg(test)] |
| 103 | fn find_meet_and_mode(&self, a_id: &Frontiers, b_id: &Frontiers) -> (MeetAsBase, DiffMode) { |
| 104 | self.try_find_meet_and_mode(a_id, b_id).unwrap() |
| 105 | } |
| 106 | fn try_find_meet_and_mode( |
| 107 | &self, |
| 108 | a_id: &Frontiers, |
| 109 | b_id: &Frontiers, |
| 110 | ) -> LoroResult<(MeetAsBase, DiffMode)>; |
| 111 | #[cfg(test)] |
| 112 | fn latest_single_head_critical_version(&self, a_id: &Frontiers, b_id: &Frontiers) -> Frontiers { |
| 113 | self.try_latest_single_head_critical_version(a_id, b_id) |
| 114 | .unwrap() |
| 115 | } |
| 116 | fn try_latest_single_head_critical_version( |
| 117 | &self, |
| 118 | a_id: &Frontiers, |
| 119 | b_id: &Frontiers, |
| 120 | ) -> LoroResult<Frontiers>; |
| 121 | /// Slow, should probably only use on dev |
| 122 | #[allow(unused)] |
| 123 | fn get_vv(&self, id: ID) -> VersionVector; |
| 124 | #[allow(unused)] |
| 125 | fn find_path(&self, from: &Frontiers, to: &Frontiers) -> VersionVectorDiff { |
| 126 | self.try_find_path(from, to).unwrap() |
| 127 | } |
| 128 | fn try_find_path(&self, from: &Frontiers, to: &Frontiers) -> LoroResult<VersionVectorDiff>; |
| 129 | #[cfg(test)] |
| 130 | fn iter_causal(&self, from: Frontiers, target: IdSpanVector) -> DagCausalIter<'_, Self> |
| 131 | where |
| 132 | Self: Sized; |
| 133 | #[allow(unused)] |
| 134 | fn iter(&self) -> DagIterator<'_, Self::Node> |
| 135 | where |
| 136 | Self: Sized; |
| 137 | #[allow(unused)] |
| 138 | fn iter_with_vv(&self) -> DagIteratorVV<'_, Self::Node> |
| 139 | where |
| 140 | Self: Sized; |
| 141 | #[allow(unused)] |
| 142 | fn mermaid(&self) -> String |
| 143 | where |
| 144 | Self: Sized; |
| 145 | } |
| 146 | |
| 147 | impl<T: Dag + ?Sized> DagUtils for T { |
| 148 | #[cfg(test)] |
| 149 | #[inline] |
| 150 | fn find_replay_base(&self, a_id: &Frontiers, b_id: &Frontiers) -> (Frontiers, DiffMode) { |
| 151 | // TODO: perf: make it also return the spans to reach the replay base |
| 152 | let (meet, mode) = self.find_meet_and_mode(a_id, b_id); |
| 153 | let base = match meet { |
| 154 | MeetAsBase::Valid(meet) => meet, |
| 155 | MeetAsBase::NeedsCriticalRetreat => { |
| 156 | self.latest_single_head_critical_version(a_id, b_id) |
| 157 | } |
| 158 | }; |
| 159 | (base, mode) |
| 160 | } |
| 161 | |
| 162 | #[inline] |
| 163 | fn try_find_meet_and_mode( |
| 164 | &self, |
| 165 | a_id: &Frontiers, |
| 166 | b_id: &Frontiers, |
| 167 | ) -> LoroResult<(MeetAsBase, DiffMode)> { |
| 168 | find_meet_and_mode(&|id| self.try_get(id), a_id, b_id) |
| 169 | } |
| 170 | |
| 171 | #[inline] |
| 172 | fn try_latest_single_head_critical_version( |
| 173 | &self, |
| 174 | a_id: &Frontiers, |
| 175 | b_id: &Frontiers, |
| 176 | ) -> LoroResult<Frontiers> { |
| 177 | latest_single_head_critical_version(&|id| self.try_get(id), a_id, b_id) |
| 178 | } |
| 179 | |
| 180 | #[inline] |
| 181 | fn get_vv(&self, id: ID) -> VersionVector { |
| 182 | get_version_vector(&|id| self.get(id), id) |
| 183 | } |
| 184 | |
| 185 | fn try_find_path(&self, from: &Frontiers, to: &Frontiers) -> LoroResult<VersionVectorDiff> { |
| 186 | let mut ans = VersionVectorDiff::default(); |
| 187 | if from == to { |
| 188 | return Ok(ans); |
| 189 | } |
| 190 | |
| 191 | if from.len() == 1 && to.len() == 1 { |
| 192 | let from = from.as_single().unwrap(); |
| 193 | let to = to.as_single().unwrap(); |
| 194 | if from.peer == to.peer { |
| 195 | let from_span = self |
| 196 | .try_get(from)? |
| 197 | .ok_or(LoroError::FrontiersNotFound(from))?; |
| 198 | let to_span = self.try_get(to)?.ok_or(LoroError::FrontiersNotFound(to))?; |
| 199 | if from_span.id_start() == to_span.id_start() { |
| 200 | if from.counter < to.counter { |
| 201 | ans.forward.insert( |
| 202 | from.peer, |
| 203 | CounterSpan::new(from.counter + 1, to.counter + 1), |
| 204 | ); |
| 205 | } else { |
| 206 | ans.retreat.insert( |
| 207 | from.peer, |
| 208 | CounterSpan::new(to.counter + 1, from.counter + 1), |
| 209 | ); |
| 210 | } |
| 211 | return Ok(ans); |
| 212 | } |
| 213 | |
| 214 | if from_span.deps().len() == 1 |
| 215 | && to_span.contains_id(from_span.deps().as_single().unwrap()) |
| 216 | { |
| 217 | ans.retreat.insert( |
| 218 | from.peer, |
| 219 | CounterSpan::new(to.counter + 1, from.counter + 1), |
| 220 | ); |
| 221 | return Ok(ans); |
| 222 | } |
| 223 | |
| 224 | if to_span.deps().len() == 1 |
| 225 | && from_span.contains_id(to_span.deps().as_single().unwrap()) |
| 226 | { |
| 227 | ans.forward.insert( |
| 228 | from.peer, |
| 229 | CounterSpan::new(from.counter + 1, to.counter + 1), |
| 230 | ); |
| 231 | return Ok(ans); |
| 232 | } |
| 233 | } |
| 234 | } |
| 235 | |
| 236 | _walk_to_meet( |
| 237 | &|v| self.try_get(v), |
| 238 | from, |
| 239 | to, |
| 240 | &mut |span, node_type| match node_type { |
| 241 | NodeType::A => ans.merge_left(span), |
| 242 | NodeType::B => ans.merge_right(span), |
| 243 | NodeType::Shared => { |
| 244 | ans.subtract_start_left(span); |
| 245 | ans.subtract_start_right(span); |
| 246 | } |
| 247 | }, |
| 248 | true, |
| 249 | )?; |
| 250 | |
| 251 | Ok(ans) |
| 252 | } |
| 253 | |
| 254 | #[inline(always)] |
| 255 | fn iter_with_vv(&self) -> DagIteratorVV<'_, Self::Node> |
| 256 | where |
| 257 | Self: Sized, |
| 258 | { |
| 259 | iter_dag_with_vv(self) |
| 260 | } |
| 261 | |
| 262 | #[inline(always)] |
| 263 | #[cfg(test)] |
| 264 | fn iter_causal(&self, from: Frontiers, target: IdSpanVector) -> DagCausalIter<'_, Self> |
| 265 | where |
| 266 | Self: Sized, |
| 267 | { |
| 268 | DagCausalIter::new(self, from, target) |
| 269 | } |
| 270 | |
| 271 | #[inline(always)] |
| 272 | fn iter(&self) -> DagIterator<'_, Self::Node> |
| 273 | where |
| 274 | Self: Sized, |
| 275 | { |
| 276 | iter_dag(self) |
| 277 | } |
| 278 | |
| 279 | /// You can visualize and generate img link at https://mermaid.live/ |
| 280 | #[inline] |
| 281 | fn mermaid(&self) -> String |
| 282 | where |
| 283 | Self: Sized, |
| 284 | { |
| 285 | dag_to_mermaid(self) |
| 286 | } |
| 287 | } |
| 288 | |
| 289 | #[allow(dead_code)] |
| 290 | fn get_version_vector<'a, Get, D>(get: &'a Get, id: ID) -> VersionVector |
| 291 | where |
| 292 | Get: Fn(ID) -> Option<D>, |
| 293 | D: DagNode + 'a, |
| 294 | { |
| 295 | let mut vv = VersionVector::new(); |
| 296 | let mut visited: FxHashSet<ID> = FxHashSet::default(); |
| 297 | vv.insert(id.peer, id.counter + 1); |
| 298 | let node = get(id).unwrap(); |
| 299 | |
| 300 | if node.deps().is_empty() { |
| 301 | return vv; |
| 302 | } |
| 303 | |
| 304 | let mut stack = Vec::with_capacity(node.deps().len()); |
| 305 | for dep in node.deps().iter() { |
| 306 | stack.push(dep); |
| 307 | } |
| 308 | |
| 309 | while let Some(node_id) = stack.pop() { |
| 310 | let node = get(node_id).unwrap(); |
| 311 | let node_id_start = node.id_start(); |
| 312 | vv.try_update_last(node_id); |
| 313 | if !visited.contains(&node_id_start) { |
| 314 | for dep in node.deps().iter() { |
| 315 | if !visited.contains(&dep) { |
| 316 | stack.push(dep); |
| 317 | } |
| 318 | } |
| 319 | |
| 320 | visited.insert(node_id_start); |
| 321 | } |
| 322 | } |
| 323 | |
| 324 | vv |
| 325 | } |
| 326 | |
| 327 | #[derive(Debug, PartialEq, Eq)] |
| 328 | struct OrdIdSpan<'a> { |
| 329 | id: ID, |
| 330 | lamport: Lamport, |
| 331 | len: usize, |
| 332 | deps: Cow<'a, Frontiers>, |
| 333 | } |
| 334 | |
| 335 | impl HasLength for OrdIdSpan<'_> { |
| 336 | fn content_len(&self) -> usize { |
| 337 | self.len |
| 338 | } |
| 339 | } |
| 340 | |
| 341 | impl HasId for OrdIdSpan<'_> { |
| 342 | fn id_start(&self) -> ID { |
| 343 | self.id |
| 344 | } |
| 345 | } |
| 346 | |
| 347 | impl HasLamport for OrdIdSpan<'_> { |
| 348 | fn lamport(&self) -> Lamport { |
| 349 | self.lamport |
| 350 | } |
| 351 | } |
| 352 | |
| 353 | impl PartialOrd for OrdIdSpan<'_> { |
| 354 | fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { |
| 355 | Some(self.cmp(other)) |
| 356 | } |
| 357 | } |
| 358 | |
| 359 | impl Ord for OrdIdSpan<'_> { |
| 360 | fn cmp(&self, other: &Self) -> std::cmp::Ordering { |
| 361 | self.lamport_last() |
| 362 | .cmp(&other.lamport_last()) |
| 363 | .then(self.id.peer.cmp(&other.id.peer)) |
| 364 | // If they have the same last id, we want the shorter one to be greater; |
| 365 | // Otherwise, find_replay_base won't work correctly. Because we may |
| 366 | // lazily load the dag node, so sometimes the longer one should be broken |
| 367 | // into smaller pieces but it's already pushed to the queue. |
| 368 | .then(other.len.cmp(&self.len)) |
| 369 | } |
| 370 | } |
| 371 | |
| 372 | #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)] |
| 373 | enum NodeType { |
| 374 | A, |
| 375 | B, |
| 376 | Shared, |
| 377 | } |
| 378 | |
| 379 | impl<'a> OrdIdSpan<'a> { |
| 380 | #[inline] |
| 381 | fn from_dag_node<D, F>(id: ID, get: &'a F) -> LoroResult<Option<OrdIdSpan<'a>>> |
| 382 | where |
| 383 | D: DagNode + 'a, |
| 384 | F: Fn(ID) -> LoroResult<Option<D>>, |
| 385 | { |
| 386 | let Some(span) = get(id)? else { |
| 387 | return Ok(None); |
| 388 | }; |
| 389 | let span_id = span.id_start(); |
| 390 | Ok(Some(OrdIdSpan { |
| 391 | id: span_id, |
| 392 | lamport: span.lamport(), |
| 393 | deps: Cow::Owned(span.deps().clone()), |
| 394 | len: (id.counter - span_id.counter) as usize + 1, |
| 395 | })) |
| 396 | } |
| 397 | |
| 398 | #[inline] |
| 399 | fn get_min(&self) -> OrdIdSpan<'a> { |
| 400 | OrdIdSpan { |
| 401 | id: self.id, |
| 402 | lamport: self.lamport, |
| 403 | deps: Cow::Owned(Default::default()), |
| 404 | len: 1, |
| 405 | } |
| 406 | } |
| 407 | } |
| 408 | |
| 409 | #[inline(always)] |
| 410 | fn find_meet_and_mode<'a, F, D>( |
| 411 | get: &'a F, |
| 412 | a_id: &Frontiers, |
| 413 | b_id: &Frontiers, |
| 414 | ) -> LoroResult<(MeetAsBase, DiffMode)> |
| 415 | where |
| 416 | D: DagNode + 'a, |
| 417 | F: Fn(ID) -> LoroResult<Option<D>>, |
| 418 | { |
| 419 | if b_id.is_empty() { |
| 420 | return Ok((MeetAsBase::Valid(Default::default()), DiffMode::Checkout)); |
| 421 | } |
| 422 | |
| 423 | _find_meet_and_mode(get, a_id, b_id) |
| 424 | } |
| 425 | |
| 426 | /// - deep whether keep searching until the min of non-shared node is found |
| 427 | fn _walk_to_meet<'a, F, D, G>( |
| 428 | get: &'a F, |
| 429 | a_ids: &Frontiers, |
| 430 | b_ids: &Frontiers, |
| 431 | notify: &mut G, |
| 432 | find_path: bool, |
| 433 | ) -> LoroResult<FxHashMap<PeerID, Counter>> |
| 434 | where |
| 435 | D: DagNode + 'a, |
| 436 | F: Fn(ID) -> LoroResult<Option<D>>, |
| 437 | G: FnMut(IdSpan, NodeType), |
| 438 | { |
| 439 | let mut ans: FxHashMap<PeerID, Counter> = Default::default(); |
| 440 | let mut queue: BinaryHeap<(OrdIdSpan, NodeType)> = BinaryHeap::new(); |
| 441 | for id in a_ids.iter() { |
| 442 | queue.push((OrdIdSpan::from_dag_node(id, get)?.unwrap(), NodeType::A)); |
| 443 | } |
| 444 | for id in b_ids.iter() { |
| 445 | queue.push((OrdIdSpan::from_dag_node(id, get)?.unwrap(), NodeType::B)); |
| 446 | } |
| 447 | let mut visited: HashMap<PeerID, (Counter, NodeType), _> = FxHashMap::default(); |
| 448 | // invariants in this method: |
| 449 | // |
| 450 | // - visited's (client, counters) are subset of max(version_vector_a, version_vector_b) |
| 451 | // - visited's node type reflecting whether we found the shared node of this client |
| 452 | // - ans's client id never repeat |
| 453 | // - nodes with the same id will only be visited once |
| 454 | // - we may visit nodes that are before the meet |
| 455 | |
| 456 | // type count in the queue. if both are zero, we can stop |
| 457 | let mut a_count = a_ids.len(); |
| 458 | let mut b_count = b_ids.len(); |
| 459 | let mut min = None; |
| 460 | while let Some((node, mut node_type)) = queue.pop() { |
| 461 | match node_type { |
| 462 | NodeType::A => a_count -= 1, |
| 463 | NodeType::B => b_count -= 1, |
| 464 | NodeType::Shared => {} |
| 465 | } |
| 466 | |
| 467 | if node_type != NodeType::Shared { |
| 468 | if let Some(min) = &mut min { |
| 469 | let node_start = node.get_min(); |
| 470 | if node_start < *min { |
| 471 | *min = node_start; |
| 472 | } |
| 473 | } else { |
| 474 | min = Some(node.get_min()) |
| 475 | } |
| 476 | } |
| 477 | |
| 478 | // pop the same node in the queue |
| 479 | while let Some((other_node, other_type)) = queue.peek() { |
| 480 | if node.id_span() == other_node.id_span() { |
| 481 | if node_type == *other_type { |
| 482 | match node_type { |
| 483 | NodeType::A => a_count -= 1, |
| 484 | NodeType::B => b_count -= 1, |
| 485 | NodeType::Shared => {} |
| 486 | } |
| 487 | } else { |
| 488 | if node_type != NodeType::Shared { |
| 489 | if visited.get(&node.id.peer).map(|(_, t)| *t) != Some(NodeType::Shared) { |
| 490 | ans.insert(node.id.peer, other_node.id_last().counter); |
| 491 | } |
| 492 | node_type = NodeType::Shared; |
| 493 | } |
| 494 | match other_type { |
| 495 | NodeType::A => a_count -= 1, |
| 496 | NodeType::B => b_count -= 1, |
| 497 | NodeType::Shared => {} |
| 498 | } |
| 499 | } |
| 500 | |
| 501 | queue.pop(); |
| 502 | } else { |
| 503 | break; |
| 504 | } |
| 505 | } |
| 506 | |
| 507 | // detect whether client is visited by other |
| 508 | if let Some((ctr, visited_type)) = visited.get_mut(&node.id.peer) { |
| 509 | debug_assert!(*ctr >= node.id_last().counter); |
| 510 | if *visited_type == NodeType::Shared { |
| 511 | node_type = NodeType::Shared; |
| 512 | } else if *visited_type != node_type { |
| 513 | // if node_type is shared, ans should already contains it or its descendance |
| 514 | if node_type != NodeType::Shared { |
| 515 | ans.insert(node.id.peer, node.id_last().counter); |
| 516 | } |
| 517 | *visited_type = NodeType::Shared; |
| 518 | node_type = NodeType::Shared; |
| 519 | } |
| 520 | } else { |
| 521 | visited.insert(node.id.peer, (node.id_last().counter, node_type)); |
| 522 | } |
| 523 | |
| 524 | // if this is not shared, the end of the span must be only reachable from A, or only reachable from B. |
| 525 | // but the begin of the span may be reachable from both A and B |
| 526 | notify(node.id_span(), node_type); |
| 527 | |
| 528 | match node_type { |
| 529 | NodeType::A => a_count += node.deps.len(), |
| 530 | NodeType::B => b_count += node.deps.len(), |
| 531 | NodeType::Shared => {} |
| 532 | } |
| 533 | |
| 534 | if a_count == 0 && b_count == 0 && (min.is_none() || &node <= min.as_ref().unwrap()) { |
| 535 | if node_type != NodeType::Shared { |
| 536 | ans.clear(); |
| 537 | } |
| 538 | |
| 539 | break; |
| 540 | } |
| 541 | |
| 542 | for dep_id in node.deps.as_ref().iter() { |
| 543 | queue.push((OrdIdSpan::from_dag_node(dep_id, get)?.unwrap(), node_type)); |
| 544 | } |
| 545 | |
| 546 | if node_type != NodeType::Shared { |
| 547 | if queue.is_empty() { |
| 548 | ans.clear(); |
| 549 | break; |
| 550 | } |
| 551 | if node.deps.is_empty() && !find_path { |
| 552 | if node.len == 1 { |
| 553 | ans.clear(); |
| 554 | break; |
| 555 | } |
| 556 | |
| 557 | match node_type { |
| 558 | NodeType::A => a_count += 1, |
| 559 | NodeType::B => b_count += 1, |
| 560 | NodeType::Shared => {} |
| 561 | } |
| 562 | |
| 563 | queue.push(( |
| 564 | OrdIdSpan { |
| 565 | deps: Cow::Owned(Default::default()), |
| 566 | id: node.id, |
| 567 | len: 1, |
| 568 | lamport: node.lamport, |
| 569 | }, |
| 570 | node_type, |
| 571 | )); |
| 572 | } |
| 573 | } |
| 574 | } |
| 575 | |
| 576 | Ok(ans) |
| 577 | } |
| 578 | |
| 579 | /// Resolves each frontier id to the span of its containing node, truncated at |
| 580 | /// that id. Returns `None` when an id is unavailable (trimmed history). |
| 581 | fn ids_to_ord_id_spans<'a, D: DagNode + 'a, F: Fn(ID) -> LoroResult<Option<D>>>( |
| 582 | ids: &Frontiers, |
| 583 | get: &'a F, |
| 584 | ) -> LoroResult<Option<Vec<OrdIdSpan<'a>>>> { |
| 585 | let mut ans = Vec::with_capacity(ids.len()); |
| 586 | for id in ids.iter() { |
| 587 | if let Some(node) = OrdIdSpan::from_dag_node(id, get)? { |
| 588 | ans.push(node); |
| 589 | } else { |
| 590 | return Ok(None); |
| 591 | } |
| 592 | } |
| 593 | |
| 594 | Ok(Some(ans)) |
| 595 | } |
| 596 | |
| 597 | /// The parent set of a span's first op: the node's explicit deps plus the |
| 598 | /// implicit same-peer predecessor when it is not already covered by one of them. |
| 599 | fn deps_to_ord_id_spans<'a, D: DagNode + 'a, F: Fn(ID) -> LoroResult<Option<D>>>( |
| 600 | node: &OrdIdSpan<'a>, |
| 601 | get: &'a F, |
| 602 | ) -> LoroResult<Option<Vec<OrdIdSpan<'a>>>> { |
| 603 | let Some(mut deps) = ids_to_ord_id_spans(node.deps.as_ref(), get)? else { |
| 604 | return Ok(None); |
| 605 | }; |
| 606 | if node.id.counter > 0 { |
| 607 | let prev = node.id.inc(-1); |
| 608 | if let Some(prev) = OrdIdSpan::from_dag_node(prev, get)? { |
| 609 | if !deps.iter().any(|dep| dep.contains_id(prev.id_last())) { |
| 610 | deps.push(prev); |
| 611 | } |
| 612 | } |
| 613 | } |
| 614 | |
| 615 | Ok(Some(deps)) |
| 616 | } |
| 617 | |
| 618 | /// The latest single-head critical version (Eg-walker §3.5/§3.6) of the |
| 619 | /// union graph `ancestry(left) ∪ ancestry(right)`: the newest event `v` |
| 620 | /// such that every other event in the union is an ancestor of `v` or |
| 621 | /// causally after `v`. Replaying from `{v}` is safe because no concurrency |
| 622 | /// crosses it, and it skips the fully-synced prefix of common history that |
| 623 | /// the old `∅` fallback would replay. |
| 624 | /// |
| 625 | /// Method: a one-colour descent from both frontiers using the same |
| 626 | /// coalesce/align machinery as the main walk. The pending heap is always a |
| 627 | /// cut of the unexplored region, so the first moment it narrows to a |
| 628 | /// single span, that span's `id_last` is the latest such `v`. If a chain |
| 629 | /// dies at a root or at trimmed history while other chains remain, its |
| 630 | /// endpoint is concurrent with everything below the current level, so no |
| 631 | /// later singleton can be valid — bail out to the empty version, which is |
| 632 | /// the old behaviour. |
| 633 | fn latest_single_head_critical_version<'a, D: DagNode + 'a, F: Fn(ID) -> LoroResult<Option<D>>>( |
| 634 | get: &'a F, |
| 635 | left: &Frontiers, |
| 636 | right: &Frontiers, |
| 637 | ) -> LoroResult<Frontiers> { |
| 638 | let mut queue: BinaryHeap<OrdIdSpan> = BinaryHeap::new(); |
| 639 | let Some(spans) = ids_to_ord_id_spans(left, get)? else { |
| 640 | return Ok(Default::default()); |
| 641 | }; |
| 642 | queue.extend(spans); |
| 643 | let Some(spans) = ids_to_ord_id_spans(right, get)? else { |
| 644 | return Ok(Default::default()); |
| 645 | }; |
| 646 | queue.extend(spans); |
| 647 | |
| 648 | while let Some(mut node) = queue.pop() { |
| 649 | while let Some(other) = queue.peek() { |
| 650 | if node == *other || node.id_last() == other.id_last() { |
| 651 | queue.pop(); |
| 652 | } else { |
| 653 | break; |
| 654 | } |
| 655 | } |
| 656 | |
| 657 | if queue.is_empty() { |
| 658 | return Ok(node.id_last().into()); |
| 659 | } |
| 660 | |
| 661 | if let Some(other) = queue.peek() { |
| 662 | if node.contains_id(other.id_last()) { |
| 663 | node.len = (other.id_last().counter - node.id.counter + 1) as usize; |
| 664 | queue.push(node); |
| 665 | continue; |
| 666 | } |
| 667 | |
| 668 | if node.len > 1 { |
| 669 | node.len = if other.lamport_last() >= node.lamport { |
| 670 | (other.lamport_last() - node.lamport + 1).min(node.len as u32 - 1) as usize |
| 671 | } else { |
| 672 | 1 |
| 673 | }; |
| 674 | queue.push(node); |
| 675 | continue; |
| 676 | } |
| 677 | } |
| 678 | |
| 679 | match deps_to_ord_id_spans(&node, get)? { |
| 680 | Some(deps) if !deps.is_empty() => { |
| 681 | for dep in deps { |
| 682 | queue.push(dep); |
| 683 | } |
| 684 | } |
| 685 | _ => return Ok(Default::default()), |
| 686 | } |
| 687 | } |
| 688 | |
| 689 | Ok(Default::default()) |
| 690 | } |
| 691 | |
| 692 | /// Finds the replay base and diff mode for the transition `left -> right`. |
| 693 | /// |
| 694 | /// Contract (see `docs/critical-version-spec.md` for definitions and proofs): |
| 695 | /// - S1: every id in the returned frontier is in the causal past of both sides; |
| 696 | /// - S2: the returned frontier is an antichain; |
| 697 | /// - S3: a non-`Checkout` mode additionally guarantees that the base equals |
| 698 | /// `left` and that EVERY newly imported event is causally after every head |
| 699 | /// of `left` (i.e. `left` is a critical version of the union graph in the |
| 700 | /// Eg-walker sense, arXiv:2409.14252 §3.5) — enforced for multi-head `left` |
| 701 | /// by `new_region_after_all_left_heads`; |
| 702 | /// - when a genuinely concurrent branch invalidates the candidate base, the |
| 703 | /// base retreats to the latest single-head critical version |
| 704 | /// (`latest_single_head_critical_version`), or to the empty version when no |
| 705 | /// such cut exists. |
| 706 | /// |
| 707 | /// Downstream consumers rely on these guarantees to skip CRDT adjudication |
| 708 | /// (tree/map fast paths) and to bound their replay windows (tree checkout); |
| 709 | /// see the comment in `diff_calc/tree.rs::checkout_diff`. |
| 710 | fn _find_meet_and_mode<'a, F, D>( |
| 711 | get: &'a F, |
| 712 | left: &Frontiers, |
| 713 | right: &Frontiers, |
| 714 | ) -> LoroResult<(MeetAsBase, DiffMode)> |
| 715 | where |
| 716 | D: DagNode + 'a, |
| 717 | F: Fn(ID) -> LoroResult<Option<D>>, |
| 718 | { |
| 719 | if right.is_empty() { |
| 720 | return Ok((MeetAsBase::Valid(Default::default()), DiffMode::Checkout)); |
| 721 | } |
| 722 | |
| 723 | if left.is_empty() { |
| 724 | if right.len() == 1 { |
| 725 | let mut node_id = right.as_single().unwrap(); |
| 726 | let mut node = get(node_id)?.unwrap(); |
| 727 | while node.deps().len() == 1 { |
| 728 | node_id = node.deps().as_single().unwrap(); |
| 729 | let Some(next) = get(node_id)? else { |
| 730 | return Ok(( |
| 731 | MeetAsBase::Valid(Default::default()), |
| 732 | DiffMode::ImportGreaterUpdates, |
| 733 | )); |
| 734 | }; |
| 735 | node = next; |
| 736 | } |
| 737 | |
| 738 | if node.deps().is_empty() { |
| 739 | return Ok((MeetAsBase::Valid(Default::default()), DiffMode::Linear)); |
| 740 | } |
| 741 | } |
| 742 | |
| 743 | return Ok(( |
| 744 | MeetAsBase::Valid(Default::default()), |
| 745 | DiffMode::ImportGreaterUpdates, |
| 746 | )); |
| 747 | } |
| 748 | |
| 749 | if left.len() == 1 && right.len() == 1 { |
| 750 | let left = left.as_single().unwrap(); |
| 751 | let right = right.as_single().unwrap(); |
| 752 | if left.peer == right.peer { |
| 753 | let left_span = get(left)?.unwrap(); |
| 754 | let right_span = get(right)?.unwrap(); |
| 755 | if left_span.id_start() == right_span.id_start() { |
| 756 | if left.counter < right.counter { |
| 757 | return Ok((MeetAsBase::Valid(left.into()), DiffMode::Linear)); |
| 758 | } else { |
| 759 | return Ok((MeetAsBase::Valid(right.into()), DiffMode::Checkout)); |
| 760 | } |
| 761 | } |
| 762 | |
| 763 | if left_span.deps().len() == 1 |
| 764 | && right_span.contains_id(left_span.deps().as_single().unwrap()) |
| 765 | { |
| 766 | return Ok((MeetAsBase::Valid(right.into()), DiffMode::Checkout)); |
| 767 | } |
| 768 | |
| 769 | if right_span.deps().len() == 1 |
| 770 | && left_span.contains_id(right_span.deps().as_single().unwrap()) |
| 771 | { |
| 772 | return Ok((MeetAsBase::Valid(left.into()), DiffMode::Linear)); |
| 773 | } |
| 774 | } |
| 775 | } |
| 776 | |
| 777 | let mut is_linear = left.len() <= 1 && right.len() == 1; |
| 778 | let mut is_right_greater = true; |
| 779 | let mut unmatched_branches = FxHashSet::default(); |
| 780 | let mut has_unresolved_unmatched_branch = false; |
| 781 | let mut ans: Frontiers = Default::default(); |
| 782 | |
| 783 | fn shrink_ancestor_frontiers<'a, D: DagNode + 'a, F: Fn(ID) -> LoroResult<Option<D>>>( |
| 784 | ids: &Frontiers, |
| 785 | get: &'a F, |
| 786 | ) -> LoroResult<Frontiers> { |
| 787 | if ids.len() <= 1 { |
| 788 | return Ok(ids.clone()); |
| 789 | } |
| 790 | |
| 791 | let mut ids = ids_to_ord_id_spans(ids, get)?.expect("meet candidates should be in dag"); |
| 792 | ids.sort_unstable(); |
| 793 | let mut frontiers = Vec::with_capacity(ids.len()); |
| 794 | for id in ids.iter().rev() { |
| 795 | let mut should_insert = true; |
| 796 | for frontier in frontiers.iter().rev() { |
| 797 | if contains_in_ancestors(get, *frontier, id)? { |
| 798 | should_insert = false; |
| 799 | break; |
| 800 | } |
| 801 | } |
| 802 | |
| 803 | if should_insert { |
| 804 | frontiers.push(id.id_last()); |
| 805 | } |
| 806 | } |
| 807 | |
| 808 | Ok(frontiers.into_iter().collect()) |
| 809 | } |
| 810 | |
| 811 | fn has_trimmed_history_deps<'a, D: DagNode + 'a, F: Fn(ID) -> LoroResult<Option<D>>>( |
| 812 | ids: &Frontiers, |
| 813 | get: &'a F, |
| 814 | ) -> LoroResult<bool> { |
| 815 | for id in ids.iter() { |
| 816 | let Some(node) = OrdIdSpan::from_dag_node(id, get)? else { |
| 817 | return Ok(true); |
| 818 | }; |
| 819 | if ids_to_ord_id_spans(node.deps.as_ref(), get)?.is_none() { |
| 820 | return Ok(true); |
| 821 | } |
| 822 | } |
| 823 | Ok(false) |
| 824 | } |
| 825 | |
| 826 | /// Whether every tip in `tips` is contained in the ancestors of `frontiers` |
| 827 | /// (the tip itself counts). One walk answers all tips: it starts from every |
| 828 | /// frontier with a shared visited set and prunes by the lowest lamport among |
| 829 | /// the still-unproven tips, so the ancestor region is traversed at most once |
| 830 | /// per call instead of once per (tip, frontier) pair. |
| 831 | fn all_tips_covered_by_ancestors<'a, D: DagNode + 'a, F: Fn(ID) -> LoroResult<Option<D>>>( |
| 832 | get: &'a F, |
| 833 | frontiers: &Frontiers, |
| 834 | tips: &FxHashSet<ID>, |
| 835 | ) -> LoroResult<bool> { |
| 836 | let mut remaining = Vec::with_capacity(tips.len()); |
| 837 | for id in tips.iter() { |
| 838 | let Some(span) = OrdIdSpan::from_dag_node(*id, get)? else { |
| 839 | return Ok(false); |
| 840 | }; |
| 841 | remaining.push(span); |
| 842 | } |
| 843 | |
| 844 | if remaining.is_empty() { |
| 845 | return Ok(true); |
| 846 | } |
| 847 | |
| 848 | let mut min_lamport = remaining |
| 849 | .iter() |
| 850 | .map(|tip| tip.lamport_last()) |
| 851 | .min() |
| 852 | .unwrap(); |
| 853 | let mut visited = FxHashSet::default(); |
| 854 | let mut pending = Vec::new(); |
| 855 | for frontier in frontiers.iter() { |
| 856 | if let Some(node) = OrdIdSpan::from_dag_node(frontier, get)? { |
| 857 | pending.push(node); |
| 858 | } |
| 859 | } |
| 860 | |
| 861 | while let Some(node) = pending.pop() { |
| 862 | let len_before = remaining.len(); |
| 863 | remaining.retain(|tip| !node.contains_id(tip.id_last())); |
| 864 | if remaining.is_empty() { |
| 865 | return Ok(true); |
| 866 | } |
| 867 | |
| 868 | if remaining.len() != len_before { |
| 869 | min_lamport = remaining |
| 870 | .iter() |
| 871 | .map(|tip| tip.lamport_last()) |
| 872 | .min() |
| 873 | .unwrap(); |
| 874 | } |
| 875 | |
| 876 | // Ancestors of `node` all have lamport strictly below the node's |
| 877 | // start, so nothing below `min_lamport` can contain a remaining tip. |
| 878 | if node.lamport_last() < min_lamport { |
| 879 | continue; |
| 880 | } |
| 881 | |
| 882 | if !visited.insert(node.id_start()) { |
| 883 | continue; |
| 884 | } |
| 885 | |
| 886 | if let Some(deps) = deps_to_ord_id_spans(&node, get)? { |
| 887 | for dep in deps { |
| 888 | pending.push(dep); |
| 889 | } |
| 890 | } |
| 891 | } |
| 892 | |
| 893 | Ok(false) |
| 894 | } |
| 895 | |
| 896 | /// Verifies the `ImportGreaterUpdates` contract for a multi-head `left`: |
| 897 | /// every event in `Events(right) − Events(left)` must be causally after |
| 898 | /// every member of `left` (i.e. `left` must be a critical version of the |
| 899 | /// union graph). The main walk only proves version inclusion, which is |
| 900 | /// weaker: a new branch can enter old history through one left head while |
| 901 | /// staying concurrent with another, and the tree calculator's fast path |
| 902 | /// applies such updates without adjudication (see |
| 903 | /// `docs/critical-version-spec.md` §4.1). |
| 904 | /// |
| 905 | /// Method: descend from `right` over new changes only. A change whose |
| 906 | /// causal parents (explicit deps plus the implicit same-peer predecessor) |
| 907 | /// are all old is an entry point of the new region; its parents must |
| 908 | /// causally cover every left head. Non-entry changes inherit coverage |
| 909 | /// through their new parents. The common healthy shape — a change whose |
| 910 | /// deps equal the left frontier — passes with a set comparison and no |
| 911 | /// graph walk. Trimmed history fails conservatively. |
| 912 | fn new_region_after_all_left_heads<'a, D: DagNode + 'a, F: Fn(ID) -> LoroResult<Option<D>>>( |
| 913 | get: &'a F, |
| 914 | left: &Frontiers, |
| 915 | right: &Frontiers, |
| 916 | ) -> LoroResult<bool> { |
| 917 | let left_ids: FxHashSet<ID> = left.iter().collect(); |
| 918 | let is_old = |id: ID| -> LoroResult<bool> { |
| 919 | if left_ids.contains(&id) { |
| 920 | return Ok(true); |
| 921 | } |
| 922 | let mut single = FxHashSet::default(); |
| 923 | single.insert(id); |
| 924 | all_tips_covered_by_ancestors(get, left, &single) |
| 925 | }; |
| 926 | |
| 927 | let mut visited: FxHashSet<ID> = FxHashSet::default(); |
| 928 | let mut stack: Vec<OrdIdSpan> = Vec::new(); |
| 929 | for id in right.iter() { |
| 930 | if is_old(id)? { |
| 931 | continue; |
| 932 | } |
| 933 | let Some(span) = OrdIdSpan::from_dag_node(id, get)? else { |
| 934 | return Ok(false); |
| 935 | }; |
| 936 | stack.push(span); |
| 937 | } |
| 938 | |
| 939 | while let Some(span) = stack.pop() { |
| 940 | if !visited.insert(span.id_start()) { |
| 941 | continue; |
| 942 | } |
| 943 | |
| 944 | let Some(parents) = deps_to_ord_id_spans(&span, get)? else { |
| 945 | return Ok(false); |
| 946 | }; |
| 947 | let mut entry_point = true; |
| 948 | let mut old_parents = Frontiers::default(); |
| 949 | for parent in parents { |
| 950 | let pid = parent.id_last(); |
| 951 | if is_old(pid)? { |
| 952 | old_parents.push(pid); |
| 953 | } else { |
| 954 | entry_point = false; |
| 955 | stack.push(parent); |
| 956 | } |
| 957 | } |
| 958 | |
| 959 | if entry_point { |
| 960 | if &old_parents == left { |
| 961 | continue; |
| 962 | } |
| 963 | |
| 964 | if !all_tips_covered_by_ancestors(get, &old_parents, &left_ids)? { |
| 965 | return Ok(false); |
| 966 | } |
| 967 | } |
| 968 | } |
| 969 | |
| 970 | Ok(true) |
| 971 | } |
| 972 | |
| 973 | fn contains_in_ancestors<'a, D: DagNode + 'a, F: Fn(ID) -> LoroResult<Option<D>>>( |
| 974 | get: &'a F, |
| 975 | frontier: ID, |
| 976 | target: &OrdIdSpan<'_>, |
| 977 | ) -> LoroResult<bool> { |
| 978 | let mut visited = FxHashSet::default(); |
| 979 | let mut pending = Vec::new(); |
| 980 | let Some(node) = OrdIdSpan::from_dag_node(frontier, get)? else { |
| 981 | return Ok(false); |
| 982 | }; |
| 983 | pending.push(node); |
| 984 | while let Some(node) = pending.pop() { |
| 985 | if node.contains_id(target.id_last()) { |
| 986 | return Ok(true); |
| 987 | } |
| 988 | |
| 989 | if node.lamport_last() < target.lamport_last() { |
| 990 | continue; |
| 991 | } |
| 992 | |
| 993 | if !visited.insert(node.id_start()) { |
| 994 | continue; |
| 995 | } |
| 996 | |
| 997 | if let Some(deps) = deps_to_ord_id_spans(&node, get)? { |
| 998 | for dep in deps { |
| 999 | pending.push(dep); |
| 1000 | } |
| 1001 | } |
| 1002 | } |
| 1003 | |
| 1004 | Ok(false) |
| 1005 | } |
| 1006 | |
| 1007 | // The third tuple item carries the dependency tips at which this path first |
| 1008 | // split from its sibling paths. If the path dies without meeting the other |
| 1009 | // side, those tips tell us whether it was a real concurrent branch or merely |
| 1010 | // a redundant route into an ancestor we already found. |
| 1011 | let mut queue: BinaryHeap<(OrdIdSpan, NodeType, Vec<ID>)> = BinaryHeap::new(); |
| 1012 | for span in ids_to_ord_id_spans(left, get)?.unwrap() { |
| 1013 | let branch_tips = if left.len() > 1 { |
| 1014 | vec![span.id_last()] |
| 1015 | } else { |
| 1016 | Vec::new() |
| 1017 | }; |
| 1018 | queue.push((span, NodeType::A, branch_tips)); |
| 1019 | } |
| 1020 | |
| 1021 | for span in ids_to_ord_id_spans(right, get)?.unwrap() { |
| 1022 | let branch_tips = if right.len() > 1 { |
| 1023 | vec![span.id_last()] |
| 1024 | } else { |
| 1025 | Vec::new() |
| 1026 | }; |
| 1027 | queue.push((span, NodeType::B, branch_tips)); |
| 1028 | } |
| 1029 | |
| 1030 | while let Some((mut node, mut node_type, mut branch_tips)) = queue.pop() { |
| 1031 | while let Some((other_node, other_type, _)) = queue.peek() { |
| 1032 | if node == *other_node || node.id_last() == other_node.id_last() { |
| 1033 | if node_type != *other_type { |
| 1034 | node_type = NodeType::Shared; |
| 1035 | } |
| 1036 | |
| 1037 | let (_, _, other_branch_tips) = queue.pop().unwrap(); |
| 1038 | // Union, not concatenation. On criss-cross histories the same |
| 1039 | // tips arrive from both parents at every re-merge; concatenating |
| 1040 | // doubles the vec per sync round, and the per-dep clone below |
| 1041 | // then makes the walk O(2^rounds). Distinct tips stay few: they |
| 1042 | // are only minted for multi-head initial frontiers and at each |
| 1043 | // side's first split. |
| 1044 | for tip in other_branch_tips { |
| 1045 | if !branch_tips.contains(&tip) { |
| 1046 | branch_tips.push(tip); |
| 1047 | } |
| 1048 | } |
| 1049 | } else { |
| 1050 | break; |
| 1051 | } |
| 1052 | } |
| 1053 | |
| 1054 | if node_type == NodeType::Shared { |
| 1055 | ans.push(node.id_last()); |
| 1056 | continue; |
| 1057 | } |
| 1058 | |
| 1059 | if queue.is_empty() { |
| 1060 | if branch_tips.is_empty() { |
| 1061 | unmatched_branches.insert(node.id_last()); |
| 1062 | } else { |
| 1063 | unmatched_branches.extend(branch_tips); |
| 1064 | } |
| 1065 | break; |
| 1066 | } |
| 1067 | |
| 1068 | // if node_type is A, then the left side is greater or parallel to the right side |
| 1069 | if node_type == NodeType::A { |
| 1070 | is_right_greater = false; |
| 1071 | } |
| 1072 | |
| 1073 | if let Some(other) = queue.peek() { |
| 1074 | if node.contains_id(other.0.id_last()) && node_type != other.1 { |
| 1075 | node.len = (other.0.id_last().counter - node.id.counter + 1) as usize; |
| 1076 | queue.push((node, node_type, branch_tips)); |
| 1077 | continue; |
| 1078 | } |
| 1079 | |
| 1080 | if node.len > 1 { |
| 1081 | // The `min(..., len - 1)` cap guarantees strict progress when |
| 1082 | // lamports tie: aligning to the other's lamport alone would |
| 1083 | // re-push the span unchanged and loop forever. It is also what |
| 1084 | // makes the termination measure decrease on this branch. |
| 1085 | node.len = if other.0.lamport_last() >= node.lamport { |
| 1086 | (other.0.lamport_last() - node.lamport + 1).min(node.len as u32 - 1) as usize |
| 1087 | } else { |
| 1088 | 1 |
| 1089 | }; |
| 1090 | queue.push((node, node_type, branch_tips)); |
| 1091 | continue; |
| 1092 | } |
| 1093 | } |
| 1094 | |
| 1095 | if let Some(deps) = deps_to_ord_id_spans(&node, get)? { |
| 1096 | if !deps.is_empty() { |
| 1097 | let starts_new_branches = branch_tips.is_empty() && deps.len() > 1; |
| 1098 | for dep in deps { |
| 1099 | let child_branch_tips = if starts_new_branches { |
| 1100 | vec![dep.id_last()] |
| 1101 | } else { |
| 1102 | branch_tips.clone() |
| 1103 | }; |
| 1104 | queue.push((dep, node_type, child_branch_tips)); |
| 1105 | } |
| 1106 | is_linear = false; |
| 1107 | continue; |
| 1108 | } |
| 1109 | } else { |
| 1110 | // The dependency is on trimmed shallow history. The exact ancestor is |
| 1111 | // not representable in the current DAG, so fall back to a conservative |
| 1112 | // checkout base. No tip needs recording: this flag short-circuits the |
| 1113 | // coverage check entirely. |
| 1114 | has_unresolved_unmatched_branch = true; |
| 1115 | continue; |
| 1116 | } |
| 1117 | |
| 1118 | { |
| 1119 | // Some checkout calculators still require replaying from a base that |
| 1120 | // includes every branch whose operation positions may affect the diff. |
| 1121 | // In non-linear checkout mode, an earlier version in the causal past of |
| 1122 | // both sides is a valid conservative base even when it is not the meet. |
| 1123 | if branch_tips.is_empty() { |
| 1124 | unmatched_branches.insert(node.id_last()); |
| 1125 | } else { |
| 1126 | unmatched_branches.extend(branch_tips); |
| 1127 | } |
| 1128 | continue; |
| 1129 | } |
| 1130 | } |
| 1131 | |
| 1132 | ans = shrink_ancestor_frontiers(&ans, get)?; |
| 1133 | // A branch can look unmatched merely because a shared node was found first |
| 1134 | // and was therefore not expanded. In that case another queued path may still |
| 1135 | // walk into one of the shared node's ancestors. That path is redundant, not a |
| 1136 | // concurrent branch. Only fall back when an unmatched tip is not causally |
| 1137 | // covered by the meet candidates we found. |
| 1138 | let has_uncovered_unmatched_branch = has_unresolved_unmatched_branch |
| 1139 | || !all_tips_covered_by_ancestors(get, &ans, &unmatched_branches)?; |
| 1140 | // A genuine concurrent branch invalidates the meet as a replay base. The |
| 1141 | // caller has to retreat to a critical version; which one is its choice, so |
| 1142 | // it can try a cheap multi-head cut before paying for the full-DAG |
| 1143 | // single-head descent. |
| 1144 | let mut needs_critical_retreat = |
| 1145 | has_uncovered_unmatched_branch && !has_trimmed_history_deps(&ans, get)?; |
| 1146 | |
| 1147 | if has_uncovered_unmatched_branch { |
| 1148 | is_right_greater = false; |
| 1149 | } else if &ans == left { |
| 1150 | // An A-only path may also have been a redundant path into `ans`. Once all |
| 1151 | // such paths are proved covered, equality with `left` is the exact proof |
| 1152 | // that `right` causally includes `left`. |
| 1153 | is_right_greater = true; |
| 1154 | } |
| 1155 | |
| 1156 | if is_right_greater && left.len() > 1 && !new_region_after_all_left_heads(get, left, right)? { |
| 1157 | // Version inclusion holds, but part of the new region entered old |
| 1158 | // history through a strict subset of the left heads and is therefore |
| 1159 | // concurrent with the others. `ImportGreaterUpdates` promises "no |
| 1160 | // update is concurrent to the current version", so claiming it here |
| 1161 | // lets fast paths (notably the tree calculator's) apply the new ops |
| 1162 | // without adjudicating against the concurrent existing branch, and the |
| 1163 | // materialized state diverges from a full replay. Demote to the |
| 1164 | // conservative mode and retreat the base to a safe cut so the |
| 1165 | // competing branches are replayed together. |
| 1166 | is_right_greater = false; |
| 1167 | needs_critical_retreat = true; |
| 1168 | } |
| 1169 | |
| 1170 | let mode = if is_right_greater { |
| 1171 | if ans.len() <= 1 { |
| 1172 | debug_assert_eq!(&ans, left); |
| 1173 | } |
| 1174 | |
| 1175 | if is_linear { |
| 1176 | debug_assert!(ans.len() <= 1); |
| 1177 | DiffMode::Linear |
| 1178 | } else { |
| 1179 | DiffMode::ImportGreaterUpdates |
| 1180 | } |
| 1181 | } else { |
| 1182 | DiffMode::Checkout |
| 1183 | }; |
| 1184 | |
| 1185 | let meet = if needs_critical_retreat { |
| 1186 | MeetAsBase::NeedsCriticalRetreat |
| 1187 | } else { |
| 1188 | MeetAsBase::Valid(ans) |
| 1189 | }; |
| 1190 | Ok((meet, mode)) |
| 1191 | } |
| 1192 | |
| 1193 | pub fn remove_included_frontiers(frontiers: &mut VersionVector, new_change_deps: &[ID]) { |
| 1194 | for dep in new_change_deps.iter() { |
| 1195 | if let Some(last) = frontiers.get_last(dep.peer) { |
| 1196 | if last <= dep.counter { |
| 1197 | frontiers.remove(&dep.peer); |
| 1198 | } |
| 1199 | } |
| 1200 | } |
| 1201 | } |
| 1202 | |
| 1203 | #[cfg(test)] |
| 1204 | mod tests { |
| 1205 | use std::collections::BTreeMap; |
| 1206 | |
| 1207 | use loro_common::{HasId, HasIdSpan}; |
| 1208 | use rand::{rngs::StdRng, Rng, SeedableRng}; |
| 1209 | |
| 1210 | use super::*; |
| 1211 | |
| 1212 | #[derive(Clone, Debug)] |
| 1213 | struct TestNode { |
| 1214 | id: ID, |
| 1215 | len: usize, |
| 1216 | lamport: Lamport, |
| 1217 | deps: Frontiers, |
| 1218 | } |
| 1219 | |
| 1220 | impl DagNode for TestNode { |
| 1221 | fn deps(&self) -> &Frontiers { |
| 1222 | &self.deps |
| 1223 | } |
| 1224 | } |
| 1225 | |
| 1226 | impl HasId for TestNode { |
| 1227 | fn id_start(&self) -> ID { |
| 1228 | self.id |
| 1229 | } |
| 1230 | } |
| 1231 | |
| 1232 | impl HasLamport for TestNode { |
| 1233 | fn lamport(&self) -> Lamport { |
| 1234 | self.lamport |
| 1235 | } |
| 1236 | } |
| 1237 | |
| 1238 | impl HasLength for TestNode { |
| 1239 | fn content_len(&self) -> usize { |
| 1240 | self.len |
| 1241 | } |
| 1242 | } |
| 1243 | |
| 1244 | impl Sliceable for TestNode { |
| 1245 | fn slice(&self, from: usize, to: usize) -> Self { |
| 1246 | Self { |
| 1247 | id: self.id.inc(from as i32), |
| 1248 | len: to - from, |
| 1249 | lamport: self.lamport + from as Lamport, |
| 1250 | deps: if from == 0 { |
| 1251 | self.deps.clone() |
| 1252 | } else { |
| 1253 | self.id.inc(from as i32 - 1).into() |
| 1254 | }, |
| 1255 | } |
| 1256 | } |
| 1257 | } |
| 1258 | |
| 1259 | #[derive(Debug)] |
| 1260 | struct TestDag { |
| 1261 | nodes: BTreeMap<ID, TestNode>, |
| 1262 | vv: VersionVector, |
| 1263 | frontier: Frontiers, |
| 1264 | } |
| 1265 | |
| 1266 | impl TestDag { |
| 1267 | fn new(nodes: impl IntoIterator<Item = TestNode>, frontier: Frontiers) -> Self { |
| 1268 | let mut vv = VersionVector::default(); |
| 1269 | let nodes = nodes |
| 1270 | .into_iter() |
| 1271 | .map(|node| { |
| 1272 | vv.set_end(node.id_end()); |
| 1273 | (node.id_start(), node) |
| 1274 | }) |
| 1275 | .collect(); |
| 1276 | Self { |
| 1277 | nodes, |
| 1278 | vv, |
| 1279 | frontier, |
| 1280 | } |
| 1281 | } |
| 1282 | } |
| 1283 | |
| 1284 | impl Dag for TestDag { |
| 1285 | type Node = TestNode; |
| 1286 | |
| 1287 | fn get(&self, id: ID) -> Option<Self::Node> { |
| 1288 | self.nodes |
| 1289 | .range(..=id) |
| 1290 | .rev() |
| 1291 | .find(|(_, node)| node.contains_id(id)) |
| 1292 | .map(|(_, node)| node.clone()) |
| 1293 | } |
| 1294 | |
| 1295 | fn frontier(&self) -> &Frontiers { |
| 1296 | &self.frontier |
| 1297 | } |
| 1298 | |
| 1299 | fn vv(&self) -> &VersionVector { |
| 1300 | &self.vv |
| 1301 | } |
| 1302 | |
| 1303 | fn contains(&self, id: ID) -> bool { |
| 1304 | self.get(id).is_some() |
| 1305 | } |
| 1306 | } |
| 1307 | |
| 1308 | fn node( |
| 1309 | peer: PeerID, |
| 1310 | counter: Counter, |
| 1311 | len: usize, |
| 1312 | lamport: Lamport, |
| 1313 | deps: Frontiers, |
| 1314 | ) -> TestNode { |
| 1315 | TestNode { |
| 1316 | id: ID::new(peer, counter), |
| 1317 | len, |
| 1318 | lamport, |
| 1319 | deps, |
| 1320 | } |
| 1321 | } |
| 1322 | |
| 1323 | fn ancestors_of_frontiers(dag: &TestDag, frontiers: &Frontiers) -> FxHashSet<ID> { |
| 1324 | let mut ans = FxHashSet::default(); |
| 1325 | for id in frontiers.iter() { |
| 1326 | collect_ancestors(dag, id, &mut ans); |
| 1327 | } |
| 1328 | ans |
| 1329 | } |
| 1330 | |
| 1331 | fn collect_ancestors(dag: &TestDag, id: ID, ans: &mut FxHashSet<ID>) { |
| 1332 | let mut stack = vec![id]; |
| 1333 | let mut visited_targets = FxHashSet::default(); |
| 1334 | while let Some(id) = stack.pop() { |
| 1335 | if !visited_targets.insert(id) { |
| 1336 | continue; |
| 1337 | } |
| 1338 | |
| 1339 | for node in dag.nodes.values() { |
| 1340 | if node.id_start().peer != id.peer || node.id_start().counter > id.counter { |
| 1341 | continue; |
| 1342 | } |
| 1343 | |
| 1344 | let end = node.id_last().counter.min(id.counter); |
| 1345 | for counter in node.id_start().counter..=end { |
| 1346 | ans.insert(ID::new(node.id_start().peer, counter)); |
| 1347 | } |
| 1348 | |
| 1349 | for dep in node.deps().iter() { |
| 1350 | stack.push(dep); |
| 1351 | } |
| 1352 | } |
| 1353 | } |
| 1354 | } |
| 1355 | |
| 1356 | fn is_ancestor(dag: &TestDag, ancestor: ID, descendant: ID) -> bool { |
| 1357 | let mut ancestors = FxHashSet::default(); |
| 1358 | collect_ancestors(dag, descendant, &mut ancestors); |
| 1359 | ancestors.contains(&ancestor) |
| 1360 | } |
| 1361 | |
| 1362 | fn maximal_frontiers(dag: &TestDag, ids: impl IntoIterator<Item = ID>) -> Frontiers { |
| 1363 | let mut ids = Vec::<ID>::from_iter(ids); |
| 1364 | ids.sort_by_key(|id| dag.get(*id).unwrap().get_lamport_from_counter(id.counter)); |
| 1365 | let mut frontiers = Vec::new(); |
| 1366 | for id in ids.into_iter().rev() { |
| 1367 | if frontiers |
| 1368 | .iter() |
| 1369 | .any(|frontier| is_ancestor(dag, id, *frontier)) |
| 1370 | { |
| 1371 | continue; |
| 1372 | } |
| 1373 | |
| 1374 | frontiers.retain(|frontier| !is_ancestor(dag, *frontier, id)); |
| 1375 | frontiers.push(id); |
| 1376 | } |
| 1377 | |
| 1378 | frontiers.into_iter().collect() |
| 1379 | } |
| 1380 | |
| 1381 | fn oracle_meet(dag: &TestDag, left: &Frontiers, right: &Frontiers) -> Frontiers { |
| 1382 | let left_ancestors = ancestors_of_frontiers(dag, left); |
| 1383 | let right_ancestors = ancestors_of_frontiers(dag, right); |
| 1384 | maximal_frontiers( |
| 1385 | dag, |
| 1386 | left_ancestors |
| 1387 | .into_iter() |
| 1388 | .filter(|id| right_ancestors.contains(id)), |
| 1389 | ) |
| 1390 | } |
| 1391 | |
| 1392 | fn assert_replay_base_valid_against_oracle(dag: &TestDag, left: &Frontiers, right: &Frontiers) { |
| 1393 | let (actual, mode) = dag.find_replay_base(left, right); |
| 1394 | let expected = oracle_meet(dag, left, right); |
| 1395 | let left_ancestors = ancestors_of_frontiers(dag, left); |
| 1396 | let right_ancestors = ancestors_of_frontiers(dag, right); |
| 1397 | for id in actual.iter() { |
| 1398 | assert!( |
| 1399 | left_ancestors.contains(&id) && right_ancestors.contains(&id), |
| 1400 | "every replay-base id {id} must be common: left={left:?} right={right:?} actual={actual:?} expected={expected:?} mode={mode:?}\ndag={dag:?}", |
| 1401 | ); |
| 1402 | } |
| 1403 | |
| 1404 | for a in actual.iter() { |
| 1405 | for b in actual.iter() { |
| 1406 | if a != b { |
| 1407 | assert!( |
| 1408 | !is_ancestor(dag, a, b), |
| 1409 | "the replay base must be a minimal frontier set: left={left:?} right={right:?} actual={actual:?} expected={expected:?} mode={mode:?}\ndag={dag:?}", |
| 1410 | ); |
| 1411 | } |
| 1412 | } |
| 1413 | } |
| 1414 | |
| 1415 | if !matches!(mode, DiffMode::Checkout) { |
| 1416 | assert_eq!( |
| 1417 | actual, expected, |
| 1418 | "non-checkout mode should use the meet: left={left:?} right={right:?} mode={mode:?}\ndag={dag:?}", |
| 1419 | ); |
| 1420 | assert_eq!( |
| 1421 | &actual, left, |
| 1422 | "non-checkout mode must use left as the replay base: left={left:?} right={right:?} mode={mode:?}" |
| 1423 | ); |
| 1424 | for id in left.iter() { |
| 1425 | assert!( |
| 1426 | right_ancestors.contains(&id), |
| 1427 | "non-checkout mode requires right to include left id {id}; left={left:?} right={right:?} mode={mode:?}", |
| 1428 | ); |
| 1429 | } |
| 1430 | } |
| 1431 | } |
| 1432 | |
| 1433 | fn all_ids(dag: &TestDag) -> Vec<ID> { |
| 1434 | dag.nodes |
| 1435 | .values() |
| 1436 | .flat_map(|node| { |
| 1437 | (0..node.content_len()).map(|offset| node.id_start().inc(offset as Counter)) |
| 1438 | }) |
| 1439 | .collect() |
| 1440 | } |
| 1441 | |
| 1442 | fn random_frontiers(dag: &TestDag, ids: &[ID], rng: &mut impl Rng) -> Frontiers { |
| 1443 | if ids.is_empty() || rng.gen_bool(0.1) { |
| 1444 | return Frontiers::default(); |
| 1445 | } |
| 1446 | |
| 1447 | let len = rng.gen_range(1..=ids.len().min(4)); |
| 1448 | maximal_frontiers(dag, (0..len).map(|_| ids[rng.gen_range(0..ids.len())])) |
| 1449 | } |
| 1450 | |
| 1451 | fn random_dag(seed: u64, node_count: usize) -> TestDag { |
| 1452 | let mut rng = StdRng::seed_from_u64(seed); |
| 1453 | let mut next_counter = [0 as Counter; 8]; |
| 1454 | let mut nodes = Vec::new(); |
| 1455 | let mut existing_ids = Vec::new(); |
| 1456 | for i in 0..node_count { |
| 1457 | let peer = rng.gen_range(1..next_counter.len() as PeerID); |
| 1458 | let counter = next_counter[peer as usize]; |
| 1459 | let len = rng.gen_range(1..=3); |
| 1460 | next_counter[peer as usize] += len as Counter; |
| 1461 | let dep_count = if existing_ids.is_empty() { |
| 1462 | 0 |
| 1463 | } else { |
| 1464 | rng.gen_range(0..=existing_ids.len().min(3)) |
| 1465 | }; |
| 1466 | let deps = maximal_frontiers( |
| 1467 | &TestDag::new(nodes.clone(), Frontiers::default()), |
| 1468 | (0..dep_count).map(|_| existing_ids[rng.gen_range(0..existing_ids.len())]), |
| 1469 | ); |
| 1470 | let node = node(peer, counter, len, i as Lamport * 4, deps); |
| 1471 | existing_ids.extend((0..len).map(|offset| node.id_start().inc(offset as Counter))); |
| 1472 | nodes.push(node); |
| 1473 | } |
| 1474 | |
| 1475 | let dag = TestDag::new(nodes, Frontiers::default()); |
| 1476 | let frontier = maximal_frontiers(&dag, existing_ids); |
| 1477 | TestDag::new(dag.nodes.into_values(), frontier) |
| 1478 | } |
| 1479 | |
| 1480 | fn layered_merge_dag() -> TestDag { |
| 1481 | let root = node(1, 0, 3, 0, Frontiers::default()); |
| 1482 | let left = node(1, 3, 2, 4, ID::new(1, 2).into()); |
| 1483 | let right = node(2, 0, 3, 5, ID::new(1, 1).into()); |
| 1484 | let late_right = node(2, 3, 2, 9, ID::new(2, 2).into()); |
| 1485 | let third = node(3, 0, 2, 6, ID::new(1, 2).into()); |
| 1486 | let merge_left_right = node( |
| 1487 | 4, |
| 1488 | 0, |
| 1489 | 1, |
| 1490 | 12, |
| 1491 | Frontiers::from([left.id_last(), right.id_last()]), |
| 1492 | ); |
| 1493 | let merge_all = node( |
| 1494 | 5, |
| 1495 | 0, |
| 1496 | 2, |
| 1497 | 16, |
| 1498 | Frontiers::from([ |
| 1499 | merge_left_right.id_last(), |
| 1500 | late_right.id_last(), |
| 1501 | third.id_last(), |
| 1502 | ]), |
| 1503 | ); |
| 1504 | let independent = node(6, 0, 2, 20, Frontiers::default()); |
| 1505 | let final_merge = node( |
| 1506 | 7, |
| 1507 | 0, |
| 1508 | 1, |
| 1509 | 25, |
| 1510 | Frontiers::from([merge_all.id_last(), independent.id_last()]), |
| 1511 | ); |
| 1512 | |
| 1513 | TestDag::new( |
| 1514 | vec![ |
| 1515 | root, |
| 1516 | left, |
| 1517 | right, |
| 1518 | late_right, |
| 1519 | third, |
| 1520 | merge_left_right, |
| 1521 | merge_all, |
| 1522 | independent, |
| 1523 | final_merge.clone(), |
| 1524 | ], |
| 1525 | final_merge.id_last().into(), |
| 1526 | ) |
| 1527 | } |
| 1528 | |
| 1529 | #[test] |
| 1530 | fn replay_base_handles_empty_linear_same_span_and_parent_child_cases() { |
| 1531 | let first = node(1, 0, 2, 0, Frontiers::default()); |
| 1532 | let second = node(1, 2, 2, 2, ID::new(1, 1).into()); |
| 1533 | let dag = TestDag::new(vec![first, second], ID::new(1, 3).into()); |
| 1534 | |
| 1535 | assert_eq!( |
| 1536 | dag.find_replay_base(&Frontiers::default(), &ID::new(1, 3).into()), |
| 1537 | (Frontiers::default(), DiffMode::Linear) |
| 1538 | ); |
| 1539 | assert_eq!( |
| 1540 | dag.find_replay_base(&ID::new(1, 3).into(), &Frontiers::default()), |
| 1541 | (Frontiers::default(), DiffMode::Checkout) |
| 1542 | ); |
| 1543 | assert_eq!( |
| 1544 | dag.find_replay_base(&ID::new(1, 0).into(), &ID::new(1, 1).into()), |
| 1545 | (ID::new(1, 0).into(), DiffMode::Linear) |
| 1546 | ); |
| 1547 | assert_eq!( |
| 1548 | dag.find_replay_base(&ID::new(1, 1).into(), &ID::new(1, 0).into()), |
| 1549 | (ID::new(1, 0).into(), DiffMode::Checkout) |
| 1550 | ); |
| 1551 | assert_eq!( |
| 1552 | dag.find_replay_base(&ID::new(1, 1).into(), &ID::new(1, 3).into()), |
| 1553 | (ID::new(1, 1).into(), DiffMode::Linear) |
| 1554 | ); |
| 1555 | } |
| 1556 | |
| 1557 | #[test] |
| 1558 | fn replay_base_left_empty_stops_linear_scan_at_missing_shallow_dependency() { |
| 1559 | let visible = node(1, 1, 1, 1, ID::new(1, 0).into()); |
| 1560 | let dag = TestDag::new(vec![visible], ID::new(1, 1).into()); |
| 1561 | |
| 1562 | assert_eq!( |
| 1563 | dag.find_replay_base(&Frontiers::default(), &ID::new(1, 1).into()), |
| 1564 | (Frontiers::default(), DiffMode::ImportGreaterUpdates) |
| 1565 | ); |
| 1566 | } |
| 1567 | |
| 1568 | #[test] |
| 1569 | fn replay_base_of_parallel_branches_is_shared_dependency() { |
| 1570 | let root = node(1, 0, 1, 0, Frontiers::default()); |
| 1571 | let left = node(2, 0, 1, 1, root.id.into()); |
| 1572 | let right = node(3, 0, 1, 2, root.id.into()); |
| 1573 | let merge = node(4, 0, 1, 3, Frontiers::from([left.id, right.id])); |
| 1574 | let dag = TestDag::new( |
| 1575 | vec![root.clone(), left.clone(), right.clone(), merge.clone()], |
| 1576 | merge.id.into(), |
| 1577 | ); |
| 1578 | |
| 1579 | let (ancestor, mode) = dag.find_replay_base(&left.id.into(), &right.id.into()); |
| 1580 | assert_eq!(ancestor, root.id.into()); |
| 1581 | assert_eq!(mode, DiffMode::Checkout); |
| 1582 | |
| 1583 | let (ancestor, _) = dag.find_replay_base(&root.id.into(), &merge.id.into()); |
| 1584 | assert_eq!(ancestor, root.id.into()); |
| 1585 | } |
| 1586 | |
| 1587 | #[test] |
| 1588 | fn replay_base_falls_back_before_independent_branch() { |
| 1589 | let left = node(1, 0, 1, 0, Frontiers::default()); |
| 1590 | let independent = node(2, 0, 1, 1, Frontiers::default()); |
| 1591 | let merge = node(3, 0, 1, 2, Frontiers::from([left.id, independent.id])); |
| 1592 | let dag = TestDag::new( |
| 1593 | vec![left.clone(), independent, merge.clone()], |
| 1594 | merge.id.into(), |
| 1595 | ); |
| 1596 | |
| 1597 | let (ancestor, mode) = dag.find_replay_base(&left.id.into(), &merge.id.into()); |
| 1598 | assert_eq!(ancestor, Frontiers::default()); |
| 1599 | assert_eq!(mode, DiffMode::Checkout); |
| 1600 | } |
| 1601 | |
| 1602 | #[test] |
| 1603 | fn replay_base_falls_back_before_unmatched_branch_with_multiple_left_frontiers() { |
| 1604 | let left_a = node(1, 0, 1, 0, Frontiers::default()); |
| 1605 | let left_b = node(2, 0, 1, 1, Frontiers::default()); |
| 1606 | let independent = node(3, 0, 1, 2, Frontiers::default()); |
| 1607 | let left_frontiers = Frontiers::from([left_a.id, left_b.id]); |
| 1608 | let merge = node( |
| 1609 | 4, |
| 1610 | 0, |
| 1611 | 1, |
| 1612 | 3, |
| 1613 | Frontiers::from([left_a.id, left_b.id, independent.id]), |
| 1614 | ); |
| 1615 | let dag = TestDag::new( |
| 1616 | vec![left_a.clone(), left_b.clone(), independent, merge.clone()], |
| 1617 | merge.id.into(), |
| 1618 | ); |
| 1619 | |
| 1620 | let (ancestor, mode) = dag.find_replay_base(&left_frontiers, &merge.id.into()); |
| 1621 | assert_eq!(ancestor, Frontiers::default()); |
| 1622 | assert_eq!(mode, DiffMode::Checkout); |
| 1623 | } |
| 1624 | |
| 1625 | #[test] |
| 1626 | fn replay_base_marks_cross_peer_direct_dependency_as_greater_update() { |
| 1627 | let left = node(1, 0, 1, 0, Frontiers::default()); |
| 1628 | let right = node(2, 0, 1, 1, left.id.into()); |
| 1629 | let dag = TestDag::new(vec![left.clone(), right.clone()], right.id.into()); |
| 1630 | |
| 1631 | let (ancestor, mode) = dag.find_replay_base(&left.id.into(), &right.id.into()); |
| 1632 | assert_eq!(ancestor, left.id.into()); |
| 1633 | assert_eq!(mode, DiffMode::ImportGreaterUpdates); |
| 1634 | } |
| 1635 | |
| 1636 | #[test] |
| 1637 | fn replay_base_ignores_implicit_predecessor_covered_by_explicit_dependency() { |
| 1638 | let peer_one_previous = node(1, 0, 1, 0, Frontiers::default()); |
| 1639 | let relay = node(2, 0, 1, 1, peer_one_previous.id.into()); |
| 1640 | // This is peer 1's next change, so it implicitly depends on |
| 1641 | // `peer_one_previous`. Its explicit dependency on `relay` already covers |
| 1642 | // that predecessor, though, so the two paths are not concurrent. |
| 1643 | let peer_one_next = node(1, 1, 1, 2, relay.id.into()); |
| 1644 | let dag = TestDag::new( |
| 1645 | vec![peer_one_previous, relay.clone(), peer_one_next.clone()], |
| 1646 | peer_one_next.id.into(), |
| 1647 | ); |
| 1648 | |
| 1649 | let (ancestor, mode) = dag.find_replay_base(&relay.id.into(), &peer_one_next.id.into()); |
| 1650 | assert_eq!(ancestor, relay.id.into()); |
| 1651 | assert_eq!(mode, DiffMode::ImportGreaterUpdates); |
| 1652 | } |
| 1653 | |
| 1654 | #[test] |
| 1655 | fn replay_base_ignores_implicit_predecessor_covered_transitively() { |
| 1656 | let peer_one_previous = node(1, 0, 1, 0, Frontiers::default()); |
| 1657 | let first_relay = node(2, 0, 1, 1, peer_one_previous.id.into()); |
| 1658 | let current_frontier = node(3, 0, 1, 2, first_relay.id.into()); |
| 1659 | let peer_one_next = node(1, 1, 1, 3, current_frontier.id.into()); |
| 1660 | let dag = TestDag::new( |
| 1661 | vec![ |
| 1662 | peer_one_previous, |
| 1663 | first_relay, |
| 1664 | current_frontier.clone(), |
| 1665 | peer_one_next.clone(), |
| 1666 | ], |
| 1667 | peer_one_next.id.into(), |
| 1668 | ); |
| 1669 | |
| 1670 | let (ancestor, mode) = |
| 1671 | dag.find_replay_base(¤t_frontier.id.into(), &peer_one_next.id.into()); |
| 1672 | assert_eq!(ancestor, current_frontier.id.into()); |
| 1673 | assert_eq!(mode, DiffMode::ImportGreaterUpdates); |
| 1674 | } |
| 1675 | |
| 1676 | #[test] |
| 1677 | fn replay_base_keeps_uncovered_implicit_predecessor_conservative() { |
| 1678 | let peer_one_previous = node(1, 0, 1, 0, Frontiers::default()); |
| 1679 | let concurrent = node(2, 0, 1, 1, Frontiers::default()); |
| 1680 | let peer_one_next = node(1, 1, 1, 2, concurrent.id.into()); |
| 1681 | let dag = TestDag::new( |
| 1682 | vec![peer_one_previous, concurrent.clone(), peer_one_next.clone()], |
| 1683 | peer_one_next.id.into(), |
| 1684 | ); |
| 1685 | |
| 1686 | let (ancestor, mode) = |
| 1687 | dag.find_replay_base(&concurrent.id.into(), &peer_one_next.id.into()); |
| 1688 | assert_eq!(ancestor, Frontiers::default()); |
| 1689 | assert_eq!(mode, DiffMode::Checkout); |
| 1690 | } |
| 1691 | |
| 1692 | #[test] |
| 1693 | fn replay_base_falls_back_when_right_adds_concurrent_branch_from_shared_root() { |
| 1694 | let root = node(1, 0, 1, 0, Frontiers::default()); |
| 1695 | let root_id = root.id; |
| 1696 | let left = node(2, 0, 1, 1, root.id.into()); |
| 1697 | let concurrent = node(3, 0, 1, 2, root.id.into()); |
| 1698 | let merge = node(4, 0, 1, 3, Frontiers::from([left.id, concurrent.id])); |
| 1699 | let dag = TestDag::new( |
| 1700 | vec![root, left.clone(), concurrent, merge.clone()], |
| 1701 | merge.id.into(), |
| 1702 | ); |
| 1703 | |
| 1704 | let (ancestor, mode) = dag.find_replay_base(&left.id.into(), &merge.id.into()); |
| 1705 | // The conservative base retreats to the latest single-head critical |
| 1706 | // version below both sides — here the shared root — instead of the |
| 1707 | // beginning of history. |
| 1708 | assert_eq!(ancestor, root_id.into()); |
| 1709 | assert_eq!(mode, DiffMode::Checkout); |
| 1710 | } |
| 1711 | |
| 1712 | #[test] |
| 1713 | fn replay_base_falls_back_when_right_frontiers_add_concurrent_branch() { |
| 1714 | let root = node(1, 0, 1, 0, Frontiers::default()); |
| 1715 | let left = node(2, 0, 1, 1, root.id.into()); |
| 1716 | let concurrent = node(3, 0, 1, 2, root.id.into()); |
| 1717 | let right = Frontiers::from([left.id, concurrent.id]); |
| 1718 | let dag = TestDag::new(vec![root, left.clone(), concurrent], right.clone()); |
| 1719 | |
| 1720 | let (ancestor, mode) = dag.find_replay_base(&left.id.into(), &right); |
| 1721 | // Conservative base = the shared root (latest single-head critical |
| 1722 | // version), not the beginning of history. |
| 1723 | assert_eq!(ancestor, ID::new(1, 0).into()); |
| 1724 | assert_eq!(mode, DiffMode::Checkout); |
| 1725 | } |
| 1726 | |
| 1727 | #[test] |
| 1728 | fn replay_base_falls_back_when_left_frontiers_add_concurrent_branch() { |
| 1729 | let root = node(1, 0, 1, 0, Frontiers::default()); |
| 1730 | let shared = node(2, 0, 1, 1, root.id.into()); |
| 1731 | let concurrent = node(3, 0, 1, 2, root.id.into()); |
| 1732 | let left = Frontiers::from([shared.id, concurrent.id]); |
| 1733 | let dag = TestDag::new(vec![root, shared.clone(), concurrent], left.clone()); |
| 1734 | |
| 1735 | // The concurrent left head walks below `shared` without ever meeting the |
| 1736 | // right side. Only the tip seeded for the multi-element left frontier can |
| 1737 | // prove it uncovered; the deep node it dies at is itself covered. |
| 1738 | let (ancestor, mode) = dag.find_replay_base(&left, &shared.id.into()); |
| 1739 | // Conservative base = the shared root (latest single-head critical |
| 1740 | // version), not the beginning of history. |
| 1741 | assert_eq!(ancestor, ID::new(1, 0).into()); |
| 1742 | assert_eq!(mode, DiffMode::Checkout); |
| 1743 | } |
| 1744 | |
| 1745 | #[test] |
| 1746 | fn replay_base_falls_back_when_walk_reaches_trimmed_history() { |
| 1747 | // Peer 9's changes are not present in the DAG, as after shallow trimming. |
| 1748 | // Both sides die at the missing dependency inside the main walk, which |
| 1749 | // must force the conservative empty base regardless of tip coverage. |
| 1750 | let a = node(1, 0, 1, 5, ID::new(9, 5).into()); |
| 1751 | let b = node(2, 0, 1, 6, ID::new(9, 7).into()); |
| 1752 | let dag = TestDag::new(vec![a.clone(), b.clone()], Frontiers::from([a.id, b.id])); |
| 1753 | |
| 1754 | let (ancestor, mode) = dag.find_replay_base(&a.id.into(), &b.id.into()); |
| 1755 | assert_eq!(ancestor, Frontiers::default()); |
| 1756 | assert_eq!(mode, DiffMode::Checkout); |
| 1757 | } |
| 1758 | |
| 1759 | #[test] |
| 1760 | fn import_greater_updates_requires_new_ops_after_all_left_heads() { |
| 1761 | // Movable-tree staleness issue shape: B3 → B4..B6 and B3 → A0 → A1..A3. |
| 1762 | // from = {A0, B6}, to = {A3, B6}. Version inclusion holds |
| 1763 | // (vv(to) ⊇ vv(from)), yet A1..A3 are concurrent with the left head B6, |
| 1764 | // so ImportGreaterUpdates must not be claimed: the tree calculator's |
| 1765 | // fast path would apply A1..A3 without adjudicating against B4..B6. |
| 1766 | // The base must retreat to the latest critical version {B3}. |
| 1767 | let b_creates = node(2, 0, 4, 0, Frontiers::default()); |
| 1768 | let b_moves = node(2, 4, 3, 4, ID::new(2, 3).into()); |
| 1769 | let a0 = node(1, 0, 1, 4, ID::new(2, 3).into()); |
| 1770 | let a_moves = node(1, 1, 3, 5, ID::new(1, 0).into()); |
| 1771 | let dag = TestDag::new( |
| 1772 | vec![b_creates, b_moves, a0, a_moves], |
| 1773 | Frontiers::from([ID::new(1, 3), ID::new(2, 6)]), |
| 1774 | ); |
| 1775 | |
| 1776 | let left = Frontiers::from([ID::new(1, 0), ID::new(2, 6)]); |
| 1777 | let right = Frontiers::from([ID::new(1, 3), ID::new(2, 6)]); |
| 1778 | let (ancestor, mode) = dag.find_replay_base(&left, &right); |
| 1779 | assert_eq!(ancestor, ID::new(2, 3).into()); |
| 1780 | assert_eq!(mode, DiffMode::Checkout); |
| 1781 | } |
| 1782 | |
| 1783 | #[test] |
| 1784 | fn import_greater_updates_kept_when_new_ops_depend_on_all_left_heads() { |
| 1785 | // Healthy multi-head import: the new change's deps equal the whole |
| 1786 | // left frontier, so every new op is causally after all of it and the |
| 1787 | // fast path must be preserved (entry check passes by set equality). |
| 1788 | let root = node(1, 0, 1, 0, Frontiers::default()); |
| 1789 | let x = node(2, 0, 1, 1, ID::new(1, 0).into()); |
| 1790 | let y = node(3, 0, 1, 1, ID::new(1, 0).into()); |
| 1791 | let merge = node(4, 0, 1, 2, Frontiers::from([ID::new(2, 0), ID::new(3, 0)])); |
| 1792 | let dag = TestDag::new(vec![root, x, y, merge], ID::new(4, 0).into()); |
| 1793 | |
| 1794 | let left = Frontiers::from([ID::new(2, 0), ID::new(3, 0)]); |
| 1795 | let (ancestor, mode) = dag.find_replay_base(&left, &ID::new(4, 0).into()); |
| 1796 | assert_eq!(ancestor, left); |
| 1797 | assert_eq!(mode, DiffMode::ImportGreaterUpdates); |
| 1798 | } |
| 1799 | |
| 1800 | #[test] |
| 1801 | fn replay_base_criss_cross_ladder_stays_linear() { |
| 1802 | // Two peers that each merge both previous heads every round — the shape |
| 1803 | // ordinary bidirectional sync produces. Branch tips re-merge at every |
| 1804 | // rung; without deduplication in the tip union the walk is O(2^rounds) |
| 1805 | // (~minutes at this depth), with it the walk is linear (~microseconds). |
| 1806 | const ROUNDS: usize = 26; |
| 1807 | let root = node(3, 0, 1, 0, Frontiers::default()); |
| 1808 | let mut a_head = node(1, 0, 1, 1, root.id.into()); |
| 1809 | let mut b_head = node(2, 0, 1, 1, root.id.into()); |
| 1810 | let mut nodes = vec![root.clone(), a_head.clone(), b_head.clone()]; |
| 1811 | for k in 1..=ROUNDS { |
| 1812 | let deps = Frontiers::from([a_head.id_last(), b_head.id_last()]); |
| 1813 | let lamport = (k as Lamport) * 2; |
| 1814 | let next_a = node(1, k as Counter, 1, lamport, deps.clone()); |
| 1815 | let next_b = node(2, k as Counter, 1, lamport, deps); |
| 1816 | nodes.push(next_a.clone()); |
| 1817 | nodes.push(next_b.clone()); |
| 1818 | a_head = next_a; |
| 1819 | b_head = next_b; |
| 1820 | } |
| 1821 | let frontier = Frontiers::from([a_head.id_last(), b_head.id_last()]); |
| 1822 | let dag = TestDag::new(nodes, frontier.clone()); |
| 1823 | |
| 1824 | let start = std::time::Instant::now(); |
| 1825 | let (ancestor, mode) = dag.find_replay_base(&root.id.into(), &frontier); |
| 1826 | assert_eq!(ancestor, root.id.into()); |
| 1827 | assert_eq!(mode, DiffMode::ImportGreaterUpdates); |
| 1828 | // Generous 4-orders-of-magnitude margin over the fixed cost; the broken |
| 1829 | // exponential path needs minutes here even in release mode. |
| 1830 | assert!( |
| 1831 | start.elapsed() < std::time::Duration::from_secs(10), |
| 1832 | "criss-cross walk took {:?}; branch-tip growth is no longer linear", |
| 1833 | start.elapsed() |
| 1834 | ); |
| 1835 | } |
| 1836 | |
| 1837 | #[test] |
| 1838 | fn replay_base_keeps_target_when_checking_out_to_ancestor_with_extra_branch() { |
| 1839 | let root = node(1, 0, 1, 0, Frontiers::default()); |
| 1840 | let left = node(2, 0, 2, 1, root.id.into()); |
| 1841 | let right = node(3, 0, 2, 3, root.id.into()); |
| 1842 | let extra = node( |
| 1843 | 4, |
| 1844 | 0, |
| 1845 | 1, |
| 1846 | 5, |
| 1847 | Frontiers::from([left.id_last(), right.id_last()]), |
| 1848 | ); |
| 1849 | let dag = TestDag::new( |
| 1850 | vec![root, left.clone(), right.clone(), extra.clone()], |
| 1851 | extra.id.into(), |
| 1852 | ); |
| 1853 | let target = Frontiers::from([ID::new(2, 0), ID::new(3, 0)]); |
| 1854 | let current = Frontiers::from([extra.id, left.id_last(), right.id_last()]); |
| 1855 | |
| 1856 | let (ancestor, mode) = dag.find_replay_base(¤t, &target); |
| 1857 | assert_eq!(ancestor, target); |
| 1858 | assert_eq!(mode, DiffMode::Checkout); |
| 1859 | } |
| 1860 | |
| 1861 | #[test] |
| 1862 | fn replay_base_does_not_keep_ancestor_of_shared_descendant() { |
| 1863 | let root = node(1, 0, 1, 0, Frontiers::default()); |
| 1864 | let shared = node(2, 0, 1, 1, root.id.into()); |
| 1865 | let left_only = node(3, 0, 1, 2, root.id.into()); |
| 1866 | let right_only = node(4, 0, 1, 3, root.id.into()); |
| 1867 | let dag = TestDag::new( |
| 1868 | vec![root, shared.clone(), left_only.clone(), right_only.clone()], |
| 1869 | Frontiers::from([shared.id, left_only.id, right_only.id]), |
| 1870 | ); |
| 1871 | |
| 1872 | let (ancestor, mode) = dag.find_replay_base( |
| 1873 | &Frontiers::from([shared.id, left_only.id]), |
| 1874 | &Frontiers::from([shared.id, right_only.id]), |
| 1875 | ); |
| 1876 | assert_eq!(ancestor, shared.id.into()); |
| 1877 | assert_eq!(mode, DiffMode::Checkout); |
| 1878 | } |
| 1879 | |
| 1880 | #[test] |
| 1881 | fn replay_base_valid_against_slow_oracle_on_random_dags() { |
| 1882 | for seed in 0..128 { |
| 1883 | let mut rng = StdRng::seed_from_u64(seed); |
| 1884 | let dag = random_dag(seed, rng.gen_range(1..=18)); |
| 1885 | let ids = all_ids(&dag); |
| 1886 | for _ in 0..64 { |
| 1887 | let left = random_frontiers(&dag, &ids, &mut rng); |
| 1888 | let right = random_frontiers(&dag, &ids, &mut rng); |
| 1889 | assert_replay_base_valid_against_oracle(&dag, &left, &right); |
| 1890 | } |
| 1891 | } |
| 1892 | } |
| 1893 | |
| 1894 | #[test] |
| 1895 | fn replay_base_valid_against_slow_oracle_on_all_pairs_in_small_random_dags() { |
| 1896 | for seed in 1000..1020 { |
| 1897 | let dag = random_dag(seed, 8); |
| 1898 | let ids = all_ids(&dag); |
| 1899 | let mut frontiers = vec![Frontiers::default()]; |
| 1900 | frontiers.extend(ids.iter().copied().map(Frontiers::from)); |
| 1901 | for chunk in ids.chunks(3) { |
| 1902 | frontiers.push(maximal_frontiers(&dag, chunk.iter().copied())); |
| 1903 | } |
| 1904 | |
| 1905 | for left in frontiers.iter() { |
| 1906 | for right in frontiers.iter() { |
| 1907 | assert_replay_base_valid_against_oracle(&dag, left, right); |
| 1908 | } |
| 1909 | } |
| 1910 | } |
| 1911 | } |
| 1912 | |
| 1913 | #[test] |
| 1914 | fn replay_base_valid_against_slow_oracle_on_layered_merge_dag() { |
| 1915 | let dag = layered_merge_dag(); |
| 1916 | let ids = all_ids(&dag); |
| 1917 | let mut frontiers = vec![Frontiers::default(), dag.frontier().clone()]; |
| 1918 | frontiers.extend(ids.iter().copied().map(Frontiers::from)); |
| 1919 | frontiers.extend([ |
| 1920 | Frontiers::from([ID::new(1, 4), ID::new(2, 2)]), |
| 1921 | Frontiers::from([ID::new(1, 4), ID::new(3, 1)]), |
| 1922 | Frontiers::from([ID::new(4, 0), ID::new(2, 4), ID::new(3, 1)]), |
| 1923 | Frontiers::from([ID::new(5, 1), ID::new(6, 1)]), |
| 1924 | ]); |
| 1925 | |
| 1926 | for left in frontiers.iter() { |
| 1927 | for right in frontiers.iter() { |
| 1928 | assert_replay_base_valid_against_oracle(&dag, left, right); |
| 1929 | } |
| 1930 | } |
| 1931 | } |
| 1932 | |
| 1933 | #[test] |
| 1934 | fn replay_base_valid_against_slow_oracle_on_branchy_random_dags() { |
| 1935 | for seed in 2000..2064 { |
| 1936 | let mut rng = StdRng::seed_from_u64(seed); |
| 1937 | let dag = random_dag(seed, rng.gen_range(20..=36)); |
| 1938 | let ids = all_ids(&dag); |
| 1939 | for _ in 0..96 { |
| 1940 | let left = random_frontiers(&dag, &ids, &mut rng); |
| 1941 | let right = random_frontiers(&dag, &ids, &mut rng); |
| 1942 | assert_replay_base_valid_against_oracle(&dag, &left, &right); |
| 1943 | } |
| 1944 | } |
| 1945 | } |
| 1946 | |
| 1947 | #[test] |
| 1948 | fn find_path_reports_forward_and_retreat_spans_for_linear_and_branch_paths() { |
| 1949 | let first = node(1, 0, 2, 0, Frontiers::default()); |
| 1950 | let second = node(1, 2, 2, 2, ID::new(1, 1).into()); |
| 1951 | let side = node(2, 0, 1, 1, ID::new(1, 1).into()); |
| 1952 | let dag = TestDag::new( |
| 1953 | vec![first, second, side], |
| 1954 | Frontiers::from([ID::new(1, 3), ID::new(2, 0)]), |
| 1955 | ); |
| 1956 | |
| 1957 | let forward = dag.find_path(&ID::new(1, 0).into(), &ID::new(1, 3).into()); |
| 1958 | assert!(forward.retreat.is_empty()); |
| 1959 | assert_eq!(forward.forward.get(&1), Some(&CounterSpan::new(1, 4))); |
| 1960 | |
| 1961 | let retreat = dag.find_path(&ID::new(1, 3).into(), &ID::new(1, 0).into()); |
| 1962 | assert!(retreat.forward.is_empty()); |
| 1963 | assert_eq!(retreat.retreat.get(&1), Some(&CounterSpan::new(1, 4))); |
| 1964 | |
| 1965 | let branch = dag.find_path(&ID::new(2, 0).into(), &ID::new(1, 3).into()); |
| 1966 | assert_eq!(branch.retreat.get(&2), Some(&CounterSpan::new(0, 1))); |
| 1967 | assert_eq!(branch.forward.get(&1), Some(&CounterSpan::new(2, 4))); |
| 1968 | } |
| 1969 | |
| 1970 | #[test] |
| 1971 | fn get_version_vector_walks_dependencies_once_and_tracks_dep_ids_inside_spans() { |
| 1972 | let base = node(1, 0, 3, 0, Frontiers::default()); |
| 1973 | let left = node(2, 0, 1, 4, ID::new(1, 1).into()); |
| 1974 | let right = node(3, 0, 1, 5, ID::new(1, 2).into()); |
| 1975 | let merge = node(4, 0, 1, 6, Frontiers::from([left.id, right.id])); |
| 1976 | let dag = TestDag::new(vec![base, left, right, merge.clone()], merge.id.into()); |
| 1977 | |
| 1978 | let vv = dag.get_vv(merge.id); |
| 1979 | assert_eq!(vv.get_last(1), Some(2)); |
| 1980 | assert_eq!(vv.get_last(2), Some(0)); |
| 1981 | assert_eq!(vv.get_last(3), Some(0)); |
| 1982 | assert_eq!(vv.get_last(4), Some(0)); |
| 1983 | } |
| 1984 | |
| 1985 | #[test] |
| 1986 | fn remove_included_frontiers_drops_only_dependencies_at_or_after_recorded_frontiers() { |
| 1987 | let mut vv = VersionVector::default(); |
| 1988 | vv.set_last(ID::new(1, 3)); |
| 1989 | vv.set_last(ID::new(2, 4)); |
| 1990 | vv.set_last(ID::new(3, 1)); |
| 1991 | |
| 1992 | remove_included_frontiers(&mut vv, &[ID::new(1, 3), ID::new(2, 2), ID::new(4, 0)]); |
| 1993 | |
| 1994 | assert_eq!(vv.get_last(1), None); |
| 1995 | assert_eq!(vv.get_last(2), Some(4)); |
| 1996 | assert_eq!(vv.get_last(3), Some(1)); |
| 1997 | } |
| 1998 | |
| 1999 | #[test] |
| 2000 | fn ord_id_span_orders_by_last_lamport_peer_and_shorter_overlapping_span() { |
| 2001 | let short = OrdIdSpan { |
| 2002 | id: ID::new(1, 1), |
| 2003 | lamport: 1, |
| 2004 | len: 1, |
| 2005 | deps: Cow::Owned(Frontiers::default()), |
| 2006 | }; |
| 2007 | let long = OrdIdSpan { |
| 2008 | id: ID::new(1, 0), |
| 2009 | lamport: 0, |
| 2010 | len: 2, |
| 2011 | deps: Cow::Owned(Frontiers::default()), |
| 2012 | }; |
| 2013 | let later_peer = OrdIdSpan { |
| 2014 | id: ID::new(2, 0), |
| 2015 | lamport: 1, |
| 2016 | len: 1, |
| 2017 | deps: Cow::Owned(Frontiers::default()), |
| 2018 | }; |
| 2019 | |
| 2020 | assert!(short > long); |
| 2021 | assert!(later_peer > short); |
| 2022 | assert_eq!(long.get_min().len, 1); |
| 2023 | } |
| 2024 | } |