forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

replay_base.rs723 lines, 26.2 KiBHistoryRawDownload
1//! Replay-base selection: the bounded multi-head critical version search
2//! (`OpLog::latest_critical_version_below_meet`) and its wiring in
3//! `iter_from_replay_base_causally`.
4//!
5//! The DAG shape under test is the criss-cross that continuous two-peer sync
6//! produces: every merge point has two heads, so the single-head descent
7//! (`latest_single_head_critical_version`) stays stuck at the initial fork
8//! point while the multi-head fixpoint finds the last fully synced version.
9
10use crate::dag::DagUtils;
11use crate::diff_calc::DiffMode;
12use crate::loro::ExportMode;
13use crate::oplog::CriticalVersionSearch;
14use crate::{LoroDoc, VersionVector};
15
16use super::exchange;
17
18/// Two peers that edit concurrently and fully sync after every round.
19fn criss_cross(rounds: usize) -> (LoroDoc, LoroDoc) {
20 let a = LoroDoc::new_auto_commit();
21 a.set_peer_id(1).unwrap();
22 a.get_text("t").insert_unicode(0, "base").unwrap();
23 a.commit_then_renew();
24 let b = a.fork();
25 b.set_peer_id(2).unwrap();
26 for _ in 0..rounds {
27 a.get_text("t").insert_unicode(0, "a").unwrap();
28 a.commit_then_renew();
29 b.get_text("t").insert_unicode(0, "b").unwrap();
30 b.commit_then_renew();
31 exchange(&a, &b);
32 }
33 (a, b)
34}
35
36/// One more unsynced concurrent pair on top of a synced criss-cross, with
37/// `b`'s side imported into `a`. Returns `(a, sync_vv, before, after)`.
38fn one_concurrent_import(rounds: usize) -> (LoroDoc, VersionVector, VersionVector, VersionVector) {
39 let (a, b) = criss_cross(rounds);
40 let sync_vv = a.oplog_vv();
41 assert_eq!(sync_vv, b.oplog_vv());
42
43 a.get_text("t").insert_unicode(0, "a").unwrap();
44 a.commit_then_renew();
45 b.get_text("t").insert_unicode(0, "b").unwrap();
46 b.commit_then_renew();
47
48 let before = a.oplog_vv();
49 let update = b.export(ExportMode::updates(&before)).unwrap();
50 a.import(&update).unwrap();
51 let after = a.oplog_vv();
52 (a, sync_vv, before, after)
53}
54
55/// Randomized multi-peer edit/sync workload: on ordinary concurrent
56/// histories the search must always find a critical base — never fall back
57/// to the single-head descent. (An earlier rounds-style cap on the fixpoint
58/// caused a silent fallback on roughly a third of such imports.)
59#[test]
60fn randomized_sync_never_exhausts_the_search_budget() {
61 use crate::oplog::CRITICAL_BASE_FALLBACK_COUNT;
62
63 struct Lcg(u64);
64 impl Lcg {
65 fn below(&mut self, n: usize) -> usize {
66 self.0 = self
67 .0
68 .wrapping_mul(6364136223846793005)
69 .wrapping_add(1442695040888963407);
70 ((self.0 >> 33) as usize) % n
71 }
72 }
73 let mut rng = Lcg(0xC0FFEE);
74
75 let docs: Vec<LoroDoc> = (1..=3)
76 .map(|p| {
77 let d = LoroDoc::new_auto_commit();
78 d.set_peer_id(p).unwrap();
79 d
80 })
81 .collect();
82 docs[0].get_text("t").insert_unicode(0, "seed").unwrap();
83 docs[0].commit_then_renew();
84 let all = docs[0].export(ExportMode::all_updates()).unwrap();
85 docs[1].import(&all).unwrap();
86 docs[2].import(&all).unwrap();
87
88 let fallbacks_before = CRITICAL_BASE_FALLBACK_COUNT.with(|c| c.get());
89 let rebuilds_before = crate::diff_calc::FULL_TRACKER_REBUILD_COUNT.with(|c| c.get());
90 for _ in 0..600 {
91 let i = rng.below(3);
92 if rng.below(3) == 0 {
93 let j = (i + 1 + rng.below(2)) % 3;
94 let u = docs[i]
95 .export(ExportMode::updates(&docs[j].oplog_vv()))
96 .unwrap();
97 docs[j].import(&u).unwrap();
98 } else {
99 let t = docs[i].get_text("t");
100 let pos = rng.below(t.len_unicode() + 1);
101 t.insert_unicode(pos, "x").unwrap();
102 docs[i].commit_then_renew();
103 }
104 }
105 for _ in 0..2 {
106 for i in 0..3 {
107 for j in 0..3 {
108 if i != j {
109 let u = docs[i]
110 .export(ExportMode::updates(&docs[j].oplog_vv()))
111 .unwrap();
112 docs[j].import(&u).unwrap();
113 }
114 }
115 }
116 }
117 assert_eq!(
118 docs[0].get_text("t").to_string(),
119 docs[1].get_text("t").to_string()
120 );
121 assert_eq!(
122 docs[0].get_text("t").to_string(),
123 docs[2].get_text("t").to_string()
124 );
125 let fallbacks = CRITICAL_BASE_FALLBACK_COUNT.with(|c| c.get()) - fallbacks_before;
126 assert_eq!(
127 fallbacks, 0,
128 "the bounded search fell back to the single-head descent"
129 );
130 let rebuilds = crate::diff_calc::FULL_TRACKER_REBUILD_COUNT.with(|c| c.get()) - rebuilds_before;
131 assert_eq!(
132 rebuilds, 0,
133 "randomized concurrent imports must not rebuild the tracker"
134 );
135}
136
137#[test]
138fn multi_head_critical_base_on_criss_cross_sync() {
139 let (a, sync_vv, before, after) = one_concurrent_import(4);
140 let before_frontiers = a.oplog().lock().dag.vv_to_frontiers(&before);
141 let after_frontiers = a.oplog_frontiers();
142
143 let oplog = a.oplog().lock();
144 // On this DAG shape every synced version has two heads, so the single-head
145 // descent stays stuck at the initial fork point (before peer 2's first op)
146 // no matter how many rounds have passed…
147 let single_head = oplog
148 .dag
149 .latest_single_head_critical_version(&before_frontiers, &after_frontiers);
150 let single_head_vv = oplog.dag.frontiers_to_vv(&single_head).unwrap();
151 assert!(!single_head_vv.includes_id(loro_common::ID::new(2, 0)));
152 // …while the multi-head search retreats only to the last synced version.
153 let (base, _) =
154 oplog.iter_from_replay_base_causally(&before, &before_frontiers, &after, &after_frontiers);
155 assert_eq!(base.vv, sync_vv);
156 assert!(base.is_critical);
157 assert_eq!(base.diff_mode, DiffMode::Import);
158}
159
160#[test]
161fn fixpoint_returns_the_greatest_cut() {
162 let (a, sync_vv, before, after) = one_concurrent_import(3);
163 let mut merged = before.clone();
164 merged.merge(&after);
165
166 let oplog = a.oplog().lock();
167 let res = oplog.latest_critical_version_below_meet(&before, &after, &merged);
168 assert_eq!(res, CriticalVersionSearch::Found(sync_vv));
169}
170
171#[test]
172fn disjoint_histories_have_no_cut_below_the_meet() {
173 let a = LoroDoc::new_auto_commit();
174 a.set_peer_id(1).unwrap();
175 a.get_text("t").insert_unicode(0, "aaa").unwrap();
176 a.commit_then_renew();
177 let b = LoroDoc::new_auto_commit();
178 b.set_peer_id(2).unwrap();
179 b.get_text("t").insert_unicode(0, "bbb").unwrap();
180 b.commit_then_renew();
181
182 let before = a.oplog_vv();
183 let before_frontiers = a.oplog_frontiers();
184 a.import(&b.export(ExportMode::all_updates()).unwrap())
185 .unwrap();
186 let after = a.oplog_vv();
187 let after_frontiers = a.oplog_frontiers();
188
189 let oplog = a.oplog().lock();
190 let mut merged = before.clone();
191 merged.merge(&after);
192 assert_eq!(
193 oplog.latest_critical_version_below_meet(&before, &after, &merged),
194 CriticalVersionSearch::NoneBelowMeet
195 );
196 // ∅ is trivially critical; the wiring reports it as such.
197 let (base, _) =
198 oplog.iter_from_replay_base_causally(&before, &before_frontiers, &after, &after_frontiers);
199 assert!(base.vv.is_empty());
200 assert!(base.is_critical);
201}
202
203// ---- Trusting a critical replay base (richtext) ----
204
205/// peer 1 commits `insert + mark` in ONE change, so `StyleStart` and
206/// `StyleEnd` are adjacent counters inside a single change. Peers 2 and 3
207/// then fork *between* those two counters (detached editing on a mid-change
208/// frontier), which is the only way a doc version can sit inside a style
209/// pair. The greatest critical cut then lands between the two ops of one
210/// mark, exercising the unpaired-end recovery path
211/// (`style_for_end_anchor`) of the non-rebuilt tracker.
212fn style_straddle_forks() -> (LoroDoc, LoroDoc, LoroDoc) {
213 use crate::cursor::PosType;
214 use crate::version::Frontiers;
215 use loro_common::ID;
216
217 let doc1 = LoroDoc::new_auto_commit();
218 doc1.set_peer_id(1).unwrap();
219 doc1.get_text("r")
220 .insert(0, "hello world", PosType::Unicode)
221 .unwrap();
222 doc1.get_text("r")
223 .mark(0, 5, "bold", true.into(), PosType::Unicode)
224 .unwrap();
225 doc1.commit_then_renew();
226 let snapshot = doc1.export(ExportMode::Snapshot).unwrap();
227
228 let mut forks = Vec::new();
229 for (peer, s) in [(2u64, "AAA"), (3u64, "BBB")] {
230 let d = LoroDoc::new_auto_commit();
231 d.set_detached_editing(true);
232 d.import(&snapshot).unwrap();
233 d.set_peer_id(peer).unwrap();
234 // Mid-change frontier: after StyleStart (counter 11), before
235 // StyleEnd (counter 12).
236 d.checkout(&Frontiers::from(ID::new(1, 11))).unwrap();
237 d.set_peer_id(peer).unwrap();
238 d.get_text("r").insert(2, s, PosType::Unicode).unwrap();
239 d.commit_then_renew();
240 forks.push(d);
241 }
242
243 let doc3 = forks.pop().unwrap();
244 let doc2 = forks.pop().unwrap();
245 (doc1, doc2, doc3)
246}
247
248#[test]
249fn critical_base_may_cut_between_style_start_and_end() {
250 let (doc1, doc2, doc3) = style_straddle_forks();
251 let target = LoroDoc::new_auto_commit();
252 target
253 .import(&doc1.export(ExportMode::Snapshot).unwrap())
254 .unwrap();
255 target
256 .import(
257 &doc2
258 .export(ExportMode::updates(&target.oplog_vv()))
259 .unwrap(),
260 )
261 .unwrap();
262
263 let before = target.oplog_vv();
264 let before_frontiers = target.oplog_frontiers();
265 target
266 .import(
267 &doc3
268 .export(ExportMode::updates(&target.oplog_vv()))
269 .unwrap(),
270 )
271 .unwrap();
272 let after = target.oplog_vv();
273 let after_frontiers = target.oplog_frontiers();
274
275 let oplog = target.oplog().lock();
276 let (base, _) =
277 oplog.iter_from_replay_base_causally(&before, &before_frontiers, &after, &after_frontiers);
278 // A later change to the base search that rounds cuts to change (or style
279 // pair) boundaries would silently drop this coverage — keep it pinned.
280 assert_eq!(
281 base.vv.get(&1).copied(),
282 Some(12),
283 "base must cut between StyleStart(11) and StyleEnd(12); got {:?}",
284 base.vv
285 );
286 assert!(
287 base.is_critical,
288 "the mid-mark cut must be reported critical"
289 );
290 assert_ne!(base.vv, before, "must be a conservative base");
291}
292
293#[test]
294fn style_straddling_base_converges_in_every_import_order() {
295 use crate::diff_calc::FULL_TRACKER_REBUILD_COUNT;
296 use crate::version::Frontiers;
297
298 let (doc1, doc2, doc3) = style_straddle_forks();
299 let rebuilds_before = FULL_TRACKER_REBUILD_COUNT.with(|c| c.get());
300 // a: import 2 then 3. b: import 3 then 2. c: everything in one batch.
301 let a = LoroDoc::new_auto_commit();
302 a.import(&doc1.export(ExportMode::Snapshot).unwrap())
303 .unwrap();
304 a.import(&doc2.export(ExportMode::updates(&a.oplog_vv())).unwrap())
305 .unwrap();
306 a.import(&doc3.export(ExportMode::updates(&a.oplog_vv())).unwrap())
307 .unwrap();
308
309 let b = LoroDoc::new_auto_commit();
310 b.import(&doc1.export(ExportMode::Snapshot).unwrap())
311 .unwrap();
312 b.import(&doc3.export(ExportMode::updates(&b.oplog_vv())).unwrap())
313 .unwrap();
314 b.import(&doc2.export(ExportMode::updates(&b.oplog_vv())).unwrap())
315 .unwrap();
316
317 let rebuilds = FULL_TRACKER_REBUILD_COUNT.with(|c| c.get()) - rebuilds_before;
318 assert_eq!(
319 rebuilds, 0,
320 "the straddle imports must take the trusted path"
321 );
322
323 let c = LoroDoc::new_auto_commit();
324 c.import(&doc1.export(ExportMode::Snapshot).unwrap())
325 .unwrap();
326 let all = vec![
327 doc2.export(ExportMode::updates(&c.oplog_vv())).unwrap(),
328 doc3.export(ExportMode::updates(&c.oplog_vv())).unwrap(),
329 ];
330 c.import_batch(&all).unwrap();
331
332 assert_eq!(a.get_text("r").to_string(), b.get_text("r").to_string());
333 assert_eq!(a.get_text("r").to_string(), c.get_text("r").to_string());
334 assert_eq!(
335 a.get_text("r").get_richtext_value(),
336 b.get_text("r").get_richtext_value()
337 );
338 assert_eq!(
339 a.get_text("r").get_richtext_value(),
340 c.get_text("r").get_richtext_value()
341 );
342
343 // Independent oracle: a checkout round-trip through the empty frontiers
344 // forces a full-history rebuild, so the trusted incremental result is
345 // compared against the rebuild path — not just against itself.
346 let incremental = a.get_text("r").get_richtext_value();
347 let head = a.oplog_frontiers();
348 let oracle_before = FULL_TRACKER_REBUILD_COUNT.with(|c| c.get());
349 a.checkout(&Frontiers::default()).unwrap();
350 a.checkout(&head).unwrap();
351 assert!(
352 FULL_TRACKER_REBUILD_COUNT.with(|c| c.get()) > oracle_before,
353 "the oracle round-trip must take the rebuild path"
354 );
355 assert_eq!(a.get_text("r").get_richtext_value(), incremental);
356}
357
358/// Continuous two-peer sync with marks: text and styles converge, and the
359/// full-history tracker rebuild never fires — every concurrent import is
360/// served from a tracker seeded at the (multi-head critical) replay base.
361#[test]
362fn criss_cross_sync_never_rebuilds_the_text_tracker() {
363 use crate::cursor::PosType;
364 use crate::diff_calc::FULL_TRACKER_REBUILD_COUNT;
365
366 let a = LoroDoc::new_auto_commit();
367 a.set_peer_id(1).unwrap();
368 let b = LoroDoc::new_auto_commit();
369 b.set_peer_id(2).unwrap();
370 a.get_text("r")
371 .insert(0, "seed text here", PosType::Unicode)
372 .unwrap();
373 a.commit_then_renew();
374 b.import(&a.export(ExportMode::updates(&b.oplog_vv())).unwrap())
375 .unwrap();
376
377 let rebuilds_before = FULL_TRACKER_REBUILD_COUNT.with(|c| c.get());
378 for round in 0..40 {
379 for (d, s) in [(&a, "x"), (&b, "y")] {
380 let t = d.get_text("r");
381 t.insert(1, s, PosType::Unicode).unwrap();
382 let len = t.len_unicode();
383 t.mark(
384 0,
385 (len / 2).max(1),
386 "bold",
387 (round % 2 == 0).into(),
388 PosType::Unicode,
389 )
390 .unwrap();
391 d.commit_then_renew();
392 }
393 exchange(&a, &b);
394 }
395 assert_eq!(a.get_text("r").to_string(), b.get_text("r").to_string());
396 assert_eq!(
397 a.get_text("r").get_richtext_value(),
398 b.get_text("r").get_richtext_value()
399 );
400 let rebuilds = FULL_TRACKER_REBUILD_COUNT.with(|c| c.get()) - rebuilds_before;
401 assert_eq!(
402 rebuilds, 0,
403 "concurrent imports must not rebuild the tracker"
404 );
405
406 // Independent oracle: force one rebuild via a checkout round-trip and
407 // compare it against the incrementally maintained state.
408 let incremental = a.get_text("r").get_richtext_value();
409 let head = a.oplog_frontiers();
410 a.checkout(&crate::version::Frontiers::default()).unwrap();
411 a.checkout(&head).unwrap();
412 assert!(
413 FULL_TRACKER_REBUILD_COUNT.with(|c| c.get()) > rebuilds_before,
414 "the oracle round-trip must take the rebuild path"
415 );
416 assert_eq!(a.get_text("r").get_richtext_value(), incremental);
417}
418
419/// A persisted calculator replays ops the tracker has already applied
420/// whenever the replay base sits below the version the tracker reached on
421/// an earlier round (the shape `LoroDoc::checkout` produces — driven here
422/// directly through one persisted `DiffCalculator`). The tracker skips
423/// them (`skip_applied`), and the style table must not grow a duplicate
424/// entry per re-replayed StyleStart: trusting the base turns what was a
425/// once-per-retreat re-replay into one on every step.
426#[test]
427fn persisted_walks_do_not_duplicate_style_entries() {
428 use crate::cursor::PosType;
429 use crate::diff_calc::{ContainerDiffCalculator, DiffCalculator, FULL_TRACKER_REBUILD_COUNT};
430 use crate::handler::HandlerTrait;
431
432 let a = LoroDoc::new_auto_commit();
433 a.set_peer_id(1).unwrap();
434 a.get_text("t")
435 .insert(0, "seed text", PosType::Unicode)
436 .unwrap();
437 a.commit_then_renew();
438 let b = a.fork();
439 b.set_peer_id(2).unwrap();
440
441 // A forward checkout path through half-synced frontiers: `{A_i}` is not
442 // critical (B_i is concurrent), so the step to `{A_i, B_i}` replays from
443 // the previous sync point and re-applies A_i's ops.
444 let rounds = 6;
445 let mut stops = vec![a.oplog_frontiers()];
446 for round in 0..rounds {
447 for (d, s) in [(&a, "x"), (&b, "y")] {
448 let t = d.get_text("t");
449 t.insert(0, s, PosType::Unicode).unwrap();
450 t.mark(0, 4, "bold", (round % 2 == 0).into(), PosType::Unicode)
451 .unwrap();
452 d.commit_then_renew();
453 }
454 stops.push(a.oplog_frontiers());
455 exchange(&a, &b);
456 stops.push(a.oplog_frontiers());
457 }
458
459 let oplog = a.oplog().lock();
460 let idx = a.get_text("t").idx();
461 let mut calc = DiffCalculator::new(true);
462 let rebuilds_before = FULL_TRACKER_REBUILD_COUNT.with(|c| c.get());
463 for w in stops.windows(2) {
464 let before = oplog.dag.frontiers_to_vv(&w[0]).unwrap();
465 let after = oplog.dag.frontiers_to_vv(&w[1]).unwrap();
466 calc.calc_diff_internal(&oplog, &before, &w[0], &after, &w[1], None);
467 }
468 assert_eq!(
469 FULL_TRACKER_REBUILD_COUNT.with(|c| c.get()) - rebuilds_before,
470 0,
471 "a forward walk over critical bases must not rebuild (a rebuild would reset the style table and mask the leak)"
472 );
473
474 let depth = oplog.arena.get_depth(idx);
475 let (_, c) = calc.get_or_create_calc(idx, depth);
476 let ContainerDiffCalculator::Richtext(text) = c else {
477 panic!("expected a richtext calculator");
478 };
479 assert_eq!(
480 text.tracked_style_ids().len(),
481 2 * rounds,
482 "each StyleStart must appear exactly once in the style table"
483 );
484}
485
486/// The StyleEnd fallback (`style_for_end_anchor`) pushes a style entry when
487/// its StyleStart lies below the tracker's seed. Re-replaying that StyleEnd
488/// must reuse the entry, not push another; likewise a rebuild-created entry
489/// must be reused by a later re-replay.
490#[test]
491fn straddling_walks_never_duplicate_style_entries() {
492 use crate::diff_calc::{ContainerDiffCalculator, DiffCalculator, FULL_TRACKER_REBUILD_COUNT};
493 use crate::handler::HandlerTrait;
494
495 let (doc1, doc2, doc3) = style_straddle_forks();
496 // A second mark on one fork puts a StyleStart into the region the later
497 // steps re-replay (the straddling mark's own StyleStart sits below every
498 // base and only its StyleEnd is replayed, via the fallback).
499 doc2.get_text("r")
500 .mark(0, 3, "italic", true.into(), crate::cursor::PosType::Unicode)
501 .unwrap();
502 doc2.commit_then_renew();
503 let target = LoroDoc::new_auto_commit();
504 for d in [&doc1, &doc2, &doc3] {
505 target
506 .import(&d.export(ExportMode::updates(&target.oplog_vv())).unwrap())
507 .unwrap();
508 }
509 let f0 = doc1.oplog_frontiers();
510 let f1 = {
511 let t = doc1.fork();
512 t.import(&doc2.export(ExportMode::updates(&t.oplog_vv())).unwrap())
513 .unwrap();
514 t.oplog_frontiers()
515 };
516 let f2 = target.oplog_frontiers();
517
518 let oplog = target.oplog().lock();
519 let idx = target.get_text("r").idx();
520 let mut calc = DiffCalculator::new(true);
521 let rebuilds_before = FULL_TRACKER_REBUILD_COUNT.with(|c| c.get());
522 // Forward over a base that cuts between StyleStart and StyleEnd (the
523 // fallback pushes), forward again (the fallback must reuse), retreat
524 // (rebuild replaces the table), forward again (reuse after a rebuild).
525 for w in [[&f0, &f1], [&f1, &f2], [&f2, &f1], [&f1, &f2]] {
526 let before = oplog.dag.frontiers_to_vv(w[0]).unwrap();
527 let after = oplog.dag.frontiers_to_vv(w[1]).unwrap();
528 calc.calc_diff_internal(&oplog, &before, w[0], &after, w[1], None);
529
530 let depth = oplog.arena.get_depth(idx);
531 let (_, c) = calc.get_or_create_calc(idx, depth);
532 let ContainerDiffCalculator::Richtext(text) = c else {
533 panic!("expected a richtext calculator");
534 };
535 let mut ids = text.tracked_style_ids();
536 let len = ids.len();
537 ids.sort();
538 ids.dedup();
539 assert_eq!(ids.len(), len, "duplicate style entry for one op id");
540 assert_eq!(len, 2, "one entry per mark: the fallback's and the fork's");
541 }
542 assert_eq!(
543 FULL_TRACKER_REBUILD_COUNT.with(|c| c.get()) - rebuilds_before,
544 1,
545 "only the retreating step may rebuild"
546 );
547}
548
549/// Same criss-cross shape on a plain list container: the list tracker also
550/// stops rebuilding once the replay base is certified critical.
551#[test]
552fn criss_cross_sync_never_rebuilds_the_list_tracker() {
553 use crate::diff_calc::FULL_TRACKER_REBUILD_COUNT;
554
555 let a = LoroDoc::new_auto_commit();
556 a.set_peer_id(1).unwrap();
557 let b = LoroDoc::new_auto_commit();
558 b.set_peer_id(2).unwrap();
559 a.get_list("l").insert(0, "seed").unwrap();
560 a.commit_then_renew();
561 b.import(&a.export(ExportMode::updates(&b.oplog_vv())).unwrap())
562 .unwrap();
563
564 let rebuilds_before = FULL_TRACKER_REBUILD_COUNT.with(|c| c.get());
565 for round in 0..40 {
566 for (d, v) in [(&a, "x"), (&b, "y")] {
567 d.get_list("l").insert(0, format!("{v}{round}")).unwrap();
568 d.commit_then_renew();
569 }
570 exchange(&a, &b);
571 }
572 assert_eq!(a.get_deep_value(), b.get_deep_value());
573 let rebuilds = FULL_TRACKER_REBUILD_COUNT.with(|c| c.get()) - rebuilds_before;
574 assert_eq!(
575 rebuilds, 0,
576 "concurrent list imports must not rebuild the tracker"
577 );
578}
579
580/// What a forward walk through half-synced versions of two concurrent
581/// branches does to one container's diff calculator: the stops, and the doc.
582fn half_synced_walk(
583 rounds: usize,
584 edit: impl Fn(&LoroDoc, usize),
585) -> (LoroDoc, Vec<crate::version::Frontiers>) {
586 let a = LoroDoc::new_auto_commit();
587 a.set_peer_id(1).unwrap();
588 let b = LoroDoc::new_auto_commit();
589 b.set_peer_id(2).unwrap();
590 let mut stops = vec![a.oplog_frontiers()];
591 for round in 0..rounds {
592 for d in [&a, &b] {
593 edit(d, round);
594 d.commit_then_renew();
595 }
596 // `{A_i}` is not critical (B_i is concurrent), so the step to
597 // `{A_i, B_i}` replays from the previous sync point and re-applies
598 // A_i's ops to a tracker that already has them.
599 stops.push(a.oplog_frontiers());
600 exchange(&a, &b);
601 stops.push(a.oplog_frontiers());
602 }
603 (a, stops)
604}
605
606/// Walks `stops` with one persisted calculator, returns the calculator's
607/// table size for `idx`, and checks the doc's checkouts against forks.
608fn walk_and_measure(
609 doc: &LoroDoc,
610 stops: &[crate::version::Frontiers],
611 idx: crate::container::idx::ContainerIdx,
612 table_len: impl Fn(&crate::diff_calc::ContainerDiffCalculator) -> usize,
613) -> usize {
614 use crate::diff_calc::{DiffCalculator, FULL_TRACKER_REBUILD_COUNT};
615
616 let len = {
617 let oplog = doc.oplog().lock();
618 let mut calc = DiffCalculator::new(true);
619 let rebuilds_before = FULL_TRACKER_REBUILD_COUNT.with(|c| c.get());
620 for w in stops.windows(2) {
621 let before = oplog.dag.frontiers_to_vv(&w[0]).unwrap();
622 let after = oplog.dag.frontiers_to_vv(&w[1]).unwrap();
623 calc.calc_diff_internal(&oplog, &before, &w[0], &after, &w[1], None);
624 }
625 assert_eq!(
626 FULL_TRACKER_REBUILD_COUNT.with(|c| c.get()) - rebuilds_before,
627 0,
628 "a rebuild would reset the table and mask the growth"
629 );
630 let depth = oplog.arena.get_depth(idx);
631 let (_, c) = calc.get_or_create_calc(idx, depth);
632 table_len(c)
633 };
634
635 for stop in stops {
636 doc.checkout(stop).unwrap();
637 assert_eq!(
638 doc.get_deep_value(),
639 doc.fork_at(stop).unwrap().get_deep_value()
640 );
641 }
642 doc.checkout_to_latest();
643 len
644}
645
646/// The diff calculators' text and value tables record what the tracker
647/// applies. A re-replayed insert, which the tracker skips, must not be
648/// recorded again (it kept growing the tables and using up their `u32`
649/// index space on every forward checkout). The applied prefix of a partly
650/// re-replayed op is covered by `insert_with_builds_content_only_for_the_unapplied_suffix`.
651/// See `context/text-arena-growth.md`.
652#[test]
653fn persisted_walks_record_each_text_char_once() {
654 use crate::cursor::PosType;
655 use crate::diff_calc::ContainerDiffCalculator;
656 use crate::handler::HandlerTrait;
657
658 let rounds = 50;
659 let (doc, stops) = half_synced_walk(rounds, |d, round| {
660 let t = d.get_text("t");
661 t.insert(
662 0,
663 if round % 2 == 0 { "ab" } else { "文😀" },
664 PosType::Unicode,
665 )
666 .unwrap();
667 });
668 let idx = doc.get_text("t").idx();
669 let len = walk_and_measure(&doc, &stops, idx, |c| {
670 let ContainerDiffCalculator::Richtext(text) = c else {
671 panic!("expected a richtext calculator");
672 };
673 text.tracked_text_len()
674 });
675 assert_eq!(len, 2 * 2 * rounds);
676}
677
678#[test]
679fn persisted_walks_record_each_list_value_once() {
680 use crate::diff_calc::ContainerDiffCalculator;
681 use crate::handler::HandlerTrait;
682
683 let rounds = 50;
684 let (doc, stops) = half_synced_walk(rounds, |d, round| {
685 let l = d.get_list("l");
686 l.insert(0, round as i64).unwrap();
687 l.insert(0, format!("v{round}")).unwrap();
688 });
689 let idx = doc.get_list("l").idx();
690 let len = walk_and_measure(&doc, &stops, idx, |c| {
691 let ContainerDiffCalculator::List(list) = c else {
692 panic!("expected a list calculator");
693 };
694 list.tracked_values_len()
695 });
696 assert_eq!(len, 2 * 2 * rounds);
697}
698
699/// The movable-list calculator rebuilds its tracker on these steps (base !=
700/// from), which replaces the table; this pins that it still holds one copy.
701#[test]
702fn persisted_walks_record_each_movable_list_value_once() {
703 use crate::diff_calc::ContainerDiffCalculator;
704 use crate::handler::HandlerTrait;
705
706 let rounds = 50;
707 let (doc, stops) = half_synced_walk(rounds, |d, round| {
708 let l = d.get_movable_list("m");
709 l.insert(0, round as i64).unwrap();
710 l.insert(0, format!("v{round}")).unwrap();
711 if l.len() > 2 {
712 l.mov(0, l.len() - 1).unwrap();
713 }
714 });
715 let idx = doc.get_movable_list("m").idx();
716 let len = walk_and_measure(&doc, &stops, idx, |c| {
717 let ContainerDiffCalculator::MovableList(list) = c else {
718 panic!("expected a movable list calculator");
719 };
720 list.tracked_values_len()
721 });
722 assert_eq!(len, 2 * 2 * rounds);
723}