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 | use std::{collections::BTreeSet, ops::RangeInclusive, sync::Arc}; |
| 2 | |
| 3 | use fractional_index::FractionalIndex; |
| 4 | use loro_common::{ContainerID, IdFull, IdLp, Lamport, PeerID, TreeID, ID}; |
| 5 | use rustc_hash::FxHashMap; |
| 6 | |
| 7 | use crate::{ |
| 8 | container::{idx::ContainerIdx, tree::tree_op::TreeOp}, |
| 9 | delta::{TreeDelta, TreeDeltaItem, TreeInternalDiff}, |
| 10 | event::InternalDiff, |
| 11 | state::TreeParentId, |
| 12 | version::Frontiers, |
| 13 | OpLog, VersionVector, |
| 14 | }; |
| 15 | |
| 16 | use super::{DiffCalcVersionInfo, DiffCalculatorTrait, DiffMode}; |
| 17 | |
| 18 | #[derive(Debug)] |
| 19 | pub(crate) struct TreeDiffCalculator { |
| 20 | container: ContainerIdx, |
| 21 | mode: TreeDiffCalculatorMode, |
| 22 | } |
| 23 | |
| 24 | #[derive(Debug)] |
| 25 | enum TreeDiffCalculatorMode { |
| 26 | Crdt, |
| 27 | Linear(TreeDelta), |
| 28 | ImportGreaterUpdates(TreeDelta), |
| 29 | } |
| 30 | |
| 31 | impl DiffCalculatorTrait for TreeDiffCalculator { |
| 32 | fn start_tracking(&mut self, _oplog: &OpLog, _vv: &crate::VersionVector, mode: DiffMode) { |
| 33 | match mode { |
| 34 | DiffMode::Checkout => { |
| 35 | self.mode = TreeDiffCalculatorMode::Crdt; |
| 36 | } |
| 37 | DiffMode::Import => { |
| 38 | self.mode = TreeDiffCalculatorMode::Crdt; |
| 39 | } |
| 40 | DiffMode::ImportGreaterUpdates => { |
| 41 | self.mode = TreeDiffCalculatorMode::ImportGreaterUpdates(TreeDelta::default()); |
| 42 | } |
| 43 | DiffMode::Linear => { |
| 44 | self.mode = TreeDiffCalculatorMode::Linear(TreeDelta::default()); |
| 45 | } |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | fn apply_change( |
| 50 | &mut self, |
| 51 | _oplog: &OpLog, |
| 52 | op: crate::op::RichOp, |
| 53 | _vv: Option<&crate::VersionVector>, |
| 54 | ) { |
| 55 | match &mut self.mode { |
| 56 | TreeDiffCalculatorMode::Crdt => {} |
| 57 | TreeDiffCalculatorMode::Linear(ref mut delta) |
| 58 | | TreeDiffCalculatorMode::ImportGreaterUpdates(ref mut delta) => { |
| 59 | let id_full = op.id_full(); |
| 60 | let op = op.op(); |
| 61 | let content = op.content.as_tree().unwrap(); |
| 62 | |
| 63 | let item: TreeDeltaItem = match &**content { |
| 64 | crate::container::tree::tree_op::TreeOp::Create { |
| 65 | target, |
| 66 | parent, |
| 67 | position, |
| 68 | } => TreeDeltaItem { |
| 69 | target: *target, |
| 70 | action: TreeInternalDiff::Create { |
| 71 | parent: (*parent).into(), |
| 72 | position: position.clone(), |
| 73 | }, |
| 74 | last_effective_move_op_id: id_full, |
| 75 | }, |
| 76 | crate::container::tree::tree_op::TreeOp::Move { |
| 77 | target, |
| 78 | parent, |
| 79 | position, |
| 80 | } => TreeDeltaItem { |
| 81 | target: *target, |
| 82 | action: TreeInternalDiff::Move { |
| 83 | parent: (*parent).into(), |
| 84 | position: position.clone(), |
| 85 | }, |
| 86 | last_effective_move_op_id: id_full, |
| 87 | }, |
| 88 | crate::container::tree::tree_op::TreeOp::Delete { target } => TreeDeltaItem { |
| 89 | target: *target, |
| 90 | action: TreeInternalDiff::Delete { |
| 91 | parent: TreeParentId::Deleted, |
| 92 | position: None, |
| 93 | }, |
| 94 | last_effective_move_op_id: id_full, |
| 95 | }, |
| 96 | }; |
| 97 | |
| 98 | delta.diff.push(item); |
| 99 | } |
| 100 | } |
| 101 | } |
| 102 | |
| 103 | fn finish_this_round(&mut self) { |
| 104 | self.mode = TreeDiffCalculatorMode::Crdt; |
| 105 | } |
| 106 | |
| 107 | fn calculate_diff( |
| 108 | &mut self, |
| 109 | _idx: ContainerIdx, |
| 110 | oplog: &OpLog, |
| 111 | info: DiffCalcVersionInfo, |
| 112 | mut on_new_container: impl FnMut(&ContainerID), |
| 113 | ) -> (InternalDiff, DiffMode) { |
| 114 | match &mut self.mode { |
| 115 | TreeDiffCalculatorMode::Crdt => { |
| 116 | let diff = self.diff(oplog, info); |
| 117 | diff.diff.iter().for_each(|d| { |
| 118 | // the metadata could be modified before, so (re)create a node need emit the map container diffs |
| 119 | // `Create` here is because maybe in a diff calc uncreate and then create back |
| 120 | if matches!(d.action, TreeInternalDiff::Create { .. }) { |
| 121 | on_new_container(&d.target.associated_meta_container()) |
| 122 | } |
| 123 | }); |
| 124 | |
| 125 | (InternalDiff::Tree(diff), DiffMode::Checkout) |
| 126 | } |
| 127 | TreeDiffCalculatorMode::Linear(ans) => { |
| 128 | (InternalDiff::Tree(std::mem::take(ans)), DiffMode::Linear) |
| 129 | } |
| 130 | TreeDiffCalculatorMode::ImportGreaterUpdates(ans) => { |
| 131 | let mut ans = std::mem::take(ans); |
| 132 | ans.diff.sort_unstable_by(|a, b| { |
| 133 | a.last_effective_move_op_id |
| 134 | .lamport |
| 135 | .cmp(&b.last_effective_move_op_id.lamport) |
| 136 | .then_with(|| { |
| 137 | a.last_effective_move_op_id |
| 138 | .peer |
| 139 | .cmp(&b.last_effective_move_op_id.peer) |
| 140 | }) |
| 141 | }); |
| 142 | (InternalDiff::Tree(ans), DiffMode::ImportGreaterUpdates) |
| 143 | } |
| 144 | } |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | impl TreeDiffCalculator { |
| 149 | pub(crate) fn new(container: ContainerIdx) -> Self { |
| 150 | Self { |
| 151 | container, |
| 152 | mode: TreeDiffCalculatorMode::Crdt, |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | fn diff(&mut self, oplog: &OpLog, info: DiffCalcVersionInfo) -> TreeDelta { |
| 157 | self.checkout(info.from_vv, info.from_frontiers, oplog); |
| 158 | self.checkout_diff(info, oplog) |
| 159 | } |
| 160 | |
| 161 | /// Moves the diff cache to `to` without recording diffs. |
| 162 | fn checkout(&mut self, to: &VersionVector, to_frontiers: &Frontiers, oplog: &OpLog) { |
| 163 | oplog.with_history_cache(|h| { |
| 164 | let mark = h.ensure_importing_caches_exist(); |
| 165 | let tree_ops = h.get_tree(&self.container, mark).unwrap(); |
| 166 | let mut tree_cache = tree_ops.tree().lock(); |
| 167 | tree_cache.init_current_vv(oplog); |
| 168 | let s = format!("checkout current {:?} to {:?}", &tree_cache.current_vv, &to); |
| 169 | let s = tracing::span!(tracing::Level::INFO, "checkout", s = s); |
| 170 | let _e = s.enter(); |
| 171 | if to == &tree_cache.current_vv { |
| 172 | return; |
| 173 | } |
| 174 | let Some(min_lamport) = min_lamport_of_version_diff(&tree_cache.current_vv, to, oplog) |
| 175 | else { |
| 176 | tree_cache.current_vv = to.clone(); |
| 177 | return; |
| 178 | }; |
| 179 | |
| 180 | let ops = tree_ops.ops(); |
| 181 | let retreat = tree_cache.retreat_range(min_lamport); |
| 182 | for (idlp, op) in retreat.map(|r| ops.range(r)).into_iter().flatten() { |
| 183 | tree_cache.take(IdFull::new(idlp.peer, op.counter, idlp.lamport), &op.value); |
| 184 | } |
| 185 | tree_cache.retreated_from(min_lamport); |
| 186 | |
| 187 | let max_lamport = self |
| 188 | .get_max_lamport_by_frontiers(to_frontiers, oplog) |
| 189 | .max(min_lamport); |
| 190 | for (idlp, op) in |
| 191 | ops.range(IdLp::new(0, min_lamport)..=IdLp::new(PeerID::MAX, max_lamport)) |
| 192 | { |
| 193 | if to.includes_id(ID::new(idlp.peer, op.counter)) { |
| 194 | tree_cache.apply(MoveLamportAndID { |
| 195 | id: IdFull::new(idlp.peer, op.counter, idlp.lamport), |
| 196 | op: op.value.clone(), |
| 197 | effected: false, |
| 198 | }); |
| 199 | } |
| 200 | } |
| 201 | tree_cache.current_vv = to.clone(); |
| 202 | }); |
| 203 | } |
| 204 | |
| 205 | fn checkout_diff(&mut self, info: DiffCalcVersionInfo, oplog: &OpLog) -> TreeDelta { |
| 206 | oplog.with_history_cache(|h| { |
| 207 | let mark = h.ensure_importing_caches_exist(); |
| 208 | let tree_ops = h.get_tree(&self.container, mark).unwrap(); |
| 209 | let mut tree_cache = tree_ops.tree().lock(); |
| 210 | debug_assert_eq!(&tree_cache.current_vv, info.from_vv); |
| 211 | let mut parent_to_children_cache = |
| 212 | TreeParentToChildrenCache::init_from_tree_cache(&tree_cache); |
| 213 | let s = tracing::span!(tracing::Level::INFO, "checkout_diff"); |
| 214 | let _e = s.enter(); |
| 215 | // CORRECTNESS: `effected` (the cycle check) of each cached op |
| 216 | // depends on every op ordered before it, so the cache must always |
| 217 | // hold ops applied in (lamport, peer) order. Ops below |
| 218 | // `min_lamport` are the same in `from` and `to`; everything at or |
| 219 | // above it is retreated from `from` and replayed for `to` in that |
| 220 | // order. The window is taken from the versions themselves, not |
| 221 | // from a replay base: in `Checkout` mode `find_replay_base` may |
| 222 | // return a meet that is not a critical version, and ops concurrent |
| 223 | // with that meet can have lower lamports than it. See |
| 224 | // `context/tree-checkout-window.md`. |
| 225 | let Some(min_lamport) = min_lamport_of_version_diff(info.from_vv, info.to_vv, oplog) |
| 226 | else { |
| 227 | tree_cache.current_vv = info.to_vv.clone(); |
| 228 | return TreeDelta::default(); |
| 229 | }; |
| 230 | // `max` keeps the forward range well-formed when `to` only drops ops. |
| 231 | let to_max_lamport = self |
| 232 | .get_max_lamport_by_frontiers(info.to_frontiers, oplog) |
| 233 | .max(min_lamport); |
| 234 | let ops = tree_ops.ops(); |
| 235 | |
| 236 | let mut diffs = vec![]; |
| 237 | // retreat, newest first |
| 238 | let retreat = tree_cache.retreat_range(min_lamport); |
| 239 | for (idlp, op) in retreat.map(|r| ops.range(r)).into_iter().flatten().rev() { |
| 240 | let Some(op) = |
| 241 | tree_cache.take(IdFull::new(idlp.peer, op.counter, idlp.lamport), &op.value) |
| 242 | else { |
| 243 | continue; |
| 244 | }; |
| 245 | if !op.effected { |
| 246 | continue; |
| 247 | } |
| 248 | let (old_parent, position, last_effective_move_op_id) = |
| 249 | tree_cache.get_parent_with_id(op.op.target()); |
| 250 | // we need to know whether old_parent is deleted |
| 251 | let is_parent_deleted = tree_cache.is_parent_deleted(op.op.parent_id()); |
| 252 | let is_old_parent_deleted = tree_cache.is_parent_deleted(old_parent); |
| 253 | if op.op.target().id() == op.id.id() { |
| 254 | assert_eq!( |
| 255 | old_parent, |
| 256 | TreeParentId::Unexist, |
| 257 | "old_parent = {:?} instead", |
| 258 | &old_parent |
| 259 | ); |
| 260 | } |
| 261 | parent_to_children_cache.record_change( |
| 262 | op.op.target(), |
| 263 | op.op.parent_id(), |
| 264 | old_parent, |
| 265 | ); |
| 266 | let this_diff = TreeDeltaItem::new( |
| 267 | op.op.target(), |
| 268 | old_parent, |
| 269 | op.op.parent_id(), |
| 270 | last_effective_move_op_id, |
| 271 | is_old_parent_deleted, |
| 272 | is_parent_deleted, |
| 273 | position, |
| 274 | ); |
| 275 | let is_create = matches!(this_diff.action, TreeInternalDiff::Create { .. }); |
| 276 | diffs.push(this_diff); |
| 277 | if is_create { |
| 278 | tree_cache.push_children_creation( |
| 279 | op.op.target(), |
| 280 | &parent_to_children_cache, |
| 281 | &mut diffs, |
| 282 | ); |
| 283 | } |
| 284 | } |
| 285 | |
| 286 | tree_cache.retreated_from(min_lamport); |
| 287 | |
| 288 | // forward, oldest first |
| 289 | for (idlp, op) in |
| 290 | ops.range(IdLp::new(0, min_lamport)..=IdLp::new(PeerID::MAX, to_max_lamport)) |
| 291 | { |
| 292 | let id = ID::new(idlp.peer, op.counter); |
| 293 | if !info.to_vv.includes_id(id) { |
| 294 | continue; |
| 295 | } |
| 296 | let op = MoveLamportAndID { |
| 297 | id: IdFull { |
| 298 | peer: id.peer, |
| 299 | lamport: idlp.lamport, |
| 300 | counter: id.counter, |
| 301 | }, |
| 302 | op: op.value.clone(), |
| 303 | effected: false, |
| 304 | }; |
| 305 | let (old_parent, _position, _id) = tree_cache.get_parent_with_id(op.op.target()); |
| 306 | let is_parent_deleted = tree_cache.is_parent_deleted(op.op.parent_id()); |
| 307 | let is_old_parent_deleted = tree_cache.is_parent_deleted(old_parent); |
| 308 | let effected = tree_cache.apply(op.clone()); |
| 309 | if effected { |
| 310 | let this_diff = TreeDeltaItem::new( |
| 311 | op.op.target(), |
| 312 | op.op.parent_id(), |
| 313 | old_parent, |
| 314 | op.id_full(), |
| 315 | is_parent_deleted, |
| 316 | is_old_parent_deleted, |
| 317 | op.op.fractional_index(), |
| 318 | ); |
| 319 | parent_to_children_cache.record_change( |
| 320 | op.op.target(), |
| 321 | old_parent, |
| 322 | op.op.parent_id(), |
| 323 | ); |
| 324 | let is_create = matches!(this_diff.action, TreeInternalDiff::Create { .. }); |
| 325 | diffs.push(this_diff); |
| 326 | if is_create { |
| 327 | tree_cache.push_children_creation( |
| 328 | op.op.target(), |
| 329 | &parent_to_children_cache, |
| 330 | &mut diffs, |
| 331 | ); |
| 332 | } |
| 333 | } |
| 334 | } |
| 335 | |
| 336 | tree_cache.current_vv = info.to_vv.clone(); |
| 337 | TreeDelta { diff: diffs } |
| 338 | }) |
| 339 | } |
| 340 | |
| 341 | fn get_max_lamport_by_frontiers(&self, frontiers: &Frontiers, oplog: &OpLog) -> Lamport { |
| 342 | frontiers |
| 343 | .iter() |
| 344 | .map(|id| oplog.get_max_lamport_at(id)) |
| 345 | .max() |
| 346 | .unwrap_or(Lamport::MAX) |
| 347 | } |
| 348 | } |
| 349 | |
| 350 | /// The smallest lamport among the ops that are in exactly one of `a` and `b`, |
| 351 | /// or `None` when both contain the same ops. |
| 352 | /// |
| 353 | /// Every tree op below it is in both versions, so moving the diff cache |
| 354 | /// between them only has to retreat and replay the ops at or above it. |
| 355 | fn min_lamport_of_version_diff( |
| 356 | a: &VersionVector, |
| 357 | b: &VersionVector, |
| 358 | oplog: &OpLog, |
| 359 | ) -> Option<Lamport> { |
| 360 | a.sub_iter(b) |
| 361 | .chain(b.sub_iter(a)) |
| 362 | .map(|span| { |
| 363 | let id = ID::new(span.peer, span.counter.start); |
| 364 | oplog |
| 365 | .dag |
| 366 | .get_lamport(&id) |
| 367 | .unwrap_or_else(|| panic!("op {id} of a tree diff version is not in the DAG")) |
| 368 | }) |
| 369 | .min() |
| 370 | } |
| 371 | |
| 372 | /// All information of an operation for diff calculating of movable tree. |
| 373 | #[derive(Debug, Clone)] |
| 374 | pub struct MoveLamportAndID { |
| 375 | pub(crate) id: IdFull, |
| 376 | pub(crate) op: Arc<TreeOp>, |
| 377 | /// Whether this action is applied in the current version. |
| 378 | /// If this action will cause a circular reference, then this action will not be applied. |
| 379 | pub(crate) effected: bool, |
| 380 | } |
| 381 | |
| 382 | impl MoveLamportAndID { |
| 383 | fn id_full(&self) -> IdFull { |
| 384 | self.id |
| 385 | } |
| 386 | } |
| 387 | |
| 388 | impl PartialEq for MoveLamportAndID { |
| 389 | fn eq(&self, other: &Self) -> bool { |
| 390 | self.id == other.id |
| 391 | } |
| 392 | } |
| 393 | |
| 394 | impl Eq for MoveLamportAndID {} |
| 395 | |
| 396 | impl PartialOrd for MoveLamportAndID { |
| 397 | fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { |
| 398 | Some(self.cmp(other)) |
| 399 | } |
| 400 | } |
| 401 | |
| 402 | impl Ord for MoveLamportAndID { |
| 403 | fn cmp(&self, other: &Self) -> std::cmp::Ordering { |
| 404 | self.id |
| 405 | .lamport |
| 406 | .cmp(&other.id.lamport) |
| 407 | .then_with(|| self.id.peer.cmp(&other.id.peer)) |
| 408 | } |
| 409 | } |
| 410 | |
| 411 | #[derive(Clone, Default)] |
| 412 | pub(crate) struct TreeCacheForDiff { |
| 413 | tree: FxHashMap<TreeID, BTreeSet<MoveLamportAndID>>, |
| 414 | current_vv: VersionVector, |
| 415 | /// `false` until the first transition. In a shallow doc the cache starts |
| 416 | /// at the shallow root (seeded with its state, or empty when the tree had |
| 417 | /// no nodes there), which `current_vv` does not express yet. |
| 418 | current_vv_initialized: bool, |
| 419 | /// No cached op has a greater lamport. Bounds the retreat so it does not |
| 420 | /// walk the ops above the cached version, which can be most of the |
| 421 | /// history when checking out between two old versions. |
| 422 | max_lamport: Lamport, |
| 423 | } |
| 424 | |
| 425 | impl std::fmt::Debug for TreeCacheForDiff { |
| 426 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 427 | writeln!(f, "TreeCacheForDiff {{ tree: ")?; |
| 428 | for (id, ops) in self.tree.iter() { |
| 429 | writeln!(f, " {} -> {:?}", id, ops)?; |
| 430 | } |
| 431 | writeln!(f, " current_vv: {:?}", self.current_vv)?; |
| 432 | Ok(()) |
| 433 | } |
| 434 | } |
| 435 | |
| 436 | impl TreeCacheForDiff { |
| 437 | /// Removes the op from the cache if it is there, returning it with its |
| 438 | /// `effected` flag. |
| 439 | fn take(&mut self, id: IdFull, op: &Arc<TreeOp>) -> Option<MoveLamportAndID> { |
| 440 | self.tree.get_mut(&op.target())?.take(&MoveLamportAndID { |
| 441 | id, |
| 442 | op: op.clone(), |
| 443 | effected: false, |
| 444 | }) |
| 445 | } |
| 446 | |
| 447 | /// The `IdLp` range holding every cached op whose lamport is at least |
| 448 | /// `min_lamport`, or `None` when there is none. |
| 449 | fn retreat_range(&self, min_lamport: Lamport) -> Option<RangeInclusive<IdLp>> { |
| 450 | (self.max_lamport >= min_lamport) |
| 451 | .then(|| IdLp::new(0, min_lamport)..=IdLp::new(PeerID::MAX, self.max_lamport)) |
| 452 | } |
| 453 | |
| 454 | /// Records that every cached op whose lamport is at least `min_lamport` |
| 455 | /// has been retreated. |
| 456 | fn retreated_from(&mut self, min_lamport: Lamport) { |
| 457 | self.max_lamport = self.max_lamport.min(min_lamport.saturating_sub(1)); |
| 458 | } |
| 459 | |
| 460 | fn init_current_vv(&mut self, oplog: &OpLog) { |
| 461 | if self.current_vv_initialized { |
| 462 | return; |
| 463 | } |
| 464 | |
| 465 | self.current_vv_initialized = true; |
| 466 | if oplog.is_shallow() { |
| 467 | self.current_vv = oplog |
| 468 | .dag |
| 469 | .frontiers_to_vv(oplog.dag.shallow_since_frontiers()) |
| 470 | .expect("the shallow root version must be in the DAG"); |
| 471 | } |
| 472 | } |
| 473 | |
| 474 | /// After `target` is (re)created, pushes a `Create` for each node of its |
| 475 | /// current subtree. |
| 476 | fn push_children_creation( |
| 477 | &self, |
| 478 | target: TreeID, |
| 479 | cache: &TreeParentToChildrenCache, |
| 480 | diffs: &mut Vec<TreeDeltaItem>, |
| 481 | ) { |
| 482 | let mut s = vec![target]; |
| 483 | while let Some(t) = s.pop() { |
| 484 | let children = self.get_children_with_id(TreeParentId::Node(t), cache); |
| 485 | diffs.extend(children.iter().map(|c| TreeDeltaItem { |
| 486 | target: c.0, |
| 487 | action: TreeInternalDiff::Create { |
| 488 | parent: TreeParentId::Node(t), |
| 489 | position: c.1.clone().unwrap(), |
| 490 | }, |
| 491 | last_effective_move_op_id: c.2, |
| 492 | })); |
| 493 | s.extend(children.iter().map(|c| c.0)); |
| 494 | } |
| 495 | } |
| 496 | |
| 497 | fn is_ancestor_of(&self, maybe_ancestor: &TreeID, node_id: &TreeParentId) -> bool { |
| 498 | if !self.tree.contains_key(maybe_ancestor) { |
| 499 | return false; |
| 500 | } |
| 501 | if let TreeParentId::Node(id) = node_id { |
| 502 | if id == maybe_ancestor { |
| 503 | return true; |
| 504 | } |
| 505 | } |
| 506 | match node_id { |
| 507 | TreeParentId::Node(id) => { |
| 508 | let (parent, _, _) = &self.get_parent_with_id(*id); |
| 509 | if parent == node_id { |
| 510 | panic!("is_ancestor_of loop") |
| 511 | } |
| 512 | self.is_ancestor_of(maybe_ancestor, parent) |
| 513 | } |
| 514 | TreeParentId::Deleted | TreeParentId::Root => false, |
| 515 | TreeParentId::Unexist => false, |
| 516 | } |
| 517 | } |
| 518 | |
| 519 | fn apply(&mut self, mut node: MoveLamportAndID) -> bool { |
| 520 | let mut effected = true; |
| 521 | if self.is_ancestor_of(&node.op.target(), &node.op.parent_id()) { |
| 522 | effected = false; |
| 523 | } |
| 524 | node.effected = effected; |
| 525 | self.max_lamport = self.max_lamport.max(node.id.lamport); |
| 526 | self.current_vv.set_last(node.id.id()); |
| 527 | self.tree.entry(node.op.target()).or_default().insert(node); |
| 528 | effected |
| 529 | } |
| 530 | |
| 531 | pub(crate) fn init_tree_with_shallow_root_version(&mut self, nodes: Vec<MoveLamportAndID>) { |
| 532 | if nodes.is_empty() { |
| 533 | return; |
| 534 | } |
| 535 | |
| 536 | debug_assert!(self.tree.is_empty()); |
| 537 | for node in nodes.into_iter() { |
| 538 | self.max_lamport = self.max_lamport.max(node.id.lamport); |
| 539 | self.current_vv.extend_to_include_last_id(node.id.id()); |
| 540 | self.current_vv |
| 541 | .extend_to_include_last_id(node.op.target().id()); |
| 542 | self.tree.entry(node.op.target()).or_default().insert(node); |
| 543 | } |
| 544 | } |
| 545 | |
| 546 | fn is_parent_deleted(&self, parent: TreeParentId) -> bool { |
| 547 | match parent { |
| 548 | TreeParentId::Deleted => true, |
| 549 | TreeParentId::Node(id) => self.is_parent_deleted(self.get_parent_with_id(id).0), |
| 550 | TreeParentId::Root => false, |
| 551 | TreeParentId::Unexist => false, |
| 552 | } |
| 553 | } |
| 554 | |
| 555 | /// get the parent of the first effected op and its id |
| 556 | fn get_parent_with_id( |
| 557 | &self, |
| 558 | tree_id: TreeID, |
| 559 | ) -> (TreeParentId, Option<FractionalIndex>, IdFull) { |
| 560 | let mut ans = (TreeParentId::Unexist, None, IdFull::NONE_ID); |
| 561 | if let Some(cache) = self.tree.get(&tree_id) { |
| 562 | for op in cache.iter().rev() { |
| 563 | if op.effected { |
| 564 | ans = ( |
| 565 | op.op.parent_id(), |
| 566 | op.op.fractional_index().clone(), |
| 567 | op.id_full(), |
| 568 | ); |
| 569 | break; |
| 570 | } |
| 571 | } |
| 572 | } |
| 573 | ans |
| 574 | } |
| 575 | |
| 576 | /// get the parent of the last effected op |
| 577 | fn get_last_effective_move(&self, tree_id: TreeID) -> Option<&MoveLamportAndID> { |
| 578 | if TreeID::is_deleted_root(&tree_id) { |
| 579 | return None; |
| 580 | } |
| 581 | |
| 582 | let mut ans = None; |
| 583 | if let Some(set) = self.tree.get(&tree_id) { |
| 584 | for op in set.iter().rev() { |
| 585 | if op.effected { |
| 586 | ans = Some(op); |
| 587 | break; |
| 588 | } |
| 589 | } |
| 590 | } |
| 591 | |
| 592 | ans |
| 593 | } |
| 594 | |
| 595 | fn get_children_with_id( |
| 596 | &self, |
| 597 | parent: TreeParentId, |
| 598 | cache: &TreeParentToChildrenCache, |
| 599 | ) -> Vec<(TreeID, Option<FractionalIndex>, IdFull)> { |
| 600 | let Some(children_ids) = cache.get_children(parent) else { |
| 601 | return vec![]; |
| 602 | }; |
| 603 | let mut ans = Vec::with_capacity(children_ids.len()); |
| 604 | for child in children_ids.iter() { |
| 605 | let Some(op) = self.get_last_effective_move(*child) else { |
| 606 | panic!("child {:?} has no last effective move", child); |
| 607 | }; |
| 608 | |
| 609 | assert_eq!(op.op.parent_id(), parent); |
| 610 | ans.push((*child, op.op.fractional_index().clone(), op.id_full())); |
| 611 | } |
| 612 | // The children should be sorted by the position. |
| 613 | // If the fractional index is the same, then sort by the lamport and peer. |
| 614 | ans.sort_by(|a, b| { |
| 615 | a.1.cmp(&b.1) |
| 616 | .then(a.2.lamport.cmp(&b.2.lamport).then(a.2.peer.cmp(&b.2.peer))) |
| 617 | }); |
| 618 | ans |
| 619 | } |
| 620 | } |
| 621 | |
| 622 | #[derive(Debug)] |
| 623 | struct TreeParentToChildrenCache { |
| 624 | cache: FxHashMap<TreeParentId, BTreeSet<TreeID>>, |
| 625 | } |
| 626 | |
| 627 | impl TreeParentToChildrenCache { |
| 628 | fn get_children(&self, parent: TreeParentId) -> Option<&BTreeSet<TreeID>> { |
| 629 | self.cache.get(&parent) |
| 630 | } |
| 631 | |
| 632 | fn init_from_tree_cache(tree_cache: &TreeCacheForDiff) -> Self { |
| 633 | let mut cache = Self { |
| 634 | cache: FxHashMap::default(), |
| 635 | }; |
| 636 | for (tree_id, _) in tree_cache.tree.iter() { |
| 637 | let Some(op) = tree_cache.get_last_effective_move(*tree_id) else { |
| 638 | continue; |
| 639 | }; |
| 640 | |
| 641 | cache |
| 642 | .cache |
| 643 | .entry(op.op.parent_id()) |
| 644 | .or_default() |
| 645 | .insert(op.op.target()); |
| 646 | } |
| 647 | cache |
| 648 | } |
| 649 | |
| 650 | fn record_change( |
| 651 | &mut self, |
| 652 | target: TreeID, |
| 653 | old_parent: TreeParentId, |
| 654 | new_parent: TreeParentId, |
| 655 | ) { |
| 656 | if !old_parent.is_unexist() { |
| 657 | let removed = if let Some(children) = self.cache.get_mut(&old_parent) { |
| 658 | children.remove(&target) |
| 659 | } else { |
| 660 | false |
| 661 | }; |
| 662 | |
| 663 | if !removed { |
| 664 | let removed = self |
| 665 | .cache |
| 666 | .values_mut() |
| 667 | .any(|children| children.remove(&target)); |
| 668 | assert!( |
| 669 | removed, |
| 670 | "target {target:?} should be present in TreeParentToChildrenCache before moving from {old_parent:?} to {new_parent:?}", |
| 671 | ); |
| 672 | } |
| 673 | } |
| 674 | self.cache.entry(new_parent).or_default().insert(target); |
| 675 | } |
| 676 | } |
| 677 | |
| 678 | #[cfg(test)] |
| 679 | mod test { |
| 680 | use loro_common::{TreeID, ID}; |
| 681 | |
| 682 | use crate::{state::TreeParentId, version::Frontiers, HandlerTrait, LoroDoc}; |
| 683 | |
| 684 | /// Checking out between two old versions must retreat only what the cache |
| 685 | /// holds: `max_lamport` bounds every cached op, and stays at the cached |
| 686 | /// version instead of the end of the history. |
| 687 | #[test] |
| 688 | fn retreat_bound_follows_the_cached_version() { |
| 689 | let doc = LoroDoc::new_auto_commit(); |
| 690 | doc.set_peer_id(1).unwrap(); |
| 691 | let tree = doc.get_tree("tree"); |
| 692 | let nodes: Vec<TreeID> = (0..20) |
| 693 | .map(|_| tree.create(TreeParentId::Root).unwrap()) |
| 694 | .collect(); |
| 695 | doc.commit_then_renew(); |
| 696 | let mut versions = vec![]; |
| 697 | for i in 0..400 { |
| 698 | let _ = tree.mov(nodes[i % 20], TreeParentId::Node(nodes[(i * 7 + 3) % 20])); |
| 699 | doc.commit_then_renew(); |
| 700 | versions.push(doc.oplog_frontiers()); |
| 701 | } |
| 702 | |
| 703 | let (v1, v2) = (&versions[10], &versions[20]); |
| 704 | let lamport_of = |f: &Frontiers| { |
| 705 | let id: ID = f.as_single().unwrap(); |
| 706 | doc.oplog().lock().dag.get_lamport(&id).unwrap() |
| 707 | }; |
| 708 | for v in [v1, v2, v1, v2] { |
| 709 | doc.checkout(v).unwrap(); |
| 710 | let (cached_max, bound) = doc.oplog().lock().with_history_cache(|h| { |
| 711 | let mark = h.ensure_importing_caches_exist(); |
| 712 | let cache = h.get_tree(&tree.idx(), mark).unwrap().tree().lock(); |
| 713 | let cached_max = cache |
| 714 | .tree |
| 715 | .values() |
| 716 | .flat_map(|ops| ops.iter().map(|op| op.id.lamport)) |
| 717 | .max() |
| 718 | .unwrap(); |
| 719 | (cached_max, cache.max_lamport) |
| 720 | }); |
| 721 | assert!(cached_max <= bound); |
| 722 | assert!(bound <= lamport_of(v)); |
| 723 | } |
| 724 | } |
| 725 | } |