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::{num::NonZeroU16, sync::Arc}; |
| 2 | |
| 3 | #[cfg(feature = "counter")] |
| 4 | mod counter; |
| 5 | #[cfg(feature = "counter")] |
| 6 | pub(crate) use counter::CounterDiffCalculator; |
| 7 | mod tracker_texts; |
| 8 | mod tracker_values; |
| 9 | pub(super) mod tree; |
| 10 | mod unknown; |
| 11 | use either::Either; |
| 12 | use generic_btree::rle::{HasLength as _, Sliceable as _}; |
| 13 | use itertools::Itertools; |
| 14 | use tracker_texts::TrackerTexts; |
| 15 | use tracker_values::TrackerValues; |
| 16 | |
| 17 | use enum_dispatch::enum_dispatch; |
| 18 | use loro_common::{ |
| 19 | CompactIdLp, ContainerID, Counter, HasCounterSpan, IdFull, IdLp, IdSpan, LoroValue, PeerID, ID, |
| 20 | }; |
| 21 | use loro_delta::DeltaRope; |
| 22 | use rustc_hash::{FxHashMap, FxHashSet}; |
| 23 | use smallvec::SmallVec; |
| 24 | use tracing::{info_span, instrument}; |
| 25 | |
| 26 | use crate::{ |
| 27 | change::Lamport, |
| 28 | container::{ |
| 29 | idx::ContainerIdx, |
| 30 | list::list_op::InnerListOp, |
| 31 | richtext::{ |
| 32 | richtext_state::{RichtextStateChunk, TextChunk}, |
| 33 | AnchorType, CrdtRopeDelta, RichtextChunk, RichtextChunkValue, RichtextTracker, StyleOp, |
| 34 | }, |
| 35 | }, |
| 36 | cursor::AbsolutePosition, |
| 37 | delta::{ |
| 38 | Delta, DeltaItem, DeltaValue, ElementDelta, MapDelta, MapValue, MovableListInnerDelta, |
| 39 | }, |
| 40 | event::{DiffVariant, InternalDiff}, |
| 41 | op::{InnerContent, RichOp, SliceWithId}, |
| 42 | span::{HasId, HasLamport}, |
| 43 | version::Frontiers, |
| 44 | InternalString, VersionVector, |
| 45 | }; |
| 46 | |
| 47 | use self::tree::TreeDiffCalculator; |
| 48 | |
| 49 | use self::unknown::UnknownDiffCalculator; |
| 50 | |
| 51 | use super::{ |
| 52 | event::InternalContainerDiff, |
| 53 | oplog::{OpLog, ReplayBase}, |
| 54 | }; |
| 55 | |
| 56 | /// Calculate the diff between two versions. given [OpLog][super::oplog::OpLog] |
| 57 | /// and [AppState][super::state::AppState]. |
| 58 | /// |
| 59 | /// TODO: persist diffCalculator and skip processed version |
| 60 | #[derive(Debug)] |
| 61 | pub struct DiffCalculator { |
| 62 | /// ContainerIdx -> (depth, calculator) |
| 63 | /// |
| 64 | /// if depth is None, we need to calculate it again |
| 65 | calculators: FxHashMap<ContainerIdx, (Option<NonZeroU16>, ContainerDiffCalculator)>, |
| 66 | retain_mode: DiffCalculatorRetainMode, |
| 67 | } |
| 68 | |
| 69 | #[derive(Debug)] |
| 70 | enum DiffCalculatorRetainMode { |
| 71 | /// The diff calculator can only be used once. |
| 72 | Once { used: bool }, |
| 73 | /// The diff calculator will be persisted and can be reused after the diff calc is done. |
| 74 | Persist, |
| 75 | } |
| 76 | |
| 77 | /// This mode defines how the diff is calculated and how it should be applied on the state. |
| 78 | #[derive(Debug, Clone, PartialEq, Eq, Copy)] |
| 79 | pub(crate) enum DiffMode { |
| 80 | /// This is the most general mode of diff calculation. |
| 81 | /// |
| 82 | /// When applying `Checkout` diff, we already know the current state of the affected registers. |
| 83 | /// So there is no need to compare the lamport values. |
| 84 | /// |
| 85 | /// It can be used whenever a user want to switch to a different version. |
| 86 | /// But it is also the slowest mode. It relies on the `ContainerHistoryCache`, which is expensive to build and maintain in memory. |
| 87 | Checkout, |
| 88 | /// This mode is used when the user imports new updates. |
| 89 | /// |
| 90 | /// When applying `Import` diff, we may need to know the the current state. |
| 91 | /// For example, we may need to compare the current register's lamport with the update's lamport to decide |
| 92 | /// what's the new value. |
| 93 | /// |
| 94 | /// It has stricter requirements than `Checkout`: |
| 95 | /// |
| 96 | /// - The target version vector must be greater than the current version vector. |
| 97 | Import, |
| 98 | /// This mode is used when the user imports new updates and all the updates are guaranteed to greater than the current version. |
| 99 | /// |
| 100 | /// It has stricter requirements than `Import`. |
| 101 | /// - All the updates are greater than the current version. No update is concurrent to the current version. |
| 102 | /// - So the replay base is always the `from` version |
| 103 | ImportGreaterUpdates, |
| 104 | /// This mode is used when we don't need to build CRDTs to calculate the difference. It is the fastest mode. |
| 105 | /// |
| 106 | /// It has stricter requirements than `ImportGreaterUpdates`. |
| 107 | /// - In `ImportGreaterUpdates`, all the updates are guaranteed to be greater than the current version. |
| 108 | /// - In `Linear`, all the updates are ordered, no concurrent update exists. |
| 109 | Linear, |
| 110 | } |
| 111 | |
| 112 | #[derive(Debug, Clone, Copy)] |
| 113 | pub(crate) struct DiffCalcVersionInfo<'a> { |
| 114 | from_vv: &'a VersionVector, |
| 115 | to_vv: &'a VersionVector, |
| 116 | from_frontiers: &'a Frontiers, |
| 117 | to_frontiers: &'a Frontiers, |
| 118 | replay_base_vv: &'a VersionVector, |
| 119 | /// The replay base is a critical version of `ancestry(from) ∪ ancestry(to)`: |
| 120 | /// nothing above it is concurrent with anything below it. See |
| 121 | /// `OpLog::iter_from_replay_base_causally`. |
| 122 | replay_base_is_critical: bool, |
| 123 | } |
| 124 | |
| 125 | fn changed_containers_between( |
| 126 | oplog: &OpLog, |
| 127 | before: &VersionVector, |
| 128 | after: &VersionVector, |
| 129 | ) -> loro_common::LoroResult<FxHashSet<ContainerIdx>> { |
| 130 | let (retreat, forward) = before.diff_iter(after); |
| 131 | oplog.try_containers_in_spans(retreat.chain(forward)) |
| 132 | } |
| 133 | |
| 134 | impl DiffCalculator { |
| 135 | /// Create a new diff calculator. |
| 136 | /// |
| 137 | /// If `persist` is true, the diff calculator will be persisted after the diff calc is done. |
| 138 | /// This is useful when we need to cache the diff calculator for future use. But it is slower |
| 139 | /// for importing updates and requires more memory. |
| 140 | pub fn new(persist: bool) -> Self { |
| 141 | Self { |
| 142 | calculators: Default::default(), |
| 143 | retain_mode: if persist { |
| 144 | DiffCalculatorRetainMode::Persist |
| 145 | } else { |
| 146 | DiffCalculatorRetainMode::Once { used: false } |
| 147 | }, |
| 148 | } |
| 149 | } |
| 150 | |
| 151 | /// The containers touched by the ranges this calculator has computed diffs for. |
| 152 | pub(crate) fn touched_containers(&self) -> impl Iterator<Item = ContainerIdx> + '_ { |
| 153 | self.calculators.keys().copied() |
| 154 | } |
| 155 | |
| 156 | #[allow(unused)] |
| 157 | pub(crate) fn get_calc(&self, container: ContainerIdx) -> Option<&ContainerDiffCalculator> { |
| 158 | self.calculators.get(&container).map(|(_, c)| c) |
| 159 | } |
| 160 | |
| 161 | /// Calculate the diff between two versions. |
| 162 | /// |
| 163 | /// Return the diff and the origin diff mode (it's not the diff mode used by the diff calculator. |
| 164 | /// It's the expected diff mode inferred from the two version, which can reflect the direction of the |
| 165 | /// change). |
| 166 | pub(crate) fn calc_diff_internal( |
| 167 | &mut self, |
| 168 | oplog: &OpLog, |
| 169 | before: &VersionVector, |
| 170 | before_frontiers: &Frontiers, |
| 171 | after: &VersionVector, |
| 172 | after_frontiers: &Frontiers, |
| 173 | container_filter: Option<&dyn Fn(ContainerIdx) -> bool>, |
| 174 | ) -> (Vec<InternalContainerDiff>, DiffMode) { |
| 175 | self.try_calc_diff_internal( |
| 176 | oplog, |
| 177 | before, |
| 178 | before_frontiers, |
| 179 | after, |
| 180 | after_frontiers, |
| 181 | container_filter, |
| 182 | ) |
| 183 | .unwrap() |
| 184 | } |
| 185 | |
| 186 | pub(crate) fn try_calc_diff_internal( |
| 187 | &mut self, |
| 188 | oplog: &super::oplog::OpLog, |
| 189 | before: &crate::VersionVector, |
| 190 | before_frontiers: &Frontiers, |
| 191 | after: &crate::VersionVector, |
| 192 | after_frontiers: &Frontiers, |
| 193 | container_filter: Option<&dyn Fn(ContainerIdx) -> bool>, |
| 194 | ) -> loro_common::LoroResult<(Vec<InternalContainerDiff>, DiffMode)> { |
| 195 | if before == after { |
| 196 | return Ok((Vec::new(), DiffMode::Linear)); |
| 197 | } |
| 198 | |
| 199 | let s = tracing::span!(tracing::Level::INFO, "DiffCalc", ?before, ?after,); |
| 200 | let _e = s.enter(); |
| 201 | |
| 202 | let mut merged = before.clone(); |
| 203 | merged.merge(after); |
| 204 | let ( |
| 205 | ReplayBase { |
| 206 | vv: replay_base, |
| 207 | diff_mode: origin_diff_mode, |
| 208 | is_critical: replay_base_is_critical, |
| 209 | concurrent_containers, |
| 210 | }, |
| 211 | iter, |
| 212 | ) = oplog.try_iter_from_replay_base_causally( |
| 213 | before, |
| 214 | before_frontiers, |
| 215 | after, |
| 216 | after_frontiers, |
| 217 | )?; |
| 218 | // A conservative replay base may be much older than `before`. The causal replay |
| 219 | // still needs that common history as position context, but containers |
| 220 | // whose ops are present on both sides cannot contribute to the diff. |
| 221 | // Without this filter, every such List/Text/MovableList can trigger its |
| 222 | // own full-history safety rebuild below. |
| 223 | let changed_containers = (&replay_base != before) |
| 224 | .then(|| changed_containers_between(oplog, before, after)) |
| 225 | .transpose()?; |
| 226 | // Two distinct mode values live in this function — do not conflate them: |
| 227 | // - `origin_diff_mode` describes the DIRECTION of the transition |
| 228 | // (Checkout can go backwards; the other modes imply `after ⊇ before`). |
| 229 | // It is what this function returns, and its consumer |
| 230 | // (`DocState::apply_diff`) uses it only for direction-sensitive |
| 231 | // policies such as the dead-containers cache. |
| 232 | // - `calc_mode` is the mode the calculators actually COMPUTE with. A |
| 233 | // persistent calculator always computes in Checkout mode, and each |
| 234 | // calculator reports its own effective mode in the per-container |
| 235 | // `InternalContainerDiff::diff_mode`, which is what the state layer's |
| 236 | // per-container logic (`need_check` / `need_compare`) consumes. |
| 237 | let mut calc_mode = origin_diff_mode; |
| 238 | match &mut self.retain_mode { |
| 239 | DiffCalculatorRetainMode::Once { used } => { |
| 240 | if *used { |
| 241 | panic!("DiffCalculator with retain_mode Once can only be used once"); |
| 242 | } |
| 243 | } |
| 244 | DiffCalculatorRetainMode::Persist => { |
| 245 | calc_mode = DiffMode::Checkout; |
| 246 | } |
| 247 | } |
| 248 | |
| 249 | let affected_set = { |
| 250 | loro_common::debug!("replay_base: {:?} mode={:?}", &replay_base, calc_mode); |
| 251 | let mut started_set = FxHashSet::default(); |
| 252 | for item in iter { |
| 253 | let (change, (start_counter, end_counter), vv) = item?; |
| 254 | let iter_start = change |
| 255 | .ops |
| 256 | .binary_search_by(|op| op.ctr_last().cmp(&start_counter)) |
| 257 | .unwrap_or_else(|e| e); |
| 258 | let mut visited = FxHashSet::default(); |
| 259 | for mut op in &change.ops.vec()[iter_start..] { |
| 260 | if op.counter >= end_counter { |
| 261 | break; |
| 262 | } |
| 263 | |
| 264 | let idx = op.container; |
| 265 | if changed_containers |
| 266 | .as_ref() |
| 267 | .is_some_and(|containers| !containers.contains(&idx)) |
| 268 | { |
| 269 | continue; |
| 270 | } |
| 271 | |
| 272 | if let Some(filter) = container_filter { |
| 273 | if !filter(idx) { |
| 274 | continue; |
| 275 | } |
| 276 | } |
| 277 | |
| 278 | // slice the op if needed |
| 279 | // PERF: we can skip the slice by using the RichOp::new_slice |
| 280 | let stack_sliced_op; |
| 281 | if op.ctr_last() < start_counter { |
| 282 | continue; |
| 283 | } |
| 284 | |
| 285 | if op.counter < start_counter || op.ctr_end() > end_counter { |
| 286 | stack_sliced_op = Some(op.slice( |
| 287 | (start_counter as usize).saturating_sub(op.counter as usize), |
| 288 | op.atom_len().min((end_counter - op.counter) as usize), |
| 289 | )); |
| 290 | op = stack_sliced_op.as_ref().unwrap(); |
| 291 | } |
| 292 | |
| 293 | let vv = &mut vv.borrow_mut(); |
| 294 | vv.extend_to_include_end_id(ID::new(change.peer(), op.counter)); |
| 295 | let container = op.container; |
| 296 | let depth = oplog.arena.get_depth(container); |
| 297 | let (old_depth, calculator) = self.get_or_create_calc(container, depth); |
| 298 | // checkout use the same diff_calculator, the depth of calculator is not updated |
| 299 | // That may cause the container to be considered deleted |
| 300 | if *old_depth != depth { |
| 301 | *old_depth = depth; |
| 302 | } |
| 303 | |
| 304 | if !started_set.contains(&op.container) { |
| 305 | started_set.insert(container); |
| 306 | // A container that also has ops in the concurrent old |
| 307 | // history (a register, or the oplog would not have let |
| 308 | // us replay from `before`) must resolve its values from |
| 309 | // history instead of trusting the state's metadata. |
| 310 | let container_mode = if concurrent_containers |
| 311 | .as_ref() |
| 312 | .is_some_and(|set| set.contains(&container)) |
| 313 | { |
| 314 | DiffMode::Import |
| 315 | } else { |
| 316 | calc_mode |
| 317 | }; |
| 318 | calculator.start_tracking(oplog, &replay_base, container_mode); |
| 319 | } |
| 320 | |
| 321 | // A change whose version misses part of `before` is being |
| 322 | // applied against a source state it never saw. When the |
| 323 | // oplog proved which containers that missing history |
| 324 | // touches, only those calculators lose their op context; |
| 325 | // the others see exactly the state their ops were made in. |
| 326 | if !vv.includes_vv(before) |
| 327 | && concurrent_containers |
| 328 | .as_ref() |
| 329 | .is_none_or(|set| set.contains(&container)) |
| 330 | { |
| 331 | calculator.mark_source_not_in_op_context(); |
| 332 | } |
| 333 | |
| 334 | // A replayed op concurrent with the replay base would |
| 335 | // contradict the base's claimed criticality. |
| 336 | debug_assert!( |
| 337 | !replay_base_is_critical || vv.includes_vv(&replay_base), |
| 338 | "op {}@{} is concurrent with a replay base claimed critical", |
| 339 | op.counter, |
| 340 | change.peer(), |
| 341 | ); |
| 342 | |
| 343 | if calculator.ignores_ops_shared_by_both_versions() { |
| 344 | let op_id = ID::new(change.peer(), op.ctr_last()); |
| 345 | if before.includes_id(op_id) && after.includes_id(op_id) { |
| 346 | continue; |
| 347 | } |
| 348 | } |
| 349 | |
| 350 | if visited.contains(&op.container) { |
| 351 | // don't checkout if we have already checked out this container in this round |
| 352 | calculator.apply_change(oplog, RichOp::new_by_change(&change, op), None); |
| 353 | } else { |
| 354 | calculator.apply_change( |
| 355 | oplog, |
| 356 | RichOp::new_by_change(&change, op), |
| 357 | Some(vv), |
| 358 | ); |
| 359 | visited.insert(container); |
| 360 | } |
| 361 | } |
| 362 | } |
| 363 | |
| 364 | Some(started_set) |
| 365 | }; |
| 366 | |
| 367 | // Because we need to get correct `bring_back` value that indicates container is created during this round of diff calc, |
| 368 | // we need to iterate from parents to children. i.e. from smaller depth to larger depth. |
| 369 | let mut new_containers = FxHashSet::default(); |
| 370 | let mut container_id_to_depth = FxHashMap::default(); |
| 371 | let mut all: Vec<(Option<NonZeroU16>, ContainerIdx)> = if let Some(set) = affected_set { |
| 372 | // only visit the affected containers |
| 373 | set.into_iter() |
| 374 | .map(|x| { |
| 375 | let (depth, _) = self.calculators.get_mut(&x).unwrap(); |
| 376 | (*depth, x) |
| 377 | }) |
| 378 | .collect() |
| 379 | } else { |
| 380 | self.calculators |
| 381 | .iter_mut() |
| 382 | .map(|(x, (depth, _))| (*depth, *x)) |
| 383 | .collect() |
| 384 | }; |
| 385 | let mut ans = FxHashMap::default(); |
| 386 | let info = DiffCalcVersionInfo { |
| 387 | from_vv: before, |
| 388 | to_vv: after, |
| 389 | from_frontiers: before_frontiers, |
| 390 | to_frontiers: after_frontiers, |
| 391 | replay_base_vv: &replay_base, |
| 392 | replay_base_is_critical, |
| 393 | }; |
| 394 | while !all.is_empty() { |
| 395 | // sort by depth and lamport, ensure we iterate from top to bottom |
| 396 | all.sort_by_key(|x| x.0); |
| 397 | for (_, container_idx) in std::mem::take(&mut all) { |
| 398 | if ans.contains_key(&container_idx) { |
| 399 | continue; |
| 400 | } |
| 401 | let (depth, calc) = self.calculators.get_mut(&container_idx).unwrap(); |
| 402 | if depth.is_none() { |
| 403 | let d = oplog.arena.get_depth(container_idx); |
| 404 | if d != *depth { |
| 405 | *depth = d; |
| 406 | all.push((*depth, container_idx)); |
| 407 | continue; |
| 408 | } |
| 409 | } |
| 410 | let id = oplog.arena.idx_to_id(container_idx).unwrap(); |
| 411 | let bring_back = new_containers.remove(&id); |
| 412 | |
| 413 | info_span!("CalcDiff", ?id).in_scope(|| { |
| 414 | let (diff, diff_mode) = calc.calculate_diff(container_idx, oplog, info, |c| { |
| 415 | new_containers.insert(c.clone()); |
| 416 | container_id_to_depth |
| 417 | .insert(c.clone(), depth.and_then(|d| d.checked_add(1))); |
| 418 | oplog.arena.register_container(c); |
| 419 | }); |
| 420 | calc.finish_this_round(); |
| 421 | if !diff.is_empty() || bring_back { |
| 422 | ans.insert( |
| 423 | container_idx, |
| 424 | ( |
| 425 | *depth, |
| 426 | InternalContainerDiff { |
| 427 | idx: container_idx, |
| 428 | bring_back, |
| 429 | diff: diff.into(), |
| 430 | diff_mode, |
| 431 | kept: None, |
| 432 | }, |
| 433 | ), |
| 434 | ); |
| 435 | } |
| 436 | }); |
| 437 | } |
| 438 | } |
| 439 | |
| 440 | while !new_containers.is_empty() { |
| 441 | for id in std::mem::take(&mut new_containers) { |
| 442 | // Registration can be lazy; ensure it is registered so we can proceed |
| 443 | let idx = oplog.arena.register_container(&id); |
| 444 | if ans.contains_key(&idx) { |
| 445 | continue; |
| 446 | } |
| 447 | let depth = container_id_to_depth.remove(&id).unwrap(); |
| 448 | ans.insert( |
| 449 | idx, |
| 450 | ( |
| 451 | depth, |
| 452 | InternalContainerDiff { |
| 453 | idx, |
| 454 | bring_back: true, |
| 455 | diff: DiffVariant::None, |
| 456 | diff_mode: DiffMode::Checkout, |
| 457 | kept: None, |
| 458 | }, |
| 459 | ), |
| 460 | ); |
| 461 | } |
| 462 | } |
| 463 | |
| 464 | Ok(( |
| 465 | ans.into_values().map(|x| x.1).collect_vec(), |
| 466 | origin_diff_mode, |
| 467 | )) |
| 468 | } |
| 469 | |
| 470 | // TODO: we may remove depth info |
| 471 | pub(crate) fn get_or_create_calc( |
| 472 | &mut self, |
| 473 | idx: ContainerIdx, |
| 474 | depth: Option<NonZeroU16>, |
| 475 | ) -> &mut (Option<NonZeroU16>, ContainerDiffCalculator) { |
| 476 | self.calculators |
| 477 | .entry(idx) |
| 478 | .or_insert_with(|| match idx.get_type() { |
| 479 | crate::ContainerType::Text => ( |
| 480 | depth, |
| 481 | ContainerDiffCalculator::Richtext(RichtextDiffCalculator::new()), |
| 482 | ), |
| 483 | crate::ContainerType::Map => ( |
| 484 | depth, |
| 485 | ContainerDiffCalculator::Map(MapDiffCalculator::new(idx)), |
| 486 | ), |
| 487 | crate::ContainerType::List => ( |
| 488 | depth, |
| 489 | ContainerDiffCalculator::List(ListDiffCalculator::default()), |
| 490 | ), |
| 491 | crate::ContainerType::Tree => ( |
| 492 | depth, |
| 493 | ContainerDiffCalculator::Tree(TreeDiffCalculator::new(idx)), |
| 494 | ), |
| 495 | crate::ContainerType::Unknown(_) => ( |
| 496 | depth, |
| 497 | ContainerDiffCalculator::Unknown(unknown::UnknownDiffCalculator), |
| 498 | ), |
| 499 | crate::ContainerType::MovableList => ( |
| 500 | depth, |
| 501 | ContainerDiffCalculator::MovableList(MovableListDiffCalculator::new(idx)), |
| 502 | ), |
| 503 | #[cfg(feature = "counter")] |
| 504 | crate::ContainerType::Counter => ( |
| 505 | depth, |
| 506 | ContainerDiffCalculator::Counter(CounterDiffCalculator::new(idx)), |
| 507 | ), |
| 508 | }) |
| 509 | } |
| 510 | } |
| 511 | |
| 512 | /// DiffCalculator should track the history first before it can calculate the difference. |
| 513 | /// |
| 514 | /// So we need it to first apply all the ops between the two versions. |
| 515 | /// |
| 516 | /// NOTE: not every op between two versions are included in a certain container. |
| 517 | /// So there may be some ops that cannot be seen by the container. |
| 518 | /// |
| 519 | #[enum_dispatch] |
| 520 | pub(crate) trait DiffCalculatorTrait { |
| 521 | fn start_tracking(&mut self, oplog: &OpLog, vv: &crate::VersionVector, mode: DiffMode); |
| 522 | fn apply_change( |
| 523 | &mut self, |
| 524 | oplog: &OpLog, |
| 525 | op: crate::op::RichOp, |
| 526 | vv: Option<&crate::VersionVector>, |
| 527 | ); |
| 528 | fn calculate_diff( |
| 529 | &mut self, |
| 530 | idx: ContainerIdx, |
| 531 | oplog: &OpLog, |
| 532 | info: DiffCalcVersionInfo, |
| 533 | on_new_container: impl FnMut(&ContainerID), |
| 534 | ) -> (InternalDiff, DiffMode); |
| 535 | /// This round of diff calc is finished, we can clear the cache |
| 536 | fn finish_this_round(&mut self); |
| 537 | } |
| 538 | |
| 539 | #[cfg(test)] |
| 540 | thread_local! { |
| 541 | /// Counts full-history CRDT tracker rebuilds so tests can assert the |
| 542 | /// incremental path actually short-circuits them. Test observability |
| 543 | /// only; thread-local so concurrently running tests cannot disturb each |
| 544 | /// other's counts (diff calc runs on the importing thread). |
| 545 | pub(crate) static FULL_TRACKER_REBUILD_COUNT: std::cell::Cell<u64> = |
| 546 | const { std::cell::Cell::new(0) }; |
| 547 | } |
| 548 | |
| 549 | #[enum_dispatch(DiffCalculatorTrait)] |
| 550 | #[derive(Debug)] |
| 551 | pub(crate) enum ContainerDiffCalculator { |
| 552 | Map(MapDiffCalculator), |
| 553 | List(ListDiffCalculator), |
| 554 | Richtext(RichtextDiffCalculator), |
| 555 | Tree(TreeDiffCalculator), |
| 556 | MovableList(MovableListDiffCalculator), |
| 557 | #[cfg(feature = "counter")] |
| 558 | Counter(counter::CounterDiffCalculator), |
| 559 | Unknown(UnknownDiffCalculator), |
| 560 | } |
| 561 | |
| 562 | impl ContainerDiffCalculator { |
| 563 | /// Whether ops that both versions already contain can be skipped. |
| 564 | /// |
| 565 | /// A conservative replay base can be far below `before`, so most replayed |
| 566 | /// ops are shared by both versions. Trackers still need them as position |
| 567 | /// context, but a register (map) resolves per key from the history cache, |
| 568 | /// so a shared op can never change the diff: it only makes the calculator |
| 569 | /// look up a key that must resolve to the same value on both sides. |
| 570 | fn ignores_ops_shared_by_both_versions(&self) -> bool { |
| 571 | matches!(self, Self::Map(_)) |
| 572 | } |
| 573 | |
| 574 | fn mark_source_not_in_op_context(&mut self) { |
| 575 | match self { |
| 576 | Self::Richtext(calc) => calc.mark_source_not_in_op_context(), |
| 577 | Self::List(calc) => calc.mark_source_not_in_op_context(), |
| 578 | Self::MovableList(calc) => calc.mark_source_not_in_op_context(), |
| 579 | _ => {} |
| 580 | } |
| 581 | } |
| 582 | } |
| 583 | |
| 584 | trait RebuildOpVisitor { |
| 585 | fn visit(&mut self, vv: &VersionVector, op: RichOp<'_>); |
| 586 | } |
| 587 | |
| 588 | #[cold] |
| 589 | #[inline(never)] |
| 590 | fn replay_container_ops_from_empty( |
| 591 | idx: ContainerIdx, |
| 592 | oplog: &OpLog, |
| 593 | vv: &VersionVector, |
| 594 | visitor: &mut dyn RebuildOpVisitor, |
| 595 | ) { |
| 596 | let empty_vv = VersionVector::default(); |
| 597 | let empty_frontiers = Frontiers::default(); |
| 598 | let target_frontiers = oplog.dag.vv_to_frontiers(vv); |
| 599 | let (_, iter) = |
| 600 | oplog.iter_from_replay_base_causally(&empty_vv, &empty_frontiers, vv, &target_frontiers); |
| 601 | |
| 602 | for (change, (start_counter, end_counter), vv) in iter { |
| 603 | let iter_start = change |
| 604 | .ops |
| 605 | .binary_search_by(|op| op.ctr_last().cmp(&start_counter)) |
| 606 | .unwrap_or_else(|e| e); |
| 607 | for mut op in &change.ops.vec()[iter_start..] { |
| 608 | if op.counter >= end_counter { |
| 609 | break; |
| 610 | } |
| 611 | |
| 612 | if op.container != idx || op.ctr_last() < start_counter { |
| 613 | continue; |
| 614 | } |
| 615 | |
| 616 | let stack_sliced_op; |
| 617 | if op.counter < start_counter || op.ctr_end() > end_counter { |
| 618 | stack_sliced_op = Some(op.slice( |
| 619 | (start_counter as usize).saturating_sub(op.counter as usize), |
| 620 | op.atom_len().min((end_counter - op.counter) as usize), |
| 621 | )); |
| 622 | op = stack_sliced_op.as_ref().unwrap(); |
| 623 | } |
| 624 | |
| 625 | let vv = &mut vv.borrow_mut(); |
| 626 | vv.extend_to_include_end_id(ID::new(change.peer(), op.counter)); |
| 627 | visitor.visit(vv, RichOp::new_by_change(&change, op)); |
| 628 | } |
| 629 | } |
| 630 | } |
| 631 | |
| 632 | #[derive(Debug)] |
| 633 | pub(crate) struct MapDiffCalculator { |
| 634 | container_idx: ContainerIdx, |
| 635 | /// In `ImportGreaterUpdates`/`Linear` this holds the resolved new value per key. |
| 636 | /// |
| 637 | /// In `Checkout`/`Import` the values come from the history cache instead, so |
| 638 | /// only the key set matters (values stay `None`): a key that no op in the |
| 639 | /// replayed span writes has the same ops on both sides and therefore the |
| 640 | /// same winner, so it cannot appear in the diff. Restricting the history |
| 641 | /// cache lookup to these keys keeps map diffing proportional to the update |
| 642 | /// instead of to the size of the map. |
| 643 | changed: FxHashMap<InternalString, Option<MapValue>>, |
| 644 | current_mode: DiffMode, |
| 645 | } |
| 646 | |
| 647 | impl MapDiffCalculator { |
| 648 | pub(crate) fn new(container_idx: ContainerIdx) -> Self { |
| 649 | Self { |
| 650 | container_idx, |
| 651 | changed: Default::default(), |
| 652 | current_mode: DiffMode::Checkout, |
| 653 | } |
| 654 | } |
| 655 | } |
| 656 | |
| 657 | impl DiffCalculatorTrait for MapDiffCalculator { |
| 658 | fn start_tracking( |
| 659 | &mut self, |
| 660 | _oplog: &crate::OpLog, |
| 661 | _vv: &crate::VersionVector, |
| 662 | mode: DiffMode, |
| 663 | ) { |
| 664 | self.changed.clear(); |
| 665 | self.current_mode = mode; |
| 666 | } |
| 667 | |
| 668 | fn apply_change( |
| 669 | &mut self, |
| 670 | _oplog: &crate::OpLog, |
| 671 | op: crate::op::RichOp, |
| 672 | _vv: Option<&crate::VersionVector>, |
| 673 | ) { |
| 674 | let map = op.raw_op().content.as_map().unwrap(); |
| 675 | if matches!(self.current_mode, DiffMode::Checkout | DiffMode::Import) { |
| 676 | // The value is resolved from the history cache; only record which |
| 677 | // keys this span could have changed. |
| 678 | if !self.changed.contains_key(&map.key) { |
| 679 | self.changed.insert(map.key.clone(), None); |
| 680 | } |
| 681 | return; |
| 682 | } |
| 683 | |
| 684 | let new_value = MapValue { |
| 685 | value: map.value.clone(), |
| 686 | peer: op.peer, |
| 687 | lamp: op.lamport(), |
| 688 | }; |
| 689 | match self.changed.get(&map.key) { |
| 690 | Some(Some(old_value)) if old_value > &new_value => {} |
| 691 | _ => { |
| 692 | self.changed.insert(map.key.clone(), Some(new_value)); |
| 693 | } |
| 694 | } |
| 695 | } |
| 696 | |
| 697 | fn finish_this_round(&mut self) { |
| 698 | self.changed.clear(); |
| 699 | self.current_mode = DiffMode::Checkout; |
| 700 | } |
| 701 | |
| 702 | fn calculate_diff( |
| 703 | &mut self, |
| 704 | _idx: ContainerIdx, |
| 705 | oplog: &super::oplog::OpLog, |
| 706 | DiffCalcVersionInfo { from_vv, to_vv, .. }: DiffCalcVersionInfo, |
| 707 | mut on_new_container: impl FnMut(&ContainerID), |
| 708 | ) -> (InternalDiff, DiffMode) { |
| 709 | match self.current_mode { |
| 710 | DiffMode::Checkout | DiffMode::Import => oplog.with_history_cache(|h| { |
| 711 | h.ensure_shallow_map_seeded(self.container_idx); |
| 712 | let checkout_index = &h.get_checkout_index().map; |
| 713 | let keys = std::mem::take(&mut self.changed); |
| 714 | // Every key whose winning op differs is emitted, even when both |
| 715 | // winners carry the same value: the state keeps the winner's |
| 716 | // lamport/peer, and a shallow root state encoded from stale |
| 717 | // metadata collides with a retained op in this index and loses |
| 718 | // the root entry. The state is at `from` and already holds the |
| 719 | // `from` value, so `MapState` tells value changes from |
| 720 | // metadata-only updates in the same write, and the `from` value |
| 721 | // is never fetched here. |
| 722 | let changed = checkout_index.changed_winners_for_keys( |
| 723 | self.container_idx, |
| 724 | from_vv, |
| 725 | to_vv, |
| 726 | keys.into_keys(), |
| 727 | oplog, |
| 728 | ); |
| 729 | |
| 730 | let mut updated = |
| 731 | FxHashMap::with_capacity_and_hasher(changed.len(), Default::default()); |
| 732 | for (key, value) in changed { |
| 733 | let value = value.map(|v| { |
| 734 | // A normal container id is minted by one op, so a new |
| 735 | // winner holding a container always changes the value. |
| 736 | if let Some(LoroValue::Container(c)) = &v.value { |
| 737 | on_new_container(c); |
| 738 | } |
| 739 | |
| 740 | MapValue { |
| 741 | value: v.value, |
| 742 | lamp: v.lamport, |
| 743 | peer: v.peer, |
| 744 | } |
| 745 | }); |
| 746 | |
| 747 | updated.insert(key, value); |
| 748 | } |
| 749 | |
| 750 | (InternalDiff::Map(MapDelta { updated }), DiffMode::Checkout) |
| 751 | }), |
| 752 | DiffMode::ImportGreaterUpdates | DiffMode::Linear => { |
| 753 | let changed = std::mem::take(&mut self.changed); |
| 754 | let mode = self.current_mode; |
| 755 | // Reset this field to avoid we use `has_all` to cache the diff calc and use it next round |
| 756 | // (In the next round we need to use the checkout mode) |
| 757 | self.current_mode = DiffMode::Checkout; |
| 758 | (InternalDiff::Map(MapDelta { updated: changed }), mode) |
| 759 | } |
| 760 | } |
| 761 | } |
| 762 | } |
| 763 | |
| 764 | use rle::{HasLength as _, Sliceable}; |
| 765 | |
| 766 | #[derive(Default)] |
| 767 | pub(crate) struct ListDiffCalculator { |
| 768 | start_vv: VersionVector, |
| 769 | tracker: Box<ListTracker>, |
| 770 | source_not_in_op_context: bool, |
| 771 | } |
| 772 | |
| 773 | /// A list tracker and the values its chunks point into, replaced together. |
| 774 | #[derive(Default)] |
| 775 | struct ListTracker { |
| 776 | tracker: RichtextTracker, |
| 777 | values: TrackerValues, |
| 778 | } |
| 779 | |
| 780 | impl ListTracker { |
| 781 | /// Reseeds the tracker; the value table keeps its capacity. |
| 782 | fn reset(&mut self) { |
| 783 | self.tracker = RichtextTracker::new_with_unknown(); |
| 784 | self.values.clear(); |
| 785 | } |
| 786 | |
| 787 | #[inline(never)] |
| 788 | fn apply_op(&mut self, op: &crate::op::RichOp<'_>) { |
| 789 | match &op.op().content { |
| 790 | crate::op::InnerContent::List(l) => match l { |
| 791 | InnerListOp::Insert { slice, pos } => { |
| 792 | // Record only what the tracker has not applied yet: a |
| 793 | // checkout can replay ops the tracker already has. |
| 794 | let values = &mut self.values; |
| 795 | self.tracker |
| 796 | .insert_with(op.id_full(), *pos, slice.len(), |skip| { |
| 797 | RichtextChunk::new_text(values.push(slice.slice(skip, slice.len()))) |
| 798 | }); |
| 799 | } |
| 800 | InnerListOp::Delete(del) => { |
| 801 | self.tracker.delete( |
| 802 | op.id_start(), |
| 803 | del.id_start, |
| 804 | del.start() as usize, |
| 805 | del.atom_len(), |
| 806 | del.is_reversed(), |
| 807 | ); |
| 808 | } |
| 809 | _ => unreachable!(), |
| 810 | }, |
| 811 | _ => unreachable!(), |
| 812 | } |
| 813 | } |
| 814 | } |
| 815 | |
| 816 | impl std::ops::Deref for ListTracker { |
| 817 | type Target = RichtextTracker; |
| 818 | |
| 819 | fn deref(&self) -> &Self::Target { |
| 820 | &self.tracker |
| 821 | } |
| 822 | } |
| 823 | |
| 824 | impl std::ops::DerefMut for ListTracker { |
| 825 | fn deref_mut(&mut self) -> &mut Self::Target { |
| 826 | &mut self.tracker |
| 827 | } |
| 828 | } |
| 829 | |
| 830 | impl ListDiffCalculator { |
| 831 | /// Test-only: how many values the value table holds, to pin that |
| 832 | /// re-replayed inserts do not grow it. |
| 833 | #[cfg(test)] |
| 834 | pub(crate) fn tracked_values_len(&self) -> usize { |
| 835 | self.tracker.values.len() |
| 836 | } |
| 837 | |
| 838 | pub(crate) fn get_id_latest_pos(&self, id: ID) -> Option<crate::cursor::AbsolutePosition> { |
| 839 | self.tracker.get_target_id_latest_index_at_new_version(id) |
| 840 | } |
| 841 | |
| 842 | fn mark_source_not_in_op_context(&mut self) { |
| 843 | self.source_not_in_op_context = true; |
| 844 | } |
| 845 | |
| 846 | #[cold] |
| 847 | #[inline(never)] |
| 848 | fn build_full_tracker(idx: ContainerIdx, oplog: &OpLog, vv: &VersionVector) -> ListTracker { |
| 849 | struct ListRebuildVisitor<'a> { |
| 850 | tracker: &'a mut ListTracker, |
| 851 | } |
| 852 | |
| 853 | impl RebuildOpVisitor for ListRebuildVisitor<'_> { |
| 854 | fn visit(&mut self, vv: &VersionVector, op: RichOp<'_>) { |
| 855 | self.tracker.checkout(vv); |
| 856 | self.tracker.apply_op(&op); |
| 857 | } |
| 858 | } |
| 859 | |
| 860 | let mut tracker = ListTracker::default(); |
| 861 | let mut visitor = ListRebuildVisitor { |
| 862 | tracker: &mut tracker, |
| 863 | }; |
| 864 | replay_container_ops_from_empty(idx, oplog, vv, &mut visitor); |
| 865 | |
| 866 | tracker |
| 867 | } |
| 868 | } |
| 869 | |
| 870 | impl MovableListDiffCalculator { |
| 871 | #[cfg(test)] |
| 872 | pub(crate) fn tracked_values_len(&self) -> usize { |
| 873 | self.list.tracked_values_len() |
| 874 | } |
| 875 | |
| 876 | pub(crate) fn get_id_latest_pos(&self, id: ID) -> Option<crate::cursor::AbsolutePosition> { |
| 877 | self.list |
| 878 | .tracker |
| 879 | .get_target_id_latest_index_at_new_version(id) |
| 880 | } |
| 881 | |
| 882 | fn mark_source_not_in_op_context(&mut self) { |
| 883 | self.list.mark_source_not_in_op_context(); |
| 884 | } |
| 885 | } |
| 886 | |
| 887 | impl std::fmt::Debug for ListDiffCalculator { |
| 888 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 889 | f.debug_struct("ListDiffCalculator") |
| 890 | // .field("tracker", &self.tracker) |
| 891 | .finish() |
| 892 | } |
| 893 | } |
| 894 | |
| 895 | impl DiffCalculatorTrait for ListDiffCalculator { |
| 896 | fn start_tracking(&mut self, _oplog: &OpLog, vv: &crate::VersionVector, _mode: DiffMode) { |
| 897 | self.source_not_in_op_context = false; |
| 898 | if !vv.includes_vv(&self.start_vv) || !self.tracker.all_vv().includes_vv(vv) { |
| 899 | self.tracker.reset(); |
| 900 | self.start_vv = vv.clone(); |
| 901 | } |
| 902 | |
| 903 | self.tracker.checkout(vv); |
| 904 | } |
| 905 | |
| 906 | fn apply_change( |
| 907 | &mut self, |
| 908 | _oplog: &OpLog, |
| 909 | op: crate::op::RichOp, |
| 910 | vv: Option<&crate::VersionVector>, |
| 911 | ) { |
| 912 | if let Some(vv) = vv { |
| 913 | self.tracker.checkout(vv); |
| 914 | } |
| 915 | |
| 916 | self.tracker.apply_op(&op); |
| 917 | } |
| 918 | |
| 919 | fn finish_this_round(&mut self) {} |
| 920 | |
| 921 | fn calculate_diff( |
| 922 | &mut self, |
| 923 | idx: ContainerIdx, |
| 924 | oplog: &OpLog, |
| 925 | info: DiffCalcVersionInfo, |
| 926 | mut on_new_container: impl FnMut(&ContainerID), |
| 927 | ) -> (InternalDiff, DiffMode) { |
| 928 | let mut delta = Delta::new(); |
| 929 | let (mut retreat, _) = info.from_vv.diff_iter(info.to_vv); |
| 930 | let has_retreat = retreat.next().is_some(); |
| 931 | let should_rebuild = matches!(idx.get_type(), crate::ContainerType::List) && { |
| 932 | // A certified-critical replay base can be trusted for the same |
| 933 | // reason as in richtext (see the soundness comment in |
| 934 | // `RichtextDiffCalculator::calculate_diff`) — with less |
| 935 | // machinery, as list trackers have no style anchors. The critical |
| 936 | // arm additionally requires a non-shallow doc, which preserves |
| 937 | // the old behavior exactly: list trackers have no shallow-root |
| 938 | // seeding, and the pre-existing `base == from` arm never had a |
| 939 | // shallow term. `has_retreat` stays load-bearing: a retreat is |
| 940 | // the only way a diff could emit the opaque below-base span. |
| 941 | let base_is_trustworthy = (info.replay_base_is_critical |
| 942 | && oplog.shallow_since_vv().is_empty()) |
| 943 | || (info.replay_base_vv == info.from_vv && !self.source_not_in_op_context); |
| 944 | has_retreat || !base_is_trustworthy |
| 945 | }; |
| 946 | let diff_items = if should_rebuild { |
| 947 | #[cfg(test)] |
| 948 | FULL_TRACKER_REBUILD_COUNT.with(|c| c.set(c.get() + 1)); |
| 949 | let mut merged = info.from_vv.clone(); |
| 950 | merged.merge(info.to_vv); |
| 951 | let mut full_tracker = Self::build_full_tracker(idx, oplog, &merged); |
| 952 | let diff_items = full_tracker.diff(info.from_vv, info.to_vv).collect_vec(); |
| 953 | *self.tracker = full_tracker; |
| 954 | diff_items |
| 955 | } else { |
| 956 | self.tracker.diff(info.from_vv, info.to_vv).collect_vec() |
| 957 | }; |
| 958 | |
| 959 | for item in diff_items { |
| 960 | match item { |
| 961 | CrdtRopeDelta::Retain(len) => { |
| 962 | delta = delta.retain(len); |
| 963 | } |
| 964 | CrdtRopeDelta::Insert { |
| 965 | chunk: value, |
| 966 | id, |
| 967 | lamport, |
| 968 | } => match value.value() { |
| 969 | RichtextChunkValue::Text(range) => { |
| 970 | let lamport = lamport.unwrap(); |
| 971 | self.tracker.values.for_each_slice(range, |offset, values| { |
| 972 | for v in values.as_slice() { |
| 973 | if let LoroValue::Container(c) = v { |
| 974 | on_new_container(c); |
| 975 | } |
| 976 | } |
| 977 | delta = std::mem::take(&mut delta).insert(SliceWithId { |
| 978 | values: Either::Left(values), |
| 979 | id: IdFull::new( |
| 980 | id.peer, |
| 981 | id.counter + offset as Counter, |
| 982 | lamport + offset as Lamport, |
| 983 | ), |
| 984 | elem_id: None, |
| 985 | }); |
| 986 | }); |
| 987 | } |
| 988 | RichtextChunkValue::StyleAnchor { .. } => unreachable!(), |
| 989 | RichtextChunkValue::Unknown(len) => { |
| 990 | delta = handle_unknown(idx, id, oplog, len, &mut on_new_container, delta); |
| 991 | } |
| 992 | RichtextChunkValue::MoveAnchor => { |
| 993 | delta = handle_unknown(idx, id, oplog, 1, &mut on_new_container, delta); |
| 994 | } |
| 995 | }, |
| 996 | CrdtRopeDelta::Delete(len) => { |
| 997 | delta = delta.delete(len); |
| 998 | } |
| 999 | } |
| 1000 | } |
| 1001 | |
| 1002 | /// Handle span with unknown content when calculating diff |
| 1003 | /// |
| 1004 | /// We can lookup the content of the span by the id in the oplog |
| 1005 | fn handle_unknown( |
| 1006 | idx: ContainerIdx, |
| 1007 | mut id: ID, |
| 1008 | oplog: &OpLog, |
| 1009 | len: u32, |
| 1010 | on_new_container: &mut dyn FnMut(&ContainerID), |
| 1011 | mut delta: Delta<SliceWithId>, |
| 1012 | ) -> Delta<SliceWithId> { |
| 1013 | // assert not unknown id |
| 1014 | assert_ne!(id.peer, PeerID::MAX); |
| 1015 | let mut acc_len = 0; |
| 1016 | let end = id.counter + len as Counter; |
| 1017 | let shallow_root = oplog.shallow_since_vv().get(&id.peer).copied().unwrap_or(0); |
| 1018 | if id.counter < shallow_root { |
| 1019 | // need to find the content between id.counter ~ target_end in gc state |
| 1020 | let target_end = shallow_root.min(end); |
| 1021 | delta = oplog.with_history_cache(|h| { |
| 1022 | let chunks = |
| 1023 | h.find_list_chunks_in(idx, IdSpan::new(id.peer, id.counter, target_end)); |
| 1024 | for c in chunks { |
| 1025 | acc_len += c.length(); |
| 1026 | match &c.values { |
| 1027 | Either::Left(_) => unreachable!(), |
| 1028 | Either::Right(r) => { |
| 1029 | if let LoroValue::Container(c) = r { |
| 1030 | on_new_container(c) |
| 1031 | } |
| 1032 | } |
| 1033 | } |
| 1034 | delta = delta.insert(c); |
| 1035 | } |
| 1036 | |
| 1037 | delta |
| 1038 | }); |
| 1039 | id.counter = shallow_root; |
| 1040 | } |
| 1041 | |
| 1042 | if id.counter < end { |
| 1043 | for rich_op in oplog.iter_ops(IdSpan::new(id.peer, id.counter, end)) { |
| 1044 | acc_len += rich_op.content_len(); |
| 1045 | let op = rich_op.op(); |
| 1046 | let lamport = rich_op.lamport(); |
| 1047 | |
| 1048 | if let InnerListOp::Insert { slice, pos: _ } = op.content.as_list().unwrap() { |
| 1049 | for v in slice.as_slice() { |
| 1050 | if let LoroValue::Container(c) = v { |
| 1051 | (on_new_container)(c); |
| 1052 | } |
| 1053 | } |
| 1054 | |
| 1055 | delta = delta.insert(SliceWithId { |
| 1056 | values: Either::Left(slice.clone()), |
| 1057 | id: IdFull::new(id.peer, op.counter, lamport), |
| 1058 | elem_id: None, |
| 1059 | }); |
| 1060 | } else if let InnerListOp::Move { elem_id, .. } = op.content.as_list().unwrap() |
| 1061 | { |
| 1062 | delta = delta.insert(SliceWithId { |
| 1063 | // We do NOT need an actual value range, |
| 1064 | // movable list container will only use the id info |
| 1065 | values: Either::Right(LoroValue::Null), |
| 1066 | id: IdFull::new(id.peer, op.counter, lamport), |
| 1067 | elem_id: Some(elem_id.compact()), |
| 1068 | }); |
| 1069 | } |
| 1070 | } |
| 1071 | } |
| 1072 | |
| 1073 | debug_assert_eq!(acc_len, len as usize); |
| 1074 | delta |
| 1075 | } |
| 1076 | |
| 1077 | (InternalDiff::ListRaw(delta), DiffMode::Checkout) |
| 1078 | } |
| 1079 | } |
| 1080 | |
| 1081 | #[derive(Debug)] |
| 1082 | pub(crate) struct RichtextDiffCalculator { |
| 1083 | mode: Box<RichtextCalcMode>, |
| 1084 | } |
| 1085 | |
| 1086 | #[derive(Debug)] |
| 1087 | enum RichtextCalcMode { |
| 1088 | Crdt { |
| 1089 | tracker: Box<RichtextTracker>, |
| 1090 | /// (op, end_pos) |
| 1091 | styles: Vec<(StyleOp, usize)>, |
| 1092 | /// The text the tracker's text chunks point into. |
| 1093 | texts: TrackerTexts, |
| 1094 | start_vv: VersionVector, |
| 1095 | source_not_in_op_context: bool, |
| 1096 | shallow_root_seeded: bool, |
| 1097 | }, |
| 1098 | Linear { |
| 1099 | diff: DeltaRope<RichtextStateChunk, ()>, |
| 1100 | last_style_start: Option<(Arc<StyleOp>, u32)>, |
| 1101 | }, |
| 1102 | } |
| 1103 | |
| 1104 | impl RichtextDiffCalculator { |
| 1105 | pub fn new() -> Self { |
| 1106 | Self { |
| 1107 | mode: Box::new(RichtextCalcMode::Crdt { |
| 1108 | tracker: Box::new(RichtextTracker::new_with_unknown()), |
| 1109 | styles: Vec::new(), |
| 1110 | texts: TrackerTexts::default(), |
| 1111 | start_vv: VersionVector::new(), |
| 1112 | source_not_in_op_context: false, |
| 1113 | shallow_root_seeded: false, |
| 1114 | }), |
| 1115 | } |
| 1116 | } |
| 1117 | |
| 1118 | fn mark_source_not_in_op_context(&mut self) { |
| 1119 | if let RichtextCalcMode::Crdt { |
| 1120 | source_not_in_op_context, |
| 1121 | .. |
| 1122 | } = &mut *self.mode |
| 1123 | { |
| 1124 | *source_not_in_op_context = true; |
| 1125 | } |
| 1126 | } |
| 1127 | |
| 1128 | /// Test-only: how many chars the text table holds, to pin that |
| 1129 | /// re-replayed inserts do not grow it. |
| 1130 | #[cfg(test)] |
| 1131 | pub(crate) fn tracked_text_len(&self) -> usize { |
| 1132 | match &*self.mode { |
| 1133 | RichtextCalcMode::Crdt { texts, .. } => texts.len(), |
| 1134 | RichtextCalcMode::Linear { .. } => unreachable!(), |
| 1135 | } |
| 1136 | } |
| 1137 | |
| 1138 | /// Test-only: the ids of the style table's entries, to pin that |
| 1139 | /// re-replayed style ops do not grow the table. |
| 1140 | #[cfg(test)] |
| 1141 | pub(crate) fn tracked_style_ids(&self) -> Vec<ID> { |
| 1142 | match &*self.mode { |
| 1143 | RichtextCalcMode::Crdt { styles, .. } => { |
| 1144 | styles.iter().map(|(s, _)| ID::new(s.peer, s.cnt)).collect() |
| 1145 | } |
| 1146 | RichtextCalcMode::Linear { .. } => unreachable!(), |
| 1147 | } |
| 1148 | } |
| 1149 | |
| 1150 | fn style_for_end_anchor(oplog: &OpLog, op: &RichOp) -> Option<(StyleOp, usize)> { |
| 1151 | let style_start_id = op.id().inc(-1); |
| 1152 | if let Some(start_op) = oplog.get_op_that_includes(style_start_id) { |
| 1153 | let InnerListOp::StyleStart { |
| 1154 | start: _, |
| 1155 | end, |
| 1156 | key, |
| 1157 | value, |
| 1158 | info, |
| 1159 | } = start_op.content.as_list().unwrap() |
| 1160 | else { |
| 1161 | unreachable!() |
| 1162 | }; |
| 1163 | |
| 1164 | Some(( |
| 1165 | StyleOp { |
| 1166 | lamport: start_op.lamport(), |
| 1167 | peer: style_start_id.peer, |
| 1168 | cnt: style_start_id.counter, |
| 1169 | key: key.clone(), |
| 1170 | value: value.clone(), |
| 1171 | info: *info, |
| 1172 | }, |
| 1173 | *end as usize, |
| 1174 | )) |
| 1175 | } else { |
| 1176 | oplog.with_history_cache(|history_cache| { |
| 1177 | history_cache |
| 1178 | .find_text_style_end_in_shallow_root(op.raw_op().container, style_start_id) |
| 1179 | }) |
| 1180 | } |
| 1181 | } |
| 1182 | |
| 1183 | fn shallow_delete_range_matches_tracker( |
| 1184 | tracker: &RichtextTracker, |
| 1185 | target_start: ID, |
| 1186 | pos: usize, |
| 1187 | len: usize, |
| 1188 | ) -> bool { |
| 1189 | let mut remaining = len; |
| 1190 | let mut pos = pos; |
| 1191 | let mut expected = target_start; |
| 1192 | while remaining > 0 { |
| 1193 | let Some((real_id, available)) = tracker.active_real_span_at(pos) else { |
| 1194 | return false; |
| 1195 | }; |
| 1196 | |
| 1197 | if real_id.peer != expected.peer || real_id.counter != expected.counter { |
| 1198 | return false; |
| 1199 | } |
| 1200 | |
| 1201 | let take = remaining.min(available); |
| 1202 | expected = expected.inc(take as Counter); |
| 1203 | pos += take; |
| 1204 | remaining -= take; |
| 1205 | } |
| 1206 | |
| 1207 | true |
| 1208 | } |
| 1209 | |
| 1210 | fn shallow_clamped_tracker_pos(oplog: &OpLog, tracker: &RichtextTracker, pos: usize) -> usize { |
| 1211 | if oplog.shallow_since_vv().is_empty() { |
| 1212 | pos |
| 1213 | } else { |
| 1214 | pos.min(tracker.len()) |
| 1215 | } |
| 1216 | } |
| 1217 | |
| 1218 | /// This should be called after calc_diff |
| 1219 | /// |
| 1220 | /// TODO: Refactor, this can be simplified |
| 1221 | pub fn get_id_latest_pos(&self, id: ID) -> Option<AbsolutePosition> { |
| 1222 | match &*self.mode { |
| 1223 | RichtextCalcMode::Crdt { tracker, .. } => { |
| 1224 | tracker.get_target_id_latest_index_at_new_version(id) |
| 1225 | } |
| 1226 | RichtextCalcMode::Linear { .. } => unreachable!(), |
| 1227 | } |
| 1228 | } |
| 1229 | |
| 1230 | fn apply_crdt_op_to_tracker( |
| 1231 | oplog: &OpLog, |
| 1232 | tracker: &mut RichtextTracker, |
| 1233 | styles: &mut Vec<(StyleOp, usize)>, |
| 1234 | texts: &mut TrackerTexts, |
| 1235 | op: RichOp, |
| 1236 | ) { |
| 1237 | match &op.raw_op().content { |
| 1238 | crate::op::InnerContent::List(l) => match l { |
| 1239 | InnerListOp::Insert { .. } | InnerListOp::Move { .. } | InnerListOp::Set { .. } => { |
| 1240 | unreachable!() |
| 1241 | } |
| 1242 | InnerListOp::InsertText { |
| 1243 | slice, |
| 1244 | unicode_len: len, |
| 1245 | pos, |
| 1246 | } => { |
| 1247 | let pos = Self::shallow_clamped_tracker_pos(oplog, tracker, *pos as usize); |
| 1248 | // Record only what the tracker has not applied yet: a |
| 1249 | // checkout can replay ops the tracker already has. |
| 1250 | tracker.insert_with(op.id_full(), pos, *len as usize, |skip| { |
| 1251 | RichtextChunk::new_text(texts.push_from(slice, *len, skip)) |
| 1252 | }); |
| 1253 | } |
| 1254 | InnerListOp::Delete(del) => { |
| 1255 | let is_shallow = !oplog.shallow_since_vv().is_empty(); |
| 1256 | let pos = del.start() as usize; |
| 1257 | if is_shallow |
| 1258 | && !Self::shallow_delete_range_matches_tracker( |
| 1259 | tracker, |
| 1260 | del.id_start, |
| 1261 | pos, |
| 1262 | del.atom_len(), |
| 1263 | ) |
| 1264 | { |
| 1265 | let atom_len = del.atom_len(); |
| 1266 | let mut segments = |
| 1267 | tracker.active_segments_of_real_id_span(del.id_start, atom_len); |
| 1268 | if segments.is_empty() { |
| 1269 | return; |
| 1270 | } |
| 1271 | |
| 1272 | segments.sort_unstable_by_key(|(_, pos, _)| *pos); |
| 1273 | if del.is_reversed() { |
| 1274 | for (target_id, pos, len) in segments.into_iter().rev() { |
| 1275 | let target_offset = |
| 1276 | (target_id.counter - del.id_start.counter) as usize; |
| 1277 | debug_assert!(target_offset + len <= atom_len); |
| 1278 | let op_offset = atom_len - target_offset - len; |
| 1279 | tracker.delete( |
| 1280 | op.id_start().inc(op_offset as Counter), |
| 1281 | target_id, |
| 1282 | pos, |
| 1283 | len, |
| 1284 | true, |
| 1285 | ); |
| 1286 | } |
| 1287 | } else { |
| 1288 | let mut deleted_before = 0; |
| 1289 | for (target_id, pos, len) in segments { |
| 1290 | let target_offset = |
| 1291 | (target_id.counter - del.id_start.counter) as usize; |
| 1292 | debug_assert!(pos >= deleted_before); |
| 1293 | tracker.delete( |
| 1294 | op.id_start().inc(target_offset as Counter), |
| 1295 | target_id, |
| 1296 | pos.saturating_sub(deleted_before), |
| 1297 | len, |
| 1298 | false, |
| 1299 | ); |
| 1300 | deleted_before += len; |
| 1301 | } |
| 1302 | } |
| 1303 | |
| 1304 | return; |
| 1305 | } |
| 1306 | |
| 1307 | tracker.delete( |
| 1308 | op.id_start(), |
| 1309 | del.id_start, |
| 1310 | pos, |
| 1311 | del.atom_len(), |
| 1312 | del.is_reversed(), |
| 1313 | ); |
| 1314 | } |
| 1315 | InnerListOp::StyleStart { |
| 1316 | start, |
| 1317 | end, |
| 1318 | key, |
| 1319 | info, |
| 1320 | value, |
| 1321 | } => { |
| 1322 | debug_assert!(start < end, "start: {}, end: {}", start, end); |
| 1323 | // A persisted tracker replays ops it has already |
| 1324 | // applied whenever the replay base sits below the |
| 1325 | // version the tracker reached on an earlier round. The |
| 1326 | // tracker itself skips those inserts (`skip_applied`), |
| 1327 | // so pushing again would only grow the table with an |
| 1328 | // unreferenced duplicate; reuse the entry pushed the |
| 1329 | // first time instead. All entries for one op id are |
| 1330 | // content-equal: seeded entries (whose position slot is |
| 1331 | // not the op's `end` field) only cover ops below the |
| 1332 | // shallow root, which are trimmed from the oplog and |
| 1333 | // never replayed here. StyleStart is a single atom, so |
| 1334 | // applied-vv membership is exact. |
| 1335 | let id = op.id_start(); |
| 1336 | let existing_style_id = if tracker.all_vv().includes_id(id) { |
| 1337 | styles |
| 1338 | .iter() |
| 1339 | .rev() |
| 1340 | .position(|(s, _)| s.peer == id.peer && s.cnt == id.counter) |
| 1341 | .map(|pos| styles.len() - pos - 1) |
| 1342 | } else { |
| 1343 | None |
| 1344 | }; |
| 1345 | let style_id = match existing_style_id { |
| 1346 | Some(style_id) => style_id, |
| 1347 | None => { |
| 1348 | styles.push(( |
| 1349 | StyleOp { |
| 1350 | lamport: op.lamport(), |
| 1351 | peer: id.peer, |
| 1352 | cnt: id.counter, |
| 1353 | key: key.clone(), |
| 1354 | value: value.clone(), |
| 1355 | info: *info, |
| 1356 | }, |
| 1357 | *end as usize, |
| 1358 | )); |
| 1359 | styles.len() - 1 |
| 1360 | } |
| 1361 | }; |
| 1362 | let start = Self::shallow_clamped_tracker_pos(oplog, tracker, *start as usize); |
| 1363 | tracker.insert( |
| 1364 | op.id_full(), |
| 1365 | start, |
| 1366 | RichtextChunk::new_style_anchor(style_id as u32, AnchorType::Start), |
| 1367 | ); |
| 1368 | } |
| 1369 | InnerListOp::StyleEnd => { |
| 1370 | let id = op.id(); |
| 1371 | if let Some(pos) = styles |
| 1372 | .iter() |
| 1373 | .rev() |
| 1374 | .position(|(op, _pos)| op.peer == id.peer && op.cnt == id.counter - 1) |
| 1375 | { |
| 1376 | let style_id = styles.len() - pos - 1; |
| 1377 | let (_start_op, end_pos) = &styles[style_id]; |
| 1378 | tracker.insert( |
| 1379 | op.id_full(), |
| 1380 | // need to shift 1 because we insert the start style anchor before this pos |
| 1381 | (*end_pos + 1).min(tracker.len()), |
| 1382 | RichtextChunk::new_style_anchor(style_id as u32, AnchorType::End), |
| 1383 | ); |
| 1384 | } else { |
| 1385 | let Some((style, end)) = Self::style_for_end_anchor(oplog, &op) else { |
| 1386 | panic!("Unhandled checkout case") |
| 1387 | }; |
| 1388 | styles.push((style, end)); |
| 1389 | let style_id = styles.len() - 1; |
| 1390 | tracker.insert( |
| 1391 | op.id_full(), |
| 1392 | // need to shift 1 because we insert the start style anchor before this pos |
| 1393 | (end + 1).min(tracker.len()), |
| 1394 | RichtextChunk::new_style_anchor(style_id as u32, AnchorType::End), |
| 1395 | ); |
| 1396 | } |
| 1397 | } |
| 1398 | }, |
| 1399 | _ => unreachable!(), |
| 1400 | } |
| 1401 | } |
| 1402 | |
| 1403 | #[cold] |
| 1404 | #[inline(never)] |
| 1405 | fn seed_tracker_from_shallow_root( |
| 1406 | idx: ContainerIdx, |
| 1407 | oplog: &OpLog, |
| 1408 | tracker: &mut RichtextTracker, |
| 1409 | styles: &mut Vec<(StyleOp, usize)>, |
| 1410 | vv: &VersionVector, |
| 1411 | ) { |
| 1412 | if oplog.shallow_since_vv().is_empty() { |
| 1413 | return; |
| 1414 | } |
| 1415 | |
| 1416 | *tracker = RichtextTracker::new_empty(); |
| 1417 | styles.clear(); |
| 1418 | let shallow_root_vv = oplog |
| 1419 | .dag |
| 1420 | .frontiers_to_vv(oplog.shallow_since_frontiers()) |
| 1421 | .unwrap_or_else(|| oplog.shallow_since_vv().to_vv()); |
| 1422 | let seed_vv = if vv.includes_vv(&shallow_root_vv) { |
| 1423 | &shallow_root_vv |
| 1424 | } else { |
| 1425 | vv |
| 1426 | }; |
| 1427 | |
| 1428 | #[derive(Debug, Clone, Copy)] |
| 1429 | struct SeedItem { |
| 1430 | order: usize, |
| 1431 | id: IdFull, |
| 1432 | content: RichtextChunk, |
| 1433 | } |
| 1434 | |
| 1435 | struct Fenwick { |
| 1436 | tree: Vec<usize>, |
| 1437 | } |
| 1438 | |
| 1439 | impl Fenwick { |
| 1440 | fn new(len: usize) -> Self { |
| 1441 | Self { |
| 1442 | tree: vec![0; len + 1], |
| 1443 | } |
| 1444 | } |
| 1445 | |
| 1446 | fn add(&mut self, mut index: usize, value: usize) { |
| 1447 | index += 1; |
| 1448 | while index < self.tree.len() { |
| 1449 | self.tree[index] += value; |
| 1450 | index += index & index.wrapping_neg(); |
| 1451 | } |
| 1452 | } |
| 1453 | |
| 1454 | fn prefix_sum(&self, mut end: usize) -> usize { |
| 1455 | let mut sum = 0; |
| 1456 | while end > 0 { |
| 1457 | sum += self.tree[end]; |
| 1458 | end -= end & end.wrapping_neg(); |
| 1459 | } |
| 1460 | |
| 1461 | sum |
| 1462 | } |
| 1463 | } |
| 1464 | |
| 1465 | let chunks = oplog.with_history_cache(|h| h.find_text_chunks_in_shallow_root_order(idx)); |
| 1466 | let mut pos = 0; |
| 1467 | let mut seed_items = Vec::new(); |
| 1468 | let mut style_id_to_index = FxHashMap::default(); |
| 1469 | for chunk in chunks { |
| 1470 | match chunk { |
| 1471 | RichtextStateChunk::Text(text) => { |
| 1472 | let id = text.id_full(); |
| 1473 | let vv_end = seed_vv.get(&id.peer).copied().unwrap_or(0); |
| 1474 | if vv_end <= id.counter { |
| 1475 | continue; |
| 1476 | } |
| 1477 | |
| 1478 | let end = vv_end.min(id.counter + text.unicode_len() as Counter); |
| 1479 | let len = (end - id.counter) as usize; |
| 1480 | if len == 0 { |
| 1481 | continue; |
| 1482 | } |
| 1483 | |
| 1484 | seed_items.push(SeedItem { |
| 1485 | order: seed_items.len(), |
| 1486 | id, |
| 1487 | content: RichtextChunk::new_unknown(len as u32), |
| 1488 | }); |
| 1489 | pos += len; |
| 1490 | } |
| 1491 | RichtextStateChunk::Style { style, anchor_type } => { |
| 1492 | let id = match anchor_type { |
| 1493 | AnchorType::Start => style.id(), |
| 1494 | AnchorType::End => style.id().inc(1), |
| 1495 | }; |
| 1496 | if !seed_vv.includes_id(id) { |
| 1497 | continue; |
| 1498 | } |
| 1499 | |
| 1500 | let style_id = if let Some(id) = style_id_to_index.get(&style.id()) { |
| 1501 | *id |
| 1502 | } else { |
| 1503 | let id = styles.len(); |
| 1504 | styles.push((style.as_ref().clone(), pos)); |
| 1505 | style_id_to_index.insert(style.id(), id); |
| 1506 | id |
| 1507 | }; |
| 1508 | |
| 1509 | if anchor_type == AnchorType::End { |
| 1510 | styles[style_id].1 = pos.saturating_sub(1); |
| 1511 | } |
| 1512 | |
| 1513 | seed_items.push(SeedItem { |
| 1514 | order: seed_items.len(), |
| 1515 | id: IdFull::new( |
| 1516 | id.peer, |
| 1517 | id.counter, |
| 1518 | style.lamport + (id.counter - style.cnt) as u32, |
| 1519 | ), |
| 1520 | content: RichtextChunk::new_style_anchor(style_id as u32, anchor_type), |
| 1521 | }); |
| 1522 | pos += 1; |
| 1523 | } |
| 1524 | } |
| 1525 | } |
| 1526 | |
| 1527 | seed_items.sort_unstable_by_key(|item| (item.id.peer, item.id.counter)); |
| 1528 | let mut seen_end_by_peer: FxHashMap<PeerID, Counter> = FxHashMap::default(); |
| 1529 | let mut normalized_items = Vec::with_capacity(seed_items.len()); |
| 1530 | for mut item in seed_items { |
| 1531 | let end = item.id.counter + item.content.len() as Counter; |
| 1532 | let seen_end = seen_end_by_peer.entry(item.id.peer).or_default(); |
| 1533 | if end <= *seen_end { |
| 1534 | continue; |
| 1535 | } |
| 1536 | |
| 1537 | if item.id.counter < *seen_end { |
| 1538 | let skip = (*seen_end - item.id.counter) as usize; |
| 1539 | item.id = item.id.inc(skip as Counter); |
| 1540 | item.content = item.content.slice(skip..item.content.len()); |
| 1541 | } |
| 1542 | |
| 1543 | *seen_end = end; |
| 1544 | normalized_items.push(item); |
| 1545 | } |
| 1546 | |
| 1547 | let seed_items = normalized_items; |
| 1548 | let fenwick_len = seed_items |
| 1549 | .iter() |
| 1550 | .map(|item| item.order) |
| 1551 | .max() |
| 1552 | .map_or(0, |order| order + 1); |
| 1553 | let mut inserted = Fenwick::new(fenwick_len); |
| 1554 | for item in seed_items { |
| 1555 | let pos = inserted.prefix_sum(item.order); |
| 1556 | tracker.insert_seeded(pos, item.content, item.id); |
| 1557 | inserted.add(item.order, item.content.len()); |
| 1558 | } |
| 1559 | |
| 1560 | tracker.mark_shallow_root_applied(seed_vv); |
| 1561 | } |
| 1562 | |
| 1563 | #[cold] |
| 1564 | #[inline(never)] |
| 1565 | fn build_full_crdt_tracker( |
| 1566 | idx: ContainerIdx, |
| 1567 | oplog: &OpLog, |
| 1568 | vv: &VersionVector, |
| 1569 | ) -> (RichtextTracker, Vec<(StyleOp, usize)>, TrackerTexts) { |
| 1570 | struct RichtextRebuildVisitor<'a> { |
| 1571 | oplog: &'a OpLog, |
| 1572 | tracker: &'a mut RichtextTracker, |
| 1573 | styles: &'a mut Vec<(StyleOp, usize)>, |
| 1574 | texts: &'a mut TrackerTexts, |
| 1575 | } |
| 1576 | |
| 1577 | impl RebuildOpVisitor for RichtextRebuildVisitor<'_> { |
| 1578 | fn visit(&mut self, vv: &VersionVector, op: RichOp<'_>) { |
| 1579 | self.tracker.checkout(vv); |
| 1580 | RichtextDiffCalculator::apply_crdt_op_to_tracker( |
| 1581 | self.oplog, |
| 1582 | self.tracker, |
| 1583 | self.styles, |
| 1584 | self.texts, |
| 1585 | op, |
| 1586 | ); |
| 1587 | } |
| 1588 | } |
| 1589 | |
| 1590 | let mut tracker = RichtextTracker::new_with_unknown(); |
| 1591 | let mut styles = Vec::new(); |
| 1592 | let mut texts = TrackerTexts::default(); |
| 1593 | if !oplog.shallow_since_vv().is_empty() { |
| 1594 | Self::seed_tracker_from_shallow_root(idx, oplog, &mut tracker, &mut styles, vv); |
| 1595 | } |
| 1596 | |
| 1597 | let mut visitor = RichtextRebuildVisitor { |
| 1598 | oplog, |
| 1599 | tracker: &mut tracker, |
| 1600 | styles: &mut styles, |
| 1601 | texts: &mut texts, |
| 1602 | }; |
| 1603 | replay_container_ops_from_empty(idx, oplog, vv, &mut visitor); |
| 1604 | |
| 1605 | (tracker, styles, texts) |
| 1606 | } |
| 1607 | } |
| 1608 | |
| 1609 | impl DiffCalculatorTrait for RichtextDiffCalculator { |
| 1610 | fn start_tracking( |
| 1611 | &mut self, |
| 1612 | _oplog: &super::oplog::OpLog, |
| 1613 | vv: &crate::VersionVector, |
| 1614 | mode: DiffMode, |
| 1615 | ) { |
| 1616 | match mode { |
| 1617 | DiffMode::Linear => { |
| 1618 | *self.mode = RichtextCalcMode::Linear { |
| 1619 | diff: DeltaRope::new(), |
| 1620 | last_style_start: None, |
| 1621 | }; |
| 1622 | } |
| 1623 | _ => { |
| 1624 | if !matches!(&*self.mode, RichtextCalcMode::Crdt { .. }) { |
| 1625 | unreachable!(); |
| 1626 | } |
| 1627 | } |
| 1628 | } |
| 1629 | |
| 1630 | match &mut *self.mode { |
| 1631 | RichtextCalcMode::Crdt { |
| 1632 | tracker, |
| 1633 | styles, |
| 1634 | texts, |
| 1635 | start_vv, |
| 1636 | source_not_in_op_context, |
| 1637 | shallow_root_seeded, |
| 1638 | } => { |
| 1639 | *source_not_in_op_context = false; |
| 1640 | if !vv.includes_vv(start_vv) || !tracker.all_vv().includes_vv(vv) { |
| 1641 | **tracker = RichtextTracker::new_with_unknown(); |
| 1642 | styles.clear(); |
| 1643 | texts.clear(); |
| 1644 | *start_vv = vv.clone(); |
| 1645 | *shallow_root_seeded = false; |
| 1646 | } |
| 1647 | |
| 1648 | tracker.checkout(vv); |
| 1649 | } |
| 1650 | RichtextCalcMode::Linear { .. } => {} |
| 1651 | } |
| 1652 | } |
| 1653 | |
| 1654 | fn apply_change( |
| 1655 | &mut self, |
| 1656 | oplog: &super::oplog::OpLog, |
| 1657 | op: crate::op::RichOp, |
| 1658 | vv: Option<&crate::VersionVector>, |
| 1659 | ) { |
| 1660 | match &mut *self.mode { |
| 1661 | RichtextCalcMode::Linear { |
| 1662 | diff, |
| 1663 | last_style_start, |
| 1664 | } => match &op.raw_op().content { |
| 1665 | crate::op::InnerContent::List(l) => match l { |
| 1666 | InnerListOp::Insert { .. } |
| 1667 | | InnerListOp::Move { .. } |
| 1668 | | InnerListOp::Set { .. } => { |
| 1669 | unreachable!() |
| 1670 | } |
| 1671 | InnerListOp::InsertText { slice, pos, .. } => { |
| 1672 | diff.insert_value( |
| 1673 | *pos as usize, |
| 1674 | RichtextStateChunk::new_text(slice.clone(), op.id_full()), |
| 1675 | (), |
| 1676 | ); |
| 1677 | } |
| 1678 | InnerListOp::Delete(del) => { |
| 1679 | diff.delete(del.start() as usize, del.atom_len()); |
| 1680 | } |
| 1681 | InnerListOp::StyleStart { |
| 1682 | start, |
| 1683 | end, |
| 1684 | key, |
| 1685 | info, |
| 1686 | value, |
| 1687 | } => { |
| 1688 | debug_assert!(start < end, "start: {}, end: {}", start, end); |
| 1689 | let style_op = Arc::new(StyleOp { |
| 1690 | lamport: op.lamport(), |
| 1691 | peer: op.peer, |
| 1692 | cnt: op.id_start().counter, |
| 1693 | key: key.clone(), |
| 1694 | value: value.clone(), |
| 1695 | info: *info, |
| 1696 | }); |
| 1697 | |
| 1698 | *last_style_start = Some((style_op.clone(), *end)); |
| 1699 | diff.insert_value( |
| 1700 | *start as usize, |
| 1701 | RichtextStateChunk::new_style(style_op, AnchorType::Start), |
| 1702 | (), |
| 1703 | ); |
| 1704 | } |
| 1705 | InnerListOp::StyleEnd => { |
| 1706 | let (style_op, pos) = match last_style_start.take() { |
| 1707 | Some((style_op, pos)) => (style_op, pos), |
| 1708 | None => { |
| 1709 | let Some((style_op, pos)) = Self::style_for_end_anchor(oplog, &op) |
| 1710 | else { |
| 1711 | panic!("Unhandled checkout case") |
| 1712 | }; |
| 1713 | |
| 1714 | (Arc::new(style_op), pos as u32) |
| 1715 | } |
| 1716 | }; |
| 1717 | assert_eq!(style_op.peer, op.peer); |
| 1718 | assert_eq!(style_op.cnt, op.id_start().counter - 1); |
| 1719 | diff.insert_value( |
| 1720 | pos as usize + 1, |
| 1721 | RichtextStateChunk::new_style(style_op, AnchorType::End), |
| 1722 | (), |
| 1723 | ); |
| 1724 | } |
| 1725 | }, |
| 1726 | _ => unreachable!(), |
| 1727 | }, |
| 1728 | RichtextCalcMode::Crdt { |
| 1729 | tracker, |
| 1730 | styles, |
| 1731 | texts, |
| 1732 | start_vv, |
| 1733 | source_not_in_op_context: _, |
| 1734 | shallow_root_seeded, |
| 1735 | } => { |
| 1736 | if !*shallow_root_seeded && !oplog.shallow_since_vv().is_empty() { |
| 1737 | Self::seed_tracker_from_shallow_root( |
| 1738 | op.raw_op().container, |
| 1739 | oplog, |
| 1740 | tracker, |
| 1741 | styles, |
| 1742 | start_vv, |
| 1743 | ); |
| 1744 | // The seeded tracker replaced the old one and holds no text chunks. |
| 1745 | texts.clear(); |
| 1746 | *shallow_root_seeded = true; |
| 1747 | } |
| 1748 | |
| 1749 | if let Some(vv) = vv { |
| 1750 | tracker.checkout(vv); |
| 1751 | } |
| 1752 | Self::apply_crdt_op_to_tracker(oplog, tracker, styles, texts, op); |
| 1753 | } |
| 1754 | } |
| 1755 | } |
| 1756 | |
| 1757 | fn calculate_diff( |
| 1758 | &mut self, |
| 1759 | idx: ContainerIdx, |
| 1760 | oplog: &OpLog, |
| 1761 | info: DiffCalcVersionInfo, |
| 1762 | _: impl FnMut(&ContainerID), |
| 1763 | ) -> (InternalDiff, DiffMode) { |
| 1764 | #[allow(clippy::too_many_arguments)] |
| 1765 | fn push_tracker_chunk( |
| 1766 | delta: &mut DeltaRope<RichtextStateChunk, ()>, |
| 1767 | idx: ContainerIdx, |
| 1768 | oplog: &OpLog, |
| 1769 | styles: &[(StyleOp, usize)], |
| 1770 | texts: &TrackerTexts, |
| 1771 | value: RichtextChunk, |
| 1772 | id: ID, |
| 1773 | lamport: Option<Lamport>, |
| 1774 | ) { |
| 1775 | match value.value() { |
| 1776 | RichtextChunkValue::Text(text) => { |
| 1777 | let lamport = lamport.unwrap(); |
| 1778 | texts.for_each_slice(text, |offset, bytes| { |
| 1779 | delta.push_insert( |
| 1780 | RichtextStateChunk::Text(TextChunk::new( |
| 1781 | bytes, |
| 1782 | IdFull::new( |
| 1783 | id.peer, |
| 1784 | id.counter + offset as Counter, |
| 1785 | lamport + offset as Lamport, |
| 1786 | ), |
| 1787 | )), |
| 1788 | (), |
| 1789 | ); |
| 1790 | }); |
| 1791 | } |
| 1792 | RichtextChunkValue::StyleAnchor { id, anchor_type } => { |
| 1793 | delta.push_insert( |
| 1794 | RichtextStateChunk::Style { |
| 1795 | style: Arc::new(styles[id as usize].0.clone()), |
| 1796 | anchor_type, |
| 1797 | }, |
| 1798 | (), |
| 1799 | ); |
| 1800 | } |
| 1801 | RichtextChunkValue::Unknown(len) => { |
| 1802 | // assert not unknown id |
| 1803 | assert_ne!(id.peer, PeerID::MAX); |
| 1804 | let mut id = id; |
| 1805 | let mut acc_len = 0; |
| 1806 | let end = id.counter + len as Counter; |
| 1807 | let shallow_root = oplog.shallow_since_vv().get(&id.peer).copied().unwrap_or(0); |
| 1808 | if id.counter < shallow_root { |
| 1809 | // need to find the content between id.counter ~ target_end in gc state |
| 1810 | let target_end = shallow_root.min(end); |
| 1811 | oplog.with_history_cache(|h| { |
| 1812 | let chunks = h.find_text_chunks_in( |
| 1813 | idx, |
| 1814 | IdSpan::new(id.peer, id.counter, target_end), |
| 1815 | ); |
| 1816 | for c in chunks { |
| 1817 | acc_len += c.rle_len(); |
| 1818 | delta.push_insert(c, ()); |
| 1819 | } |
| 1820 | }); |
| 1821 | id.counter = shallow_root; |
| 1822 | } |
| 1823 | |
| 1824 | if id.counter < end { |
| 1825 | for rich_op in oplog.iter_ops(IdSpan::new(id.peer, id.counter, end)) { |
| 1826 | acc_len += rich_op.content_len(); |
| 1827 | let op = rich_op.op(); |
| 1828 | let lamport = rich_op.lamport(); |
| 1829 | let content = op.content.as_list().unwrap(); |
| 1830 | match content { |
| 1831 | InnerListOp::InsertText { slice, .. } => { |
| 1832 | delta.push_insert( |
| 1833 | RichtextStateChunk::Text(TextChunk::new( |
| 1834 | slice.clone(), |
| 1835 | IdFull::new(id.peer, op.counter, lamport), |
| 1836 | )), |
| 1837 | (), |
| 1838 | ); |
| 1839 | } |
| 1840 | _ => unreachable!("{:?}", content), |
| 1841 | } |
| 1842 | } |
| 1843 | } |
| 1844 | |
| 1845 | debug_assert_eq!(acc_len, len as usize); |
| 1846 | } |
| 1847 | RichtextChunkValue::MoveAnchor => unreachable!(), |
| 1848 | } |
| 1849 | } |
| 1850 | |
| 1851 | fn push_tracker_delta_item( |
| 1852 | delta: &mut DeltaRope<RichtextStateChunk, ()>, |
| 1853 | idx: ContainerIdx, |
| 1854 | oplog: &OpLog, |
| 1855 | styles: &[(StyleOp, usize)], |
| 1856 | texts: &TrackerTexts, |
| 1857 | item: CrdtRopeDelta, |
| 1858 | ) { |
| 1859 | match item { |
| 1860 | CrdtRopeDelta::Retain(len) => { |
| 1861 | delta.push_retain(len, ()); |
| 1862 | } |
| 1863 | CrdtRopeDelta::Insert { |
| 1864 | chunk: value, |
| 1865 | id, |
| 1866 | lamport, |
| 1867 | } => push_tracker_chunk(delta, idx, oplog, styles, texts, value, id, lamport), |
| 1868 | CrdtRopeDelta::Delete(len) => { |
| 1869 | delta.push_delete(len); |
| 1870 | } |
| 1871 | } |
| 1872 | } |
| 1873 | |
| 1874 | match &mut *self.mode { |
| 1875 | RichtextCalcMode::Linear { diff, .. } => ( |
| 1876 | InternalDiff::RichtextRaw(std::mem::take(diff)), |
| 1877 | DiffMode::Linear, |
| 1878 | ), |
| 1879 | RichtextCalcMode::Crdt { |
| 1880 | tracker, |
| 1881 | styles, |
| 1882 | texts, |
| 1883 | source_not_in_op_context, |
| 1884 | .. |
| 1885 | } => { |
| 1886 | let (mut retreat, _) = info.from_vv.diff_iter(info.to_vv); |
| 1887 | let has_retreat = retreat.next().is_some(); |
| 1888 | // The tracker models everything below its seed version as one |
| 1889 | // opaque "unknown" span: it can never be retreated and its |
| 1890 | // interior has no ids. Trusting it is sound exactly when no |
| 1891 | // replayed op is concurrent with anything below the replay |
| 1892 | // base — the definition of a critical base (spec D8b). Every |
| 1893 | // concurrent pair the Fugue adjudication has to order is then |
| 1894 | // inside the replayed region, and the alive-set of below-base |
| 1895 | // content is identical at every checkout the replay performs, |
| 1896 | // so the opaque span is a faithful, length-stable model of |
| 1897 | // the base state. A reused tracker may be seeded even lower |
| 1898 | // (`start_vv` ⊆ base); criticality transfers down, because an |
| 1899 | // op concurrent with an event in `Events(start_vv)` would be |
| 1900 | // concurrent with that same event in `Events(base)`. |
| 1901 | // A base only known to lie in the causal past of both sides |
| 1902 | // gives no such promise (`source_not_in_op_context` then |
| 1903 | // reports replayed ops whose causal context misses the source |
| 1904 | // state), so fall back to reconstructing the target state from |
| 1905 | // CRDT ids. |
| 1906 | let base_is_trustworthy = info.replay_base_is_critical |
| 1907 | || (info.replay_base_vv == info.from_vv && !*source_not_in_op_context); |
| 1908 | let should_rebuild = |
| 1909 | has_retreat || !base_is_trustworthy || !oplog.shallow_since_vv().is_empty(); |
| 1910 | if should_rebuild { |
| 1911 | // Richtext diffs can start from a tracker that only knows the replay-base |
| 1912 | // state as unknown spans. Expressing a rollback or an import from a base |
| 1913 | // older than `from` as local |
| 1914 | // edits can target the wrong visible text when the source state contains |
| 1915 | // concurrent inserts or sliced ops. The same risk exists when an op is replayed |
| 1916 | // from a dependency version that does not include the visible source state. |
| 1917 | // Preserve correctness by replacing the visible source state with the target |
| 1918 | // state reconstructed from CRDT ids. Shallow docs seed this tracker from the |
| 1919 | // shallow-root state and replay only the retained suffix of history. |
| 1920 | #[cfg(test)] |
| 1921 | FULL_TRACKER_REBUILD_COUNT.with(|c| c.set(c.get() + 1)); |
| 1922 | let mut merged = info.from_vv.clone(); |
| 1923 | merged.merge(info.to_vv); |
| 1924 | let (mut full_tracker, full_styles, full_texts) = |
| 1925 | Self::build_full_crdt_tracker(idx, oplog, &merged); |
| 1926 | |
| 1927 | let mut delta = DeltaRope::new(); |
| 1928 | for item in full_tracker.diff(info.from_vv, info.to_vv) { |
| 1929 | push_tracker_delta_item( |
| 1930 | &mut delta, |
| 1931 | idx, |
| 1932 | oplog, |
| 1933 | &full_styles, |
| 1934 | &full_texts, |
| 1935 | item, |
| 1936 | ); |
| 1937 | } |
| 1938 | **tracker = full_tracker; |
| 1939 | *styles = full_styles; |
| 1940 | *texts = full_texts; |
| 1941 | // `start_vv` is deliberately left as-is: the rebuild's |
| 1942 | // real seed is even lower (the empty version, or the |
| 1943 | // shallow root), so the reseed test in `start_tracking` |
| 1944 | // only becomes more conservative. |
| 1945 | |
| 1946 | return (InternalDiff::RichtextRaw(delta), DiffMode::Checkout); |
| 1947 | } |
| 1948 | |
| 1949 | let mut delta = DeltaRope::new(); |
| 1950 | for item in tracker.diff(info.from_vv, info.to_vv) { |
| 1951 | // `has_retreat` in `should_rebuild` is load-bearing for |
| 1952 | // this loop: a retreat is the only way to un-delete |
| 1953 | // below-base content, so a forward-only diff can never |
| 1954 | // emit the opaque span as an insert (which would abort in |
| 1955 | // `push_tracker_chunk`). |
| 1956 | #[cfg(debug_assertions)] |
| 1957 | if let CrdtRopeDelta::Insert { chunk, .. } = &item { |
| 1958 | debug_assert!( |
| 1959 | !matches!(chunk.value(), RichtextChunkValue::Unknown(_)), |
| 1960 | "the opaque below-base span leaked into a richtext diff" |
| 1961 | ); |
| 1962 | } |
| 1963 | push_tracker_delta_item(&mut delta, idx, oplog, styles, texts, item); |
| 1964 | } |
| 1965 | |
| 1966 | (InternalDiff::RichtextRaw(delta), DiffMode::Checkout) |
| 1967 | } |
| 1968 | } |
| 1969 | } |
| 1970 | |
| 1971 | fn finish_this_round(&mut self) { |
| 1972 | match &mut *self.mode { |
| 1973 | RichtextCalcMode::Crdt { .. } => {} |
| 1974 | RichtextCalcMode::Linear { |
| 1975 | diff, |
| 1976 | last_style_start, |
| 1977 | } => { |
| 1978 | *diff = DeltaRope::new(); |
| 1979 | last_style_start.take(); |
| 1980 | } |
| 1981 | } |
| 1982 | } |
| 1983 | } |
| 1984 | |
| 1985 | #[derive(Debug)] |
| 1986 | pub(crate) struct MovableListDiffCalculator { |
| 1987 | list: Box<ListDiffCalculator>, |
| 1988 | inner: Box<MovableListInner>, |
| 1989 | } |
| 1990 | |
| 1991 | #[derive(Debug)] |
| 1992 | struct MovableListInner { |
| 1993 | changed_elements: FxHashMap<CompactIdLp, ElementDelta>, |
| 1994 | move_id_to_elem_id: FxHashMap<ID, IdLp>, |
| 1995 | current_mode: DiffMode, |
| 1996 | } |
| 1997 | |
| 1998 | impl DiffCalculatorTrait for MovableListDiffCalculator { |
| 1999 | fn start_tracking(&mut self, _oplog: &OpLog, vv: &crate::VersionVector, mode: DiffMode) { |
| 2000 | self.list.source_not_in_op_context = false; |
| 2001 | if !vv.includes_vv(&self.list.start_vv) || !self.list.tracker.all_vv().includes_vv(vv) { |
| 2002 | self.list.tracker.reset(); |
| 2003 | self.list.start_vv = vv.clone(); |
| 2004 | } |
| 2005 | |
| 2006 | self.list.tracker.checkout(vv); |
| 2007 | self.inner.current_mode = mode; |
| 2008 | } |
| 2009 | |
| 2010 | fn apply_change( |
| 2011 | &mut self, |
| 2012 | oplog: &OpLog, |
| 2013 | op: crate::op::RichOp, |
| 2014 | vv: Option<&crate::VersionVector>, |
| 2015 | ) { |
| 2016 | let InnerContent::List(l) = &op.raw_op().content else { |
| 2017 | unreachable!() |
| 2018 | }; |
| 2019 | |
| 2020 | // collect the elements that are moved, updated, or inserted |
| 2021 | |
| 2022 | // If it's checkout mode, we don't need to track the changes |
| 2023 | // we only need the element ids |
| 2024 | match l { |
| 2025 | InnerListOp::Insert { slice, pos: _ } => { |
| 2026 | let op_id = op.id_full().idlp(); |
| 2027 | for (i, value) in slice.as_slice().iter().enumerate() { |
| 2028 | let id = op_id.inc(i as Counter); |
| 2029 | |
| 2030 | self.inner.changed_elements.insert( |
| 2031 | id.compact(), |
| 2032 | ElementDelta { |
| 2033 | pos: Some(id), |
| 2034 | value: value.clone(), |
| 2035 | value_updated: true, |
| 2036 | value_id: Some(id), |
| 2037 | }, |
| 2038 | ); |
| 2039 | } |
| 2040 | } |
| 2041 | InnerListOp::Delete(_) => {} |
| 2042 | InnerListOp::Move { elem_id, .. } => { |
| 2043 | let idlp = IdLp::new(op.peer, op.lamport()); |
| 2044 | match self.inner.changed_elements.get_mut(&elem_id.compact()) { |
| 2045 | Some(change) => { |
| 2046 | if change.pos.is_some() && change.pos.as_ref().unwrap() > &idlp { |
| 2047 | } else { |
| 2048 | change.pos = Some(idlp); |
| 2049 | } |
| 2050 | } |
| 2051 | None => { |
| 2052 | self.inner.changed_elements.insert( |
| 2053 | elem_id.compact(), |
| 2054 | ElementDelta { |
| 2055 | pos: Some(idlp), |
| 2056 | value: LoroValue::Null, |
| 2057 | value_updated: false, |
| 2058 | value_id: None, |
| 2059 | }, |
| 2060 | ); |
| 2061 | } |
| 2062 | } |
| 2063 | } |
| 2064 | InnerListOp::Set { elem_id, value } => { |
| 2065 | let idlp = IdLp::new(op.peer, op.lamport()); |
| 2066 | match self.inner.changed_elements.get_mut(&elem_id.compact()) { |
| 2067 | Some(change) => { |
| 2068 | if change.value_id.is_some() && change.value_id.as_ref().unwrap() > &idlp { |
| 2069 | } else { |
| 2070 | change.value_id = Some(idlp); |
| 2071 | change.value = value.clone(); |
| 2072 | } |
| 2073 | } |
| 2074 | None => { |
| 2075 | self.inner.changed_elements.insert( |
| 2076 | elem_id.compact(), |
| 2077 | ElementDelta { |
| 2078 | pos: None, |
| 2079 | value: value.clone(), |
| 2080 | value_updated: true, |
| 2081 | value_id: Some(idlp), |
| 2082 | }, |
| 2083 | ); |
| 2084 | } |
| 2085 | } |
| 2086 | } |
| 2087 | |
| 2088 | InnerListOp::StyleStart { .. } => unreachable!(), |
| 2089 | InnerListOp::StyleEnd => unreachable!(), |
| 2090 | InnerListOp::InsertText { .. } => unreachable!(), |
| 2091 | } |
| 2092 | |
| 2093 | let is_checkout = matches!(self.inner.current_mode, DiffMode::Checkout); |
| 2094 | |
| 2095 | { |
| 2096 | // Apply change on the list items |
| 2097 | if let Some(vv) = vv { |
| 2098 | self.list.tracker.checkout(vv); |
| 2099 | } |
| 2100 | Self::apply_op_to_tracker( |
| 2101 | &mut self.list.tracker, |
| 2102 | &mut self.inner.move_id_to_elem_id, |
| 2103 | oplog, |
| 2104 | &op, |
| 2105 | is_checkout, |
| 2106 | ); |
| 2107 | }; |
| 2108 | } |
| 2109 | |
| 2110 | fn finish_this_round(&mut self) { |
| 2111 | self.list.finish_this_round(); |
| 2112 | } |
| 2113 | |
| 2114 | #[instrument(skip(self, oplog, on_new_container))] |
| 2115 | fn calculate_diff( |
| 2116 | &mut self, |
| 2117 | idx: ContainerIdx, |
| 2118 | oplog: &OpLog, |
| 2119 | info: DiffCalcVersionInfo, |
| 2120 | mut on_new_container: impl FnMut(&ContainerID), |
| 2121 | ) -> (InternalDiff, DiffMode) { |
| 2122 | let (mut retreat, _) = info.from_vv.diff_iter(info.to_vv); |
| 2123 | let has_retreat = retreat.next().is_some(); |
| 2124 | // Deliberately NOT relaxed for a certified-critical replay base: the |
| 2125 | // movable-list element phase reads positions from a tracker this |
| 2126 | // rebuild has just refreshed, and trusting an unknown-span tracker |
| 2127 | // here needs its own argument about element/position state. See the |
| 2128 | // soundness comment in `RichtextDiffCalculator::calculate_diff`. |
| 2129 | if has_retreat || info.replay_base_vv != info.from_vv || self.list.source_not_in_op_context |
| 2130 | { |
| 2131 | let mut merged = info.from_vv.clone(); |
| 2132 | merged.merge(info.to_vv); |
| 2133 | self.rebuild_full_tracker(idx, oplog, &merged); |
| 2134 | } |
| 2135 | |
| 2136 | let (InternalDiff::ListRaw(list_diff), diff_mode) = |
| 2137 | self.list.calculate_diff(idx, oplog, info, |_| {}) |
| 2138 | else { |
| 2139 | unreachable!() |
| 2140 | }; |
| 2141 | |
| 2142 | assert_eq!(diff_mode, DiffMode::Checkout); |
| 2143 | let is_checkout = matches!( |
| 2144 | self.inner.current_mode, |
| 2145 | DiffMode::Checkout | DiffMode::Import |
| 2146 | ); |
| 2147 | let mut element_changes: FxHashMap<CompactIdLp, ElementDelta> = if is_checkout { |
| 2148 | FxHashMap::default() |
| 2149 | } else { |
| 2150 | std::mem::take(&mut self.inner.changed_elements) |
| 2151 | }; |
| 2152 | |
| 2153 | if is_checkout { |
| 2154 | for id in self.inner.changed_elements.keys() { |
| 2155 | element_changes.insert(*id, ElementDelta::placeholder()); |
| 2156 | } |
| 2157 | } |
| 2158 | |
| 2159 | let list_diff: Delta<SmallVec<[IdFull; 1]>, ()> = Delta { |
| 2160 | vec: list_diff |
| 2161 | .iter() |
| 2162 | .map(|x| match x { |
| 2163 | &DeltaItem::Retain { retain, .. } => DeltaItem::Retain { |
| 2164 | retain, |
| 2165 | attributes: (), |
| 2166 | }, |
| 2167 | DeltaItem::Insert { insert, .. } => { |
| 2168 | let len = insert.length(); |
| 2169 | let id = insert.id; |
| 2170 | let mut new_insert = SmallVec::with_capacity(len); |
| 2171 | for i in 0..len { |
| 2172 | let id = id.inc(i as i32); |
| 2173 | let elem_id = |
| 2174 | if let Some(e) = self.inner.move_id_to_elem_id.get(&id.id()) { |
| 2175 | e.compact() |
| 2176 | } else { |
| 2177 | insert.elem_id.unwrap_or_else(|| id.idlp().compact()) |
| 2178 | }; |
| 2179 | if is_checkout { |
| 2180 | // add the related element id |
| 2181 | element_changes.insert(elem_id, ElementDelta::placeholder()); |
| 2182 | } |
| 2183 | new_insert.push(id); |
| 2184 | } |
| 2185 | |
| 2186 | DeltaItem::Insert { |
| 2187 | insert: new_insert, |
| 2188 | attributes: (), |
| 2189 | } |
| 2190 | } |
| 2191 | &DeltaItem::Delete { delete, .. } => DeltaItem::Delete { |
| 2192 | delete, |
| 2193 | attributes: (), |
| 2194 | }, |
| 2195 | }) |
| 2196 | .collect(), |
| 2197 | }; |
| 2198 | |
| 2199 | if is_checkout { |
| 2200 | oplog.with_history_cache(|history_cache| { |
| 2201 | let checkout_index = &history_cache.get_checkout_index().movable_list; |
| 2202 | element_changes.retain(|id, change| { |
| 2203 | let id = id.to_id(); |
| 2204 | // It can be None if the target does not exist before the `to` version |
| 2205 | // But we don't need to calc from, because the deletion is handled by the diff from list items |
| 2206 | |
| 2207 | // TODO: PERF: Provide the lamport of to version |
| 2208 | let Some(pos) = checkout_index.last_pos(id, info.to_vv, Lamport::MAX, oplog) |
| 2209 | else { |
| 2210 | return false; |
| 2211 | }; |
| 2212 | // TODO: PERF: Provide the lamport of to version |
| 2213 | let value = checkout_index |
| 2214 | .last_value(id, info.to_vv, Lamport::MAX, oplog) |
| 2215 | .unwrap(); |
| 2216 | // TODO: PERF: Provide the lamport of to version |
| 2217 | let old_pos = checkout_index.last_pos(id, info.from_vv, Lamport::MAX, oplog); |
| 2218 | // TODO: PERF: Provide the lamport of to version |
| 2219 | let old_value = |
| 2220 | checkout_index.last_value(id, info.from_vv, Lamport::MAX, oplog); |
| 2221 | if old_pos.is_none() && old_value.is_none() { |
| 2222 | if let LoroValue::Container(c) = &value.value { |
| 2223 | on_new_container(c); |
| 2224 | } |
| 2225 | *change = ElementDelta { |
| 2226 | pos: Some(pos.idlp()), |
| 2227 | value: value.value.clone(), |
| 2228 | value_id: Some(IdLp::new(value.peer, value.lamport)), |
| 2229 | value_updated: true, |
| 2230 | }; |
| 2231 | } else { |
| 2232 | // TODO: PERF: can be filtered based on the list_diff and whether the pos/value are updated |
| 2233 | *change = ElementDelta { |
| 2234 | pos: Some(pos.idlp()), |
| 2235 | value: value.value.clone(), |
| 2236 | value_updated: old_value.unwrap().value != value.value, |
| 2237 | value_id: Some(IdLp::new(value.peer, value.lamport)), |
| 2238 | }; |
| 2239 | } |
| 2240 | |
| 2241 | true |
| 2242 | }); |
| 2243 | }); |
| 2244 | } |
| 2245 | |
| 2246 | let diff = MovableListInnerDelta { |
| 2247 | list: list_diff, |
| 2248 | elements: element_changes, |
| 2249 | }; |
| 2250 | |
| 2251 | (InternalDiff::MovableList(diff), self.inner.current_mode) |
| 2252 | } |
| 2253 | } |
| 2254 | |
| 2255 | impl MovableListDiffCalculator { |
| 2256 | fn new(_container: ContainerIdx) -> MovableListDiffCalculator { |
| 2257 | MovableListDiffCalculator { |
| 2258 | list: Default::default(), |
| 2259 | inner: Box::new(MovableListInner { |
| 2260 | changed_elements: Default::default(), |
| 2261 | current_mode: DiffMode::Checkout, |
| 2262 | move_id_to_elem_id: Default::default(), |
| 2263 | }), |
| 2264 | } |
| 2265 | } |
| 2266 | |
| 2267 | fn apply_op_to_tracker( |
| 2268 | tracker: &mut ListTracker, |
| 2269 | move_id_to_elem_id: &mut FxHashMap<ID, IdLp>, |
| 2270 | oplog: &OpLog, |
| 2271 | op: &RichOp<'_>, |
| 2272 | is_checkout: bool, |
| 2273 | ) { |
| 2274 | let real_op = op.op(); |
| 2275 | match &real_op.content { |
| 2276 | InnerContent::List(l) => match l { |
| 2277 | InnerListOp::Insert { .. } | InnerListOp::Delete(_) => tracker.apply_op(op), |
| 2278 | InnerListOp::Move { from, elem_id, to } => { |
| 2279 | move_id_to_elem_id.insert(op.id(), *elem_id); |
| 2280 | if !tracker.current_vv().includes_id(op.id()) { |
| 2281 | let last_pos = if is_checkout { |
| 2282 | oplog.with_history_cache(|h| { |
| 2283 | let list = &h.get_checkout_index().movable_list; |
| 2284 | list.last_pos(*elem_id, tracker.current_vv(), Lamport::MAX, oplog) |
| 2285 | .expect("moved element should have a visible source position") |
| 2286 | .id() |
| 2287 | }) |
| 2288 | } else { |
| 2289 | // In import/linear mode this id is only needed if the tracker is later |
| 2290 | // checked out before the source version, which those modes do not do. |
| 2291 | ID::new(PeerID::MAX - 2, 0) |
| 2292 | }; |
| 2293 | tracker.move_item(op.id_full(), last_pos, *from as usize, *to as usize); |
| 2294 | } |
| 2295 | } |
| 2296 | InnerListOp::Set { .. } => {} |
| 2297 | InnerListOp::InsertText { .. } |
| 2298 | | InnerListOp::StyleStart { .. } |
| 2299 | | InnerListOp::StyleEnd => unreachable!(), |
| 2300 | }, |
| 2301 | _ => unreachable!(), |
| 2302 | } |
| 2303 | } |
| 2304 | |
| 2305 | #[cold] |
| 2306 | #[inline(never)] |
| 2307 | fn rebuild_full_tracker(&mut self, idx: ContainerIdx, oplog: &OpLog, vv: &VersionVector) { |
| 2308 | struct MovableListRebuildVisitor<'a> { |
| 2309 | oplog: &'a OpLog, |
| 2310 | tracker: &'a mut ListTracker, |
| 2311 | move_id_to_elem_id: &'a mut FxHashMap<ID, IdLp>, |
| 2312 | } |
| 2313 | |
| 2314 | impl RebuildOpVisitor for MovableListRebuildVisitor<'_> { |
| 2315 | fn visit(&mut self, vv: &VersionVector, op: RichOp<'_>) { |
| 2316 | self.tracker.checkout(vv); |
| 2317 | MovableListDiffCalculator::apply_op_to_tracker( |
| 2318 | self.tracker, |
| 2319 | self.move_id_to_elem_id, |
| 2320 | self.oplog, |
| 2321 | &op, |
| 2322 | true, |
| 2323 | ); |
| 2324 | } |
| 2325 | } |
| 2326 | |
| 2327 | let mut tracker = ListTracker::default(); |
| 2328 | let mut move_id_to_elem_id = FxHashMap::default(); |
| 2329 | let mut visitor = MovableListRebuildVisitor { |
| 2330 | oplog, |
| 2331 | tracker: &mut tracker, |
| 2332 | move_id_to_elem_id: &mut move_id_to_elem_id, |
| 2333 | }; |
| 2334 | replay_container_ops_from_empty(idx, oplog, vv, &mut visitor); |
| 2335 | |
| 2336 | *self.list.tracker = tracker; |
| 2337 | self.inner.move_id_to_elem_id = move_id_to_elem_id; |
| 2338 | } |
| 2339 | } |
| 2340 | |
| 2341 | #[test] |
| 2342 | fn test_size() { |
| 2343 | let text = RichtextDiffCalculator::new(); |
| 2344 | let size = std::mem::size_of_val(&text); |
| 2345 | assert!(size < 50, "RichtextDiffCalculator size: {}", size); |
| 2346 | let list = MovableListDiffCalculator::new(ContainerIdx::from_index_and_type( |
| 2347 | 0, |
| 2348 | loro_common::ContainerType::MovableList, |
| 2349 | )); |
| 2350 | let size = std::mem::size_of_val(&list); |
| 2351 | assert!(size < 50, "MovableListDiffCalculator size: {}", size); |
| 2352 | let calc = ContainerDiffCalculator::Richtext(text); |
| 2353 | let size = std::mem::size_of_val(&calc); |
| 2354 | assert!(size < 50, "ContainerDiffCalculator size: {}", size); |
| 2355 | } |
| 2356 | |
| 2357 | /// A doc with a movable list "items" holding a nested map (`value: 0`) plus |
| 2358 | /// unrelated list/text containers, committed as peer 1. |
| 2359 | #[cfg(test)] |
| 2360 | fn movable_list_fixture() -> crate::LoroDoc { |
| 2361 | use crate::{LoroDoc, MapHandler}; |
| 2362 | |
| 2363 | let base = LoroDoc::new_auto_commit(); |
| 2364 | base.set_peer_id(1).unwrap(); |
| 2365 | let nested = base |
| 2366 | .get_movable_list("items") |
| 2367 | .push_container(MapHandler::new_detached()) |
| 2368 | .unwrap(); |
| 2369 | nested.insert("value", 0).unwrap(); |
| 2370 | base.get_list("unrelated-list").push("a").unwrap(); |
| 2371 | base.get_text("unrelated-text") |
| 2372 | .insert(0, "a", crate::cursor::PosType::Unicode) |
| 2373 | .unwrap(); |
| 2374 | base.commit_then_renew(); |
| 2375 | base |
| 2376 | } |
| 2377 | |
| 2378 | #[cfg(test)] |
| 2379 | fn nested_map(doc: &crate::LoroDoc) -> crate::MapHandler { |
| 2380 | use crate::handler::ValueOrHandler; |
| 2381 | |
| 2382 | match doc.get_movable_list("items").get_(0).unwrap() { |
| 2383 | ValueOrHandler::Handler(handler) => handler.into_map().unwrap(), |
| 2384 | ValueOrHandler::Value(value) => panic!("expected nested map, got {value:?}"), |
| 2385 | } |
| 2386 | } |
| 2387 | |
| 2388 | /// Asserts the diff round produced exactly one internal map diff, for |
| 2389 | /// `expected_idx`, whose `key` entry resolves to `expected`. |
| 2390 | #[cfg(test)] |
| 2391 | fn assert_single_map_value_diff( |
| 2392 | diffs: &[InternalContainerDiff], |
| 2393 | expected_idx: ContainerIdx, |
| 2394 | key: &str, |
| 2395 | expected: LoroValue, |
| 2396 | ) { |
| 2397 | assert_eq!(diffs.len(), 1); |
| 2398 | let diff = &diffs[0]; |
| 2399 | assert_eq!(diff.idx, expected_idx); |
| 2400 | let DiffVariant::Internal(InternalDiff::Map(map_diff)) = &diff.diff else { |
| 2401 | panic!("expected an internal map diff, got {:?}", diff.diff); |
| 2402 | }; |
| 2403 | let value = map_diff |
| 2404 | .updated |
| 2405 | .get(&InternalString::from(key)) |
| 2406 | .unwrap_or_else(|| panic!("map diff has no entry for {key:?}: {map_diff:?}")) |
| 2407 | .as_ref() |
| 2408 | .and_then(|map_value| map_value.value.clone()); |
| 2409 | assert_eq!(value, Some(expected)); |
| 2410 | } |
| 2411 | |
| 2412 | #[test] |
| 2413 | fn causal_existing_peer_import_uses_current_version_as_replay_base() { |
| 2414 | use crate::{handler::HandlerTrait, loro::ExportMode}; |
| 2415 | |
| 2416 | let base = movable_list_fixture(); |
| 2417 | let target = base.fork(); |
| 2418 | let source = base.fork(); |
| 2419 | let relay = base.fork(); |
| 2420 | // Continue an existing peer after another peer has become the current |
| 2421 | // frontier. This gives the new change both an explicit dependency on the |
| 2422 | // relay and an implicit dependency on its own previous counter. |
| 2423 | source.set_peer_id(1).unwrap(); |
| 2424 | relay.set_peer_id(2).unwrap(); |
| 2425 | relay.get_map("relay").insert("ready", true).unwrap(); |
| 2426 | relay.commit_then_renew(); |
| 2427 | let relay_updates = relay.export(ExportMode::updates(&base.oplog_vv())).unwrap(); |
| 2428 | target.import(&relay_updates).unwrap(); |
| 2429 | source.import(&relay_updates).unwrap(); |
| 2430 | |
| 2431 | let before = target.oplog_vv(); |
| 2432 | let before_frontiers = target.oplog_frontiers(); |
| 2433 | nested_map(&source).insert("value", 1).unwrap(); |
| 2434 | source.commit_then_renew(); |
| 2435 | let nested_update = source.export(ExportMode::updates(&before)).unwrap(); |
| 2436 | |
| 2437 | // Import only into the oplog so this test can inspect the exact diff round. |
| 2438 | target.detach(); |
| 2439 | target.import(&nested_update).unwrap(); |
| 2440 | let after = target.oplog_vv(); |
| 2441 | let after_frontiers = target.oplog_frontiers(); |
| 2442 | let expected_idx = nested_map(&target).idx(); |
| 2443 | |
| 2444 | let oplog = target.oplog().lock(); |
| 2445 | let (base, _) = |
| 2446 | oplog.iter_from_replay_base_causally(&before, &before_frontiers, &after, &after_frontiers); |
| 2447 | assert_eq!(base.vv, before); |
| 2448 | assert_eq!(base.diff_mode, DiffMode::ImportGreaterUpdates); |
| 2449 | assert_eq!( |
| 2450 | changed_containers_between(&oplog, &before, &after).unwrap(), |
| 2451 | [expected_idx].into_iter().collect() |
| 2452 | ); |
| 2453 | |
| 2454 | let mut calculator = DiffCalculator::new(false); |
| 2455 | let (diffs, _) = calculator.calc_diff_internal( |
| 2456 | &oplog, |
| 2457 | &before, |
| 2458 | &before_frontiers, |
| 2459 | &after, |
| 2460 | &after_frontiers, |
| 2461 | None, |
| 2462 | ); |
| 2463 | assert_eq!(calculator.calculators.len(), 1); |
| 2464 | assert!(calculator.get_calc(expected_idx).is_some()); |
| 2465 | assert_single_map_value_diff(&diffs, expected_idx, "value", 1.into()); |
| 2466 | } |
| 2467 | |
| 2468 | #[test] |
| 2469 | fn conservative_replay_only_builds_calculators_for_changed_containers() { |
| 2470 | use crate::{handler::HandlerTrait, loro::ExportMode}; |
| 2471 | |
| 2472 | let base = movable_list_fixture(); |
| 2473 | let target = base.fork(); |
| 2474 | target.set_peer_id(2).unwrap(); |
| 2475 | target.get_map("relay").insert("ready", true).unwrap(); |
| 2476 | // Concurrent edits on the same list are what force the conservative |
| 2477 | // replay; register-only concurrency would be replayed from `before`. |
| 2478 | target.get_list("unrelated-list").push("b").unwrap(); |
| 2479 | target.commit_then_renew(); |
| 2480 | |
| 2481 | let source = base.fork(); |
| 2482 | source.set_peer_id(3).unwrap(); |
| 2483 | nested_map(&source).insert("value", 1).unwrap(); |
| 2484 | source.get_list("unrelated-list").push("c").unwrap(); |
| 2485 | source.commit_then_renew(); |
| 2486 | |
| 2487 | let before = target.oplog_vv(); |
| 2488 | let before_frontiers = target.oplog_frontiers(); |
| 2489 | let nested_update = source.export(ExportMode::updates(&before)).unwrap(); |
| 2490 | |
| 2491 | // Import only into the oplog so this test can inspect the exact diff round. |
| 2492 | target.detach(); |
| 2493 | target.import(&nested_update).unwrap(); |
| 2494 | let after = target.oplog_vv(); |
| 2495 | let after_frontiers = target.oplog_frontiers(); |
| 2496 | let expected_idx = nested_map(&target).idx(); |
| 2497 | let list_idx = target.get_list("unrelated-list").idx(); |
| 2498 | |
| 2499 | let oplog = target.oplog().lock(); |
| 2500 | let (base, _) = |
| 2501 | oplog.iter_from_replay_base_causally(&before, &before_frontiers, &after, &after_frontiers); |
| 2502 | assert_ne!( |
| 2503 | base.vv, before, |
| 2504 | "the fixture must exercise conservative replay" |
| 2505 | ); |
| 2506 | assert_eq!(base.diff_mode, DiffMode::Import); |
| 2507 | assert_eq!( |
| 2508 | changed_containers_between(&oplog, &before, &after).unwrap(), |
| 2509 | [expected_idx, list_idx].into_iter().collect() |
| 2510 | ); |
| 2511 | |
| 2512 | let mut calculator = DiffCalculator::new(false); |
| 2513 | let (diffs, _) = calculator.calc_diff_internal( |
| 2514 | &oplog, |
| 2515 | &before, |
| 2516 | &before_frontiers, |
| 2517 | &after, |
| 2518 | &after_frontiers, |
| 2519 | None, |
| 2520 | ); |
| 2521 | assert_eq!(calculator.calculators.len(), 2); |
| 2522 | assert!(calculator.get_calc(expected_idx).is_some()); |
| 2523 | assert!(calculator.get_calc(list_idx).is_some()); |
| 2524 | let map_diffs: Vec<_> = diffs |
| 2525 | .iter() |
| 2526 | .filter(|d| d.idx == expected_idx) |
| 2527 | .cloned() |
| 2528 | .collect(); |
| 2529 | assert_single_map_value_diff(&map_diffs, expected_idx, "value", 1.into()); |
| 2530 | } |
| 2531 | |
| 2532 | #[test] |
| 2533 | fn conservative_checkout_replay_filters_to_retreat_changed_containers() { |
| 2534 | use crate::{handler::HandlerTrait, loro::ExportMode}; |
| 2535 | |
| 2536 | let base = movable_list_fixture(); |
| 2537 | let target = base.fork(); |
| 2538 | target.set_peer_id(2).unwrap(); |
| 2539 | target.get_map("relay").insert("ready", true).unwrap(); |
| 2540 | target.commit_then_renew(); |
| 2541 | |
| 2542 | let source = base.fork(); |
| 2543 | source.set_peer_id(3).unwrap(); |
| 2544 | nested_map(&source).insert("value", 1).unwrap(); |
| 2545 | source.commit_then_renew(); |
| 2546 | |
| 2547 | // `after` is the older version; the concurrent nested-map edit exists only |
| 2548 | // on the `before` side, so the changed set comes from the retreat spans. |
| 2549 | let after = target.oplog_vv(); |
| 2550 | let after_frontiers = target.oplog_frontiers(); |
| 2551 | let nested_update = source |
| 2552 | .export(ExportMode::updates(&base.oplog_vv())) |
| 2553 | .unwrap(); |
| 2554 | |
| 2555 | // Import only into the oplog so this test can inspect the exact diff round. |
| 2556 | target.detach(); |
| 2557 | target.import(&nested_update).unwrap(); |
| 2558 | let before = target.oplog_vv(); |
| 2559 | let before_frontiers = target.oplog_frontiers(); |
| 2560 | let expected_idx = nested_map(&target).idx(); |
| 2561 | |
| 2562 | let oplog = target.oplog().lock(); |
| 2563 | let (base, _) = |
| 2564 | oplog.iter_from_replay_base_causally(&before, &before_frontiers, &after, &after_frontiers); |
| 2565 | assert_ne!( |
| 2566 | base.vv, before, |
| 2567 | "the fixture must exercise conservative replay" |
| 2568 | ); |
| 2569 | assert_eq!(base.diff_mode, DiffMode::Checkout); |
| 2570 | assert_eq!( |
| 2571 | changed_containers_between(&oplog, &before, &after).unwrap(), |
| 2572 | [expected_idx].into_iter().collect() |
| 2573 | ); |
| 2574 | |
| 2575 | let mut calculator = DiffCalculator::new(false); |
| 2576 | let (diffs, _) = calculator.calc_diff_internal( |
| 2577 | &oplog, |
| 2578 | &before, |
| 2579 | &before_frontiers, |
| 2580 | &after, |
| 2581 | &after_frontiers, |
| 2582 | None, |
| 2583 | ); |
| 2584 | assert_eq!(calculator.calculators.len(), 1); |
| 2585 | assert!(calculator.get_calc(expected_idx).is_some()); |
| 2586 | // Checking out backward removes the concurrent edit again. |
| 2587 | assert_single_map_value_diff(&diffs, expected_idx, "value", 0.into()); |
| 2588 | } |
| 2589 | |
| 2590 | /// A persisted calculator (the shape `LoroDoc::checkout` drives) replays |
| 2591 | /// ops its tracker has already applied whenever the tracker was rebuilt |
| 2592 | /// past `from`: here a retreat rebuilds it over the whole history, and the |
| 2593 | /// forward walk that follows re-replays every op. The tracker skips those |
| 2594 | /// inserts, but the style table must not grow a duplicate entry per |
| 2595 | /// re-replayed StyleStart. |
| 2596 | #[test] |
| 2597 | fn persisted_walk_does_not_duplicate_style_entries() { |
| 2598 | use crate::{cursor::PosType, handler::HandlerTrait, LoroDoc}; |
| 2599 | |
| 2600 | let a = LoroDoc::new_auto_commit(); |
| 2601 | a.set_peer_id(1).unwrap(); |
| 2602 | a.get_text("t") |
| 2603 | .insert(0, "seed text", PosType::Unicode) |
| 2604 | .unwrap(); |
| 2605 | a.commit_then_renew(); |
| 2606 | let marks = 5; |
| 2607 | let mut stops = vec![a.oplog_frontiers()]; |
| 2608 | for round in 0..marks { |
| 2609 | let t = a.get_text("t"); |
| 2610 | t.insert(0, "x", PosType::Unicode).unwrap(); |
| 2611 | t.mark(0, 4, "bold", (round % 2 == 0).into(), PosType::Unicode) |
| 2612 | .unwrap(); |
| 2613 | a.commit_then_renew(); |
| 2614 | stops.push(a.oplog_frontiers()); |
| 2615 | } |
| 2616 | |
| 2617 | let oplog = a.oplog().lock(); |
| 2618 | let idx = a.get_text("t").idx(); |
| 2619 | let vv = |f: &Frontiers| oplog.dag.frontiers_to_vv(f).unwrap(); |
| 2620 | let mut calc = DiffCalculator::new(true); |
| 2621 | let first = &stops[0]; |
| 2622 | let last = stops.last().unwrap(); |
| 2623 | calc.calc_diff_internal(&oplog, &vv(first), first, &vv(last), last, None); |
| 2624 | calc.calc_diff_internal(&oplog, &vv(last), last, &vv(first), first, None); |
| 2625 | for w in stops.windows(2) { |
| 2626 | calc.calc_diff_internal(&oplog, &vv(&w[0]), &w[0], &vv(&w[1]), &w[1], None); |
| 2627 | } |
| 2628 | |
| 2629 | let (_, c) = calc.get_or_create_calc(idx, oplog.arena.get_depth(idx)); |
| 2630 | let ContainerDiffCalculator::Richtext(text) = c else { |
| 2631 | panic!("expected a richtext calculator"); |
| 2632 | }; |
| 2633 | let ids = text.tracked_style_ids(); |
| 2634 | assert_eq!(ids.len(), marks, "duplicate style entries: {ids:?}"); |
| 2635 | } |