forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

shallow_snapshot.rs1979 lines, 79.3 KiBHistoryRawDownload
1use bytes::Bytes;
2use rle::HasLength;
3use rustc_hash::FxHashSet;
4use std::collections::BTreeSet;
5
6use loro_common::{ContainerID, ContainerType, IdSpan, LoroEncodeError, LoroError, ID};
7
8use crate::{
9 container::{idx::ContainerIdx, list::list_op::InnerListOp},
10 dag::DagUtils,
11 encoding::export_fast_updates_in_range,
12 encoding::fast_snapshot::{_encode_snapshot, Snapshot},
13 state::{
14 container_store::{ContainerWrapper, PrunedRootState, FRONTIERS_KEY},
15 redact_dead_style_values, DocState,
16 },
17 utils::kv_wrapper::KvWrapper,
18 version::{Frontiers, VersionVector},
19 LoroDoc,
20};
21
22#[cfg(test)]
23const MAX_OPS_NUM_TO_ENCODE_WITHOUT_LATEST_STATE: usize = 16;
24#[cfg(not(test))]
25const MAX_OPS_NUM_TO_ENCODE_WITHOUT_LATEST_STATE: usize = 256;
26
27/// Minimum number of retained ops (root..latest) for the forward-replay fast
28/// path to be worth it. Below this, the old checkout path is used: at F ==
29/// latest it is trivial (no history to walk back), and on the 66k-container /
30/// 720k-op fixture the paths tie at ~8k retained ops while the checkout path
31/// peaks at ~4x less memory; forward replay only wins decisively past ~64k
32/// (1.25-3.6x at 79k, 10-14x at 393k). Note this fixture has tiny
33/// per-container histories; docs with long text histories penalize the
34/// checkout path more, shifting the real crossover lower.
35#[cfg(test)]
36const MIN_RETAINED_OPS_FOR_FORWARD_ROOT_STATE: usize = 16;
37#[cfg(not(test))]
38const MIN_RETAINED_OPS_FOR_FORWARD_ROOT_STATE: usize = 65536;
39
40/// The fast path re-encodes and replays ALL pre-root history into a temporary
41/// doc, so its cost scales with the prefix, not the tail. Cap the prefix/tail
42/// ratio: on the fixture the fast path wins at ratio 9 and loses at ratio 19,
43/// and an unrelated huge prefix (e.g. millions of same-key Map overwrites
44/// before the root) must not be replayed just because the tail is large.
45const MAX_PRE_ROOT_TO_RETAINED_OPS_RATIO: usize = 16;
46
47/// Absolute cap on pre-root ops for the forward-replay path. Replaying ~1M ops
48/// costs roughly 0.5-1s and several hundred MiB of peak memory; beyond that
49/// the checkout path is safer (its work is bounded by the tail), especially
50/// on wasm32.
51const MAX_PRE_ROOT_OPS_FOR_FORWARD_REPLAY: usize = 1_000_000;
52
53/// Cap on the pre-root prefix's decoded byte size, estimated by walking op
54/// payloads by reference BEFORE any value is copied (see
55/// `estimate_ops_content_bytes`). Op counts miss value sizes: a Map write is
56/// one atom regardless of how large its Binary/String value is, so a
57/// byte-heavy but low-op prefix would bypass the op-count gates. Checking only
58/// the encoded blob afterwards would be too late —
59/// `export_fast_updates_in_range` slice-copies values into a fresh store while
60/// building it, which is exactly the allocation this cap exists to prevent.
61#[cfg(test)]
62const MAX_PRE_ROOT_BYTES_FOR_FORWARD_REPLAY: usize = 1 << 20;
63#[cfg(not(test))]
64const MAX_PRE_ROOT_BYTES_FOR_FORWARD_REPLAY: usize = 32 << 20;
65
66/// Estimate the decoded byte size of everything in `spans` — op payloads
67/// (recursing into nested `LoroValue::List`/`Map`), style values, and commit
68/// messages — following arena slices by reference and never copying values.
69/// The walk is cap-aware: every counting step takes a remaining budget and
70/// bails as soon as it is exceeded, so a rejected prefix costs one bounded
71/// walk instead of a full copy.
72fn estimate_ops_content_bytes(oplog: &crate::OpLog, spans: &[IdSpan], cap: usize) -> usize {
73 let mut total = 0usize;
74 'outer: for span in spans {
75 let mut span = *span;
76 span.normalize_();
77 if span.counter.end <= 0 {
78 continue;
79 }
80
81 span.counter.start = span.counter.start.max(0);
82 span.counter.end = span.counter.end.max(0);
83 if span.counter.start >= span.counter.end {
84 continue;
85 }
86
87 for change in oplog.iter_changes(span) {
88 let start =
89 ((span.counter.start - change.id.counter).max(0) as usize).min(change.atom_len());
90 let end =
91 ((span.counter.end - change.id.counter).max(0) as usize).min(change.atom_len());
92 if start == end {
93 continue;
94 }
95
96 if let Some(msg) = change.commit_msg.as_ref() {
97 total = total.saturating_add(msg.len());
98 if total > cap {
99 break 'outer;
100 }
101 }
102
103 for op in crate::op::RichOp::new_iter_by_cnt_range(change, span.counter) {
104 total = total.saturating_add(rich_op_content_bytes(oplog, &op, cap - total));
105 if total > cap {
106 break 'outer;
107 }
108 }
109 }
110 }
111 total
112}
113
114/// Byte size of an op's variable-length fields plus a small flat per-op
115/// overhead: everything the block encoder copies (payload values, map and
116/// style keys, fractional indexes, root container names, unknown-future
117/// bytes). Arena slices are measured by reference; nothing is copied.
118/// `remaining` is the budget left before the cap; the count may stop early
119/// once it is exceeded.
120fn rich_op_content_bytes(oplog: &crate::OpLog, op: &crate::op::RichOp, remaining: usize) -> usize {
121 const PER_OP_OVERHEAD: usize = 16;
122 if remaining < PER_OP_OVERHEAD {
123 return remaining + 1;
124 }
125
126 // Root container names are variable-length and copied into the encoded
127 // block's container arena.
128 let container_name_len = match oplog.arena.get_container_id(op.raw_op().container) {
129 Some(ContainerID::Root { name, .. }) => name.len(),
130 _ => 0,
131 };
132 let after_fixed = remaining.saturating_sub(PER_OP_OVERHEAD + container_name_len);
133
134 PER_OP_OVERHEAD
135 + container_name_len
136 + match &op.raw_op().content {
137 crate::op::InnerContent::Map(map) => {
138 let mut used = map.key.len();
139 if let Some(value) = map.value.as_ref() {
140 used = used.saturating_add(value_bytes_capped(
141 value,
142 after_fixed.saturating_sub(used),
143 ));
144 }
145 used
146 }
147 crate::op::InnerContent::List(list) => match list {
148 InnerListOp::Insert { slice, .. } => {
149 let mut used = 0usize;
150 for value in slice.as_slice() {
151 used = used.saturating_add(value_bytes_capped(
152 value,
153 after_fixed.saturating_sub(used),
154 ));
155 if used > after_fixed {
156 break;
157 }
158 }
159 used
160 }
161 InnerListOp::InsertText { slice, .. } => slice.len(),
162 InnerListOp::Set { value, .. } => value_bytes_capped(value, after_fixed),
163 InnerListOp::StyleStart { key, value, .. } => {
164 let mut used = key.len();
165 used = used.saturating_add(value_bytes_capped(
166 value,
167 after_fixed.saturating_sub(used),
168 ));
169 used
170 }
171 _ => 0,
172 },
173 // Fractional indexes are variable-length and copied by the encoder.
174 crate::op::InnerContent::Tree(tree_op) => match tree_op.as_ref() {
175 crate::container::tree::tree_op::TreeOp::Create { position, .. }
176 | crate::container::tree::tree_op::TreeOp::Move { position, .. } => {
177 position.as_bytes().len()
178 }
179 crate::container::tree::tree_op::TreeOp::Delete { .. } => 0,
180 },
181 crate::op::InnerContent::Future(future) => match future {
182 crate::op::FutureInnerContent::Unknown { value, .. } => {
183 owned_value_bytes_capped(value, after_fixed)
184 }
185 #[cfg(feature = "counter")]
186 crate::op::FutureInnerContent::Counter(_) => 0,
187 },
188 }
189}
190
191/// Byte size of an owned future/unknown value, recursing where the payload is
192/// a `LoroValue`. `remaining` is the budget left before the cap.
193fn owned_value_bytes_capped(value: &crate::encoding::value::OwnedValue, remaining: usize) -> usize {
194 use crate::encoding::value::OwnedValue;
195 const OVERHEAD: usize = 16;
196 if remaining < OVERHEAD {
197 return remaining + 1;
198 }
199
200 match value {
201 OwnedValue::Str(s) => OVERHEAD.saturating_add(s.len()),
202 OwnedValue::Binary(b) => OVERHEAD.saturating_add(b.len()),
203 OwnedValue::LoroValue(v) => OVERHEAD.saturating_add(value_bytes_capped(v, remaining)),
204 // The encoder writes the mark key into the block's key register and
205 // recurses into the value; both are variable-length.
206 OwnedValue::MarkStart(mark) => {
207 let mut used = OVERHEAD.saturating_add(mark.key.len());
208 used = used.saturating_add(value_bytes_capped(
209 &mark.value,
210 remaining.saturating_sub(used),
211 ));
212 used
213 }
214 // The encoder recurses into the set value.
215 OwnedValue::ListSet { value, .. } => {
216 OVERHEAD.saturating_add(value_bytes_capped(value, remaining))
217 }
218 OwnedValue::Future(owned) => match owned {
219 crate::encoding::value::OwnedFutureValue::Unknown { data, .. } => {
220 OVERHEAD.saturating_add(data.len())
221 }
222 },
223 // TreeMove/RawTreeMove/ListMove carry only fixed-size indices; the
224 // fractional-index payloads they point at are small by construction.
225 _ => OVERHEAD,
226 }
227}
228
229/// Byte size of a value, recursing into nested lists and maps (the encoder
230/// writes them recursively, so the estimate must too). `remaining` is the
231/// budget left before the cap; the count may stop early once it is exceeded.
232fn value_bytes_capped(value: &loro_common::LoroValue, remaining: usize) -> usize {
233 const OVERHEAD: usize = 16;
234 if remaining < OVERHEAD {
235 return remaining + 1;
236 }
237
238 let mut used = OVERHEAD;
239 match value {
240 loro_common::LoroValue::String(s) => used = used.saturating_add(s.len()),
241 loro_common::LoroValue::Binary(b) => used = used.saturating_add(b.len()),
242 loro_common::LoroValue::List(list) => {
243 for item in list.iter() {
244 used =
245 used.saturating_add(value_bytes_capped(item, remaining.saturating_sub(used)));
246 if used > remaining {
247 break;
248 }
249 }
250 }
251 loro_common::LoroValue::Map(map) => {
252 for (key, item) in map.iter() {
253 used = used.saturating_add(key.len());
254 if used > remaining {
255 break;
256 }
257 used =
258 used.saturating_add(value_bytes_capped(item, remaining.saturating_sub(used)));
259 if used > remaining {
260 break;
261 }
262 }
263 }
264 _ => {}
265 }
266 used
267}
268
269/// Whether the forward-replay path may be used for the given prefix/tail
270/// shape. The caller still has to require a non-shallow doc whose state is at
271/// the latest version. Extracted as a pure predicate so the gate can be
272/// tested directly.
273fn forward_replay_gate(ops_num: usize, pre_root_ops: usize, pre_root_bytes: usize) -> bool {
274 ops_num >= MIN_RETAINED_OPS_FOR_FORWARD_ROOT_STATE
275 && pre_root_ops <= MAX_PRE_ROOT_OPS_FOR_FORWARD_REPLAY
276 && pre_root_ops <= MAX_PRE_ROOT_TO_RETAINED_OPS_RATIO * ops_num
277 && pre_root_bytes <= MAX_PRE_ROOT_BYTES_FOR_FORWARD_REPLAY
278}
279
280#[tracing::instrument(skip_all)]
281pub(crate) fn export_shallow_snapshot<W: std::io::Write>(
282 doc: &LoroDoc,
283 start_from: &Frontiers,
284 w: &mut W,
285) -> Result<Frontiers, LoroEncodeError> {
286 let (snapshot, start_from) =
287 export_shallow_snapshot_inner(doc, start_from, CachedShallowRoot::Prune)?;
288 _encode_snapshot(&snapshot, w);
289 Ok(start_from)
290}
291
292/// How a shallow export at a doc's own shallow root treats the cached root state.
293#[derive(Clone, Copy, Debug, PartialEq, Eq)]
294pub(crate) enum CachedShallowRoot {
295 /// Drop containers the retention walk does not reach (every export).
296 Prune,
297 /// Reuse the cached root as-is (`LoroDoc::fork`).
298 Verbatim,
299}
300
301pub(crate) fn export_shallow_snapshot_inner(
302 doc: &LoroDoc,
303 start_from: &Frontiers,
304 cached_root: CachedShallowRoot,
305) -> Result<(Snapshot, Frontiers), LoroEncodeError> {
306 let oplog = doc.oplog().lock();
307 let start_from = calc_shallow_doc_start(&oplog, start_from, oplog.frontiers())?;
308 // `root_vv` is the version of the state at the shallow root; `start_vv`
309 // additionally excludes the frontier ops themselves because the retained
310 // history must include them.
311 let root_vv = frontiers_to_vv_for_export(&oplog, &start_from, "export_shallow_snapshot")?;
312 let mut start_vv = root_vv.clone();
313 for id in start_from.iter() {
314 // we need to include the ops in start_from, this can make things easier
315 start_vv.insert(id.peer, id.counter);
316 }
317
318 #[cfg(debug_assertions)]
319 {
320 use crate::dag::Dag;
321 if !start_from.is_empty() {
322 assert!(start_from.len() == 1);
323 let id = start_from.as_single().unwrap();
324 let node = oplog.dag.try_get(id)?.unwrap();
325 if id.counter == node.cnt {
326 let vv = oplog.dag().try_frontiers_to_vv(&node.deps)?.unwrap();
327 assert_eq!(vv, start_vv);
328 } else {
329 let vv = oplog
330 .dag()
331 .try_frontiers_to_vv(&Frontiers::from(id.inc(-1)))?
332 .unwrap();
333 assert_eq!(vv, start_vv);
334 }
335 }
336 }
337
338 loro_common::debug!(
339 "start version vv={:?} frontiers={:?}",
340 &start_vv,
341 &start_from,
342 );
343
344 let latest_frontiers = oplog.frontiers().clone();
345 let state_frontiers = doc.state_frontiers();
346 let is_attached = !doc.is_detached();
347 let oplog_bytes = oplog.export_change_store_from(&start_vv, &start_from);
348 let latest_vv = oplog.vv();
349 let ops_num: usize = latest_vv.sub_iter(&start_vv).map(|x| x.atom_len()).sum();
350 // Pre-encode the pre-root history for the forward-replay path below while
351 // the oplog lock is held. Calling `LoroDoc::export` there instead would
352 // re-enter `with_barrier` and violate the txn lock order. Shallow docs are
353 // excluded: their pre-root history is trimmed, so forward replay from
354 // empty cannot reconstruct the root state. Small retained ranges are
355 // excluded too: the checkout path is then cheap and peaks at far less
356 // memory (see MIN_RETAINED_OPS_FOR_FORWARD_ROOT_STATE). The prefix itself
357 // is bounded absolutely and relative to the tail, because this path pays
358 // for replaying all of it while the checkout path only walks the tail.
359 let pre_root_ops: usize = root_vv
360 .values()
361 .map(|counter| (*counter).max(0) as usize)
362 .sum();
363 // Cheap op-count legs first (even the estimate walks the prefix's ops, so
364 // it must not run for the small-tail cases the checkout path handles
365 // best). The byte leg runs BEFORE encoding: the estimate follows arena
366 // slices by reference, while export_fast_updates_in_range would
367 // slice-copy every value into a fresh store — the very allocation the cap
368 // exists to prevent.
369 let pre_root_updates = (state_frontiers == latest_frontiers
370 && oplog.shallow_since_vv().is_empty()
371 && forward_replay_gate(ops_num, pre_root_ops, 0))
372 .then(|| {
373 let spans: Vec<IdSpan> = root_vv
374 .iter()
375 .filter(|(_, counter)| **counter > 0)
376 .map(|(peer, counter)| IdSpan::new(*peer, 0, *counter))
377 .collect();
378 if estimate_ops_content_bytes(&oplog, &spans, MAX_PRE_ROOT_BYTES_FOR_FORWARD_REPLAY)
379 > MAX_PRE_ROOT_BYTES_FOR_FORWARD_REPLAY
380 {
381 return None;
382 }
383
384 Some(export_fast_updates_in_range(&oplog, &spans))
385 })
386 .flatten();
387 if &start_from == oplog.shallow_since_frontiers() && state_frontiers == latest_frontiers {
388 let mut state = doc.app_state().lock();
389 if let Some(shallow_root) = state.store.shallow_root_store().cloned() {
390 let (mut shallow_root_state_bytes, shallow_root_kv) =
391 state.store.shallow_root_state_for_export().unwrap();
392 // The cached root may come from an older exporter that kept
393 // containers deleted before the root, so filter it with the same
394 // retention rule the other paths use instead of trusting its key
395 // set. The root never changes, so the result is computed once.
396 // A root the walk cannot judge (an inconsistent parent header, or
397 // a state that does not decode) is kept verbatim, as exporters
398 // before #1123 did: nothing referenced is dropped, and the export
399 // still succeeds. A fork always copies the root verbatim: it
400 // publishes nothing.
401 if cached_root == CachedShallowRoot::Prune {
402 let pruned = shallow_root.pruned_root.get_or_init(|| {
403 match prune_cached_root(
404 &shallow_root_state_bytes,
405 &shallow_root_kv,
406 &shallow_root.shallow_root_frontiers,
407 &root_vv,
408 ) {
409 Ok(pruned) => pruned,
410 Err(err) => {
411 tracing::warn!(
412 ?err,
413 "cached shallow root cannot be checked; exporting it verbatim"
414 );
415 None
416 }
417 }
418 });
419 if let Some(pruned) = pruned {
420 for key in &pruned.removed {
421 shallow_root_kv.remove(key);
422 }
423 shallow_root_state_bytes = pruned.state_bytes.clone();
424 }
425 }
426
427 // Ops since the root are few enough to replay on import; otherwise
428 // also ship the encoded latest state as an overlay.
429 let overlay_kv = if ops_num > MAX_OPS_NUM_TO_ENCODE_WITHOUT_LATEST_STATE {
430 let mut alive_c_bytes = shallow_root_kv.keys();
431 if has_unknown_container_key(alive_c_bytes.iter()) {
432 return Err(LoroEncodeError::UnknownContainer);
433 }
434
435 state.ensure_all_alive_containers()?;
436 state.store.flush();
437
438 retain_created_after_root(&mut state, &root_vv, &mut alive_c_bytes);
439
440 let new_kv = state.store.get_kv_clone();
441 new_kv.remove_same(&shallow_root_kv);
442 new_kv.retain_keys(&alive_c_bytes);
443 Some(new_kv)
444 } else {
445 None
446 };
447
448 // The stored shallow-root bytes may predate dead-style redaction
449 // (e.g. imported from an older export), so re-run it before reuse.
450 let shallow_root_state_bytes =
451 if redact_export_states(&shallow_root_kv, overlay_kv.as_ref())? {
452 // The cloned root kv has no FRONTIERS_KEY (InnerStore::decode
453 // strips it on import); restore it before export.
454 shallow_root_kv.insert(FRONTIERS_KEY, start_from.encode().into());
455 shallow_root_kv.export()
456 } else {
457 shallow_root_state_bytes
458 };
459
460 return Ok((
461 Snapshot {
462 oplog_bytes,
463 state_bytes: overlay_kv.map(|kv| kv.export()),
464 shallow_root_state_bytes,
465 },
466 start_from,
467 ));
468 }
469 }
470 drop(oplog);
471 let result = (|| -> Result<Snapshot, LoroEncodeError> {
472 if let Some(pre_root_updates) = pre_root_updates {
473 // The live state is already at the latest version: build the root
474 // state by replaying pre-root history forward into a temporary doc
475 // instead of checking the live doc out backwards. A reverse
476 // checkout (latest -> root) makes the diff calculators rebuild a
477 // full CRDT tracker from empty for every list-like container
478 // touched in the range (the `should_rebuild` path in
479 // `RichtextDiffCalculator::calculate_diff`), which costs orders of
480 // magnitude more than forward replay when the doc has many small
481 // containers. Forward replay also leaves the live doc untouched,
482 // so no state restore is needed.
483 let root_doc = LoroDoc::new();
484 root_doc
485 .import(&pre_root_updates)
486 .map_err(LoroEncodeError::from)?;
487 let mut root_state = root_doc.app_state().lock();
488 // The replay doc does not share the live doc's deleted-root set;
489 // without it a root container deleted before the root would be
490 // re-encoded as an empty entry instead of being dropped at flush.
491 // (`InnerStore::flush` only drops the entry when the value is
492 // still empty, so roots deleted *after* the root keep their
493 // at-root content even with the set mirrored.)
494 *root_state.config.deleted_root_containers.lock() =
495 doc.config().deleted_root_containers.lock().clone();
496 // Root containers exist on the live doc once they are accessed,
497 // even when they have no ops; the replay doc cannot know about
498 // those. Mirror the live store's root entries so the exported root
499 // state ships the same empty root containers the checkout path
500 // would. `existing_retention_roots` is a root-only key scan — a
501 // full `load_all` here would defeat lazily imported docs.
502 {
503 let mut live_state = doc.app_state().lock();
504 for idx in live_state.existing_retention_roots() {
505 let cid = live_state.arena.get_container_id(idx).unwrap();
506 root_state.store.ensure_container(&cid);
507 }
508 }
509 let alive_containers = root_state.ensure_all_alive_containers()?;
510 if has_unknown_container(alive_containers.iter().copied()) {
511 return Err(LoroEncodeError::UnknownContainer);
512 }
513 let mut alive_c_bytes = alive_indices_to_bytes(&root_state, &alive_containers);
514 root_state.store.flush();
515 let shallow_root_state_kv = root_state.store.get_kv_clone();
516 drop(root_state);
517
518 let latest_state_kv = {
519 let mut state = doc.app_state().lock();
520 latest_state_overlay_kv(
521 &mut state,
522 ops_num,
523 &root_vv,
524 &shallow_root_state_kv,
525 &mut alive_c_bytes,
526 )?
527 };
528 return encode_shallow_sections(
529 oplog_bytes,
530 &start_from,
531 shallow_root_state_kv,
532 latest_state_kv,
533 alive_c_bytes,
534 );
535 }
536
537 doc._checkout_without_emitting(&start_from, false, false)
538 .map_err(LoroEncodeError::from)?;
539 let mut state = doc.app_state().lock();
540 let alive_containers = state.ensure_all_alive_containers()?;
541 if has_unknown_container(alive_containers.iter().copied()) {
542 return Err(LoroEncodeError::UnknownContainer);
543 }
544 let mut alive_c_bytes = alive_indices_to_bytes(&state, &alive_containers);
545 state.store.flush();
546 let shallow_root_state_kv = state.store.get_kv_clone();
547 drop(state);
548 doc._checkout_without_emitting(&latest_frontiers, false, false)
549 .map_err(LoroEncodeError::from)?;
550 let latest_state_kv = {
551 let mut state = doc.app_state().lock();
552 latest_state_overlay_kv(
553 &mut state,
554 ops_num,
555 &root_vv,
556 &shallow_root_state_kv,
557 &mut alive_c_bytes,
558 )?
559 };
560 encode_shallow_sections(
561 oplog_bytes,
562 &start_from,
563 shallow_root_state_kv,
564 latest_state_kv,
565 alive_c_bytes,
566 )
567 })();
568
569 restore_export_doc_state(doc, &state_frontiers, is_attached)?;
570 doc.drop_pending_events();
571 Ok((result?, start_from))
572}
573
574/// Compute the encoded latest-state overlay shipped alongside the shallow root
575/// when the retained history is too large to replay on import. Containers
576/// created after the root are added to `alive_c_bytes` so both the root
577/// state and the overlay keep them.
578fn latest_state_overlay_kv(
579 state: &mut DocState,
580 ops_num: usize,
581 root_vv: &VersionVector,
582 shallow_root_state_kv: &KvWrapper,
583 alive_c_bytes: &mut BTreeSet<Vec<u8>>,
584) -> Result<Option<KvWrapper>, LoroEncodeError> {
585 if ops_num <= MAX_OPS_NUM_TO_ENCODE_WITHOUT_LATEST_STATE {
586 return Ok(None);
587 }
588
589 state.ensure_all_alive_containers()?;
590 state.store.encode();
591 retain_created_after_root(state, root_vv, alive_c_bytes);
592
593 let new_kv = state.store.get_kv_clone();
594 new_kv.remove_same(shallow_root_state_kv);
595 new_kv.retain_keys(alive_c_bytes);
596 Ok(Some(new_kv))
597}
598
599/// Adds every stored container created after the root (plus every non-normal
600/// container) to `alive_c_bytes`.
601///
602/// `alive_c_bytes` starts as the root state's retention set
603/// (`DocState::ensure_all_alive_containers`), so a container created at or
604/// before the root survives only if that walk reached it. Map/list children
605/// deleted before the root are dropped: a retained op cannot re-attach them.
606/// Tree node metas are not dropped even when the node is deleted, because a
607/// retained op can revive the node; the retention walk includes them.
608fn retain_created_after_root(
609 state: &mut DocState,
610 root_vv: &VersionVector,
611 alive_c_bytes: &mut BTreeSet<Vec<u8>>,
612) {
613 for cid in state.store.iter_all_container_ids() {
614 if let ContainerID::Normal { peer, counter, .. } = cid {
615 if !root_vv.includes_id(ID::new(peer, counter)) {
616 alive_c_bytes.insert(cid.to_bytes());
617 }
618 } else {
619 alive_c_bytes.insert(cid.to_bytes());
620 }
621 }
622}
623
624/// Filters a cached shallow root state with the retention walk, returning the
625/// pruned state, or `None` when nothing has to be removed.
626///
627/// Runs on a scratch doc so the live doc's arena and store are untouched. The
628/// cheap `DocState::unreached_stored_containers` filter settles the common
629/// case: every stored container is reached, counting placeholders for
630/// containers created after the root as reached. Otherwise the full walk
631/// (`ensure_all_alive_containers`) also runs; its `Err` on an inconsistent root
632/// is returned rather than dropping containers that are still referenced (the
633/// caller then exports the root verbatim), and only keys that both leave
634/// unreached are removed.
635fn prune_cached_root(
636 root_state_bytes: &Bytes,
637 root_kv: &KvWrapper,
638 root_frontiers: &Frontiers,
639 root_vv: &VersionVector,
640) -> Result<Option<PrunedRootState>, LoroEncodeError> {
641 let root_doc = LoroDoc::new();
642 let mut root_state = root_doc.app_state().lock();
643 root_state
644 .store
645 .decode(root_state_bytes.clone())
646 .map_err(LoroEncodeError::from)?;
647 let candidates = root_state.unreached_stored_containers(root_vv)?;
648 if candidates.is_empty() {
649 #[cfg(debug_assertions)]
650 debug_check_nothing_to_prune(root_state_bytes, root_kv, root_vv);
651 return Ok(None);
652 }
653
654 // Remove only what both the filter and the full walk leave unreached: the
655 // walk rejects forged headers the filter cannot judge, and the filter
656 // protects entries the walk cannot see (post-root placeholders, children of
657 // unknown-type containers).
658 let alive = root_state.ensure_all_alive_containers()?;
659 let retained = alive_indices_to_bytes(&root_state, &alive);
660 let removed: Vec<Bytes> = candidates
661 .into_iter()
662 .filter(|key| !retained.contains(&key[..]))
663 .collect();
664 if removed.is_empty() {
665 return Ok(None);
666 }
667
668 for key in &removed {
669 root_kv.remove(key);
670 }
671 root_kv.insert(FRONTIERS_KEY, root_frontiers.encode().into());
672 let state_bytes = root_kv.export();
673 root_kv.remove(FRONTIERS_KEY);
674 Ok(Some(PrunedRootState {
675 state_bytes,
676 removed,
677 }))
678}
679
680/// When the filter finds no candidate, the full walk must not drop anything
681/// either, except post-root placeholders. Only checked when no unknown-type
682/// container is stored: the filter keeps their subtrees, which the walk cannot
683/// see.
684#[cfg(debug_assertions)]
685fn debug_check_nothing_to_prune(
686 root_state_bytes: &Bytes,
687 root_kv: &KvWrapper,
688 root_vv: &VersionVector,
689) {
690 let keys = root_kv.scan_all_keys();
691 if keys
692 .iter()
693 .any(|key| ContainerID::from_bytes(key).is_unknown())
694 {
695 return;
696 }
697 let check_doc = LoroDoc::new();
698 let mut check_state = check_doc.app_state().lock();
699 check_state.store.decode(root_state_bytes.clone()).unwrap();
700 let Ok(alive) = check_state.ensure_all_alive_containers() else {
701 return;
702 };
703 let retained = alive_indices_to_bytes(&check_state, &alive);
704 for key in keys {
705 if retained.contains(&key[..]) {
706 continue;
707 }
708 let ContainerID::Normal { peer, counter, .. } = ContainerID::from_bytes(&key) else {
709 continue;
710 };
711 assert!(
712 !root_vv.includes_id(ID::new(peer, counter)),
713 "cached-root retention filter missed an unretained container"
714 );
715 }
716}
717
718fn encode_shallow_sections(
719 oplog_bytes: Bytes,
720 start_from: &Frontiers,
721 shallow_root_state_kv: KvWrapper,
722 latest_state_kv: Option<KvWrapper>,
723 alive_c_bytes: BTreeSet<Vec<u8>>,
724) -> Result<Snapshot, LoroEncodeError> {
725 shallow_root_state_kv.retain_keys(&alive_c_bytes);
726 redact_export_states(&shallow_root_state_kv, latest_state_kv.as_ref())?;
727 let state_bytes = latest_state_kv.map(|kv| kv.export());
728 shallow_root_state_kv.insert(FRONTIERS_KEY, start_from.encode().into());
729 let shallow_root_state_bytes = shallow_root_state_kv.export();
730
731 Ok(Snapshot {
732 oplog_bytes,
733 state_bytes,
734 shallow_root_state_bytes,
735 })
736}
737
738fn has_unknown_container(mut idxs: impl Iterator<Item = ContainerIdx>) -> bool {
739 idxs.any(|idx| matches!(idx.get_type(), ContainerType::Unknown(_)))
740}
741
742fn has_unknown_container_key<'a>(mut keys: impl Iterator<Item = &'a Vec<u8>>) -> bool {
743 keys.any(|key| ContainerID::from_bytes(key).is_unknown())
744}
745
746/// Nulls the values of rich-text style pairs that are dead in this state (no
747/// text between the anchors). In a document whose history is trimmed at this
748/// state such a pair can never style anything again, but its value would
749/// otherwise ship in the export even though no read API can reach it. See
750/// `context/shallow-snapshot-style-redaction.md`.
751///
752/// Containers are keyed by `ContainerID` bytes whose first byte is the
753/// container type, so the scan stays within the two Text key ranges and blocks
754/// holding other containers are passed through in their compressed form.
755///
756/// Returns the ids of the redacted `StyleStart` ops, or `None` when the KV was
757/// left untouched.
758/// Applies dead-style redaction to the states being exported.
759///
760/// The root state is fully redacted; the optional overlay (the encoded
761/// latest/target state shipped alongside it) only redacts the pairs the root
762/// redacted. Pairs that die *after* the root must keep their values so
763/// checkouts into the retained range still render them — this function is the
764/// single place that protocol lives.
765///
766/// Returns whether the root KV changed. Call before the KVs are exported and
767/// after `remove_same`, so byte-identical entries still dedup (a deduped entry
768/// resolves to the redacted root version on import).
769fn redact_export_states(
770 root: &KvWrapper,
771 overlay: Option<&KvWrapper>,
772) -> Result<bool, LoroEncodeError> {
773 match redact_dead_text_styles(root, None)? {
774 None => Ok(false),
775 Some(redacted) => {
776 if let Some(overlay) = overlay {
777 redact_dead_text_styles(overlay, Some(&redacted))?;
778 }
779 Ok(true)
780 }
781 }
782}
783
784fn redact_dead_text_styles(
785 kv: &KvWrapper,
786 only_pairs: Option<&FxHashSet<ID>>,
787) -> Result<Option<FxHashSet<ID>>, LoroEncodeError> {
788 const ROOT_MARK: u8 = 0b1000_0000;
789 let text_kind = ContainerType::Text.to_u8();
790 debug_assert_eq!(text_kind & ROOT_MARK, 0);
791 let mut redacted: FxHashSet<ID> = FxHashSet::default();
792 let mut changed = false;
793 for first_key_byte in [text_kind, text_kind | ROOT_MARK] {
794 for (key, value) in kv.scan_range_entries(&[first_key_byte], &[first_key_byte + 1]) {
795 if value.is_empty() {
796 continue;
797 }
798 let offset = ContainerWrapper::payload_offset(&value).map_err(LoroEncodeError::from)?;
799 if let Some((payload, ids)) = redact_dead_style_values(&value[offset..], only_pairs)
800 .map_err(LoroEncodeError::from)?
801 {
802 let mut new_value = Vec::with_capacity(offset + payload.len());
803 new_value.extend_from_slice(&value[..offset]);
804 new_value.extend_from_slice(&payload);
805 kv.insert(&key, new_value.into());
806 redacted.extend(ids);
807 changed = true;
808 }
809 }
810 }
811 Ok(changed.then_some(redacted))
812}
813
814pub(crate) fn export_state_only_snapshot<W: std::io::Write>(
815 doc: &LoroDoc,
816 target_frontiers: &Frontiers,
817 w: &mut W,
818) -> Result<Frontiers, LoroEncodeError> {
819 let oplog = doc.oplog().lock();
820 let start_from = calc_shallow_doc_start(&oplog, target_frontiers, target_frontiers)?;
821 let root_vv = frontiers_to_vv_for_export(&oplog, &start_from, "export_state_only_snapshot")?;
822 let mut start_vv = root_vv.clone();
823 for id in start_from.iter() {
824 // we need to include the ops in start_from, this can make things easier
825 start_vv.insert(id.peer, id.counter);
826 }
827
828 loro_common::debug!(
829 "start version vv={:?} frontiers={:?}",
830 &start_vv,
831 &start_from,
832 );
833
834 let to_vv = frontiers_to_vv_for_export(&oplog, target_frontiers, "export_state_only_snapshot")?;
835 let oplog_bytes =
836 oplog.export_change_store_in_range(&start_vv, &start_from, &to_vv, target_frontiers);
837 let state_frontiers = doc.state_frontiers();
838 let is_attached = !doc.is_detached();
839 drop(oplog);
840 let result = (|| -> Result<(), LoroEncodeError> {
841 doc._checkout_without_emitting(&start_from, false, false)
842 .map_err(LoroEncodeError::from)?;
843 let mut state = doc.app_state().lock();
844 let alive_containers = state.ensure_all_alive_containers()?;
845 if has_unknown_container(alive_containers.iter().copied()) {
846 return Err(LoroEncodeError::UnknownContainer);
847 }
848 let mut alive_c_bytes = alive_indices_to_bytes(&state, &alive_containers);
849 state.store.flush();
850 let shallow_state_kv = state.store.get_kv_clone();
851 drop(state);
852
853 doc._checkout_without_emitting(target_frontiers, false, false)
854 .map_err(LoroEncodeError::from)?;
855 let mut state = doc.app_state().lock();
856 state.ensure_all_alive_containers()?;
857 state.store.encode();
858 retain_created_after_root(&mut state, &root_vv, &mut alive_c_bytes);
859
860 let target_state_kv = state.store.get_kv_clone();
861 drop(state);
862 target_state_kv.remove_same(&shallow_state_kv);
863 target_state_kv.retain_keys(&alive_c_bytes);
864
865 shallow_state_kv.retain_keys(&alive_c_bytes);
866 redact_export_states(&shallow_state_kv, Some(&target_state_kv))?;
867 shallow_state_kv.insert(FRONTIERS_KEY, start_from.encode().into());
868 let shallow_state_bytes = shallow_state_kv.export();
869 let snapshot = Snapshot {
870 oplog_bytes,
871 state_bytes: Some(target_state_kv.export()),
872 shallow_root_state_bytes: shallow_state_bytes,
873 };
874 _encode_snapshot(&snapshot, w);
875 Ok(())
876 })();
877
878 restore_export_doc_state(doc, &state_frontiers, is_attached)?;
879 doc.drop_pending_events();
880 result?;
881 Ok(start_from)
882}
883
884fn alive_indices_to_bytes(
885 state: &DocState,
886 alive_containers: &rustc_hash::FxHashSet<ContainerIdx>,
887) -> BTreeSet<Vec<u8>> {
888 alive_containers
889 .iter()
890 .map(|idx| state.arena.get_container_id(*idx).unwrap().to_bytes())
891 .collect()
892}
893
894fn frontiers_to_vv_for_export(
895 oplog: &crate::OpLog,
896 frontiers: &Frontiers,
897 context: &str,
898) -> Result<VersionVector, LoroEncodeError> {
899 oplog.dag().try_frontiers_to_vv(frontiers)?.ok_or_else(|| {
900 LoroEncodeError::FrontiersNotFound(format!(
901 "{context}: unreachable frontiers {frontiers:?}"
902 ))
903 })
904}
905
906fn restore_export_doc_state(
907 doc: &LoroDoc,
908 state_frontiers: &Frontiers,
909 was_attached: bool,
910) -> Result<(), LoroEncodeError> {
911 if &doc.state_frontiers() != state_frontiers {
912 doc._checkout_without_emitting(state_frontiers, false, false)
913 .map_err(LoroEncodeError::from)?;
914 }
915
916 if was_attached {
917 doc.set_detached(false);
918 }
919
920 Ok(())
921}
922
923/// Picks the shallow root for an export at `frontiers`.
924///
925/// The root must be a *critical version* of every op the export retains: each
926/// one is causally before the root or causally after it, never concurrent.
927/// The shallow format stores the state at the root plus every op above it, so
928/// an op concurrent with the root belongs to neither side and the snapshot
929/// cannot be imported (loro-dev/loro#1095). The meet of the heads is not
930/// enough.
931///
932/// `retained_to` is where the retained history ends: the latest version for a
933/// shallow snapshot, `frontiers` itself for a state-only snapshot. It matters
934/// because a branch merged after `frontiers` that forked below it is
935/// concurrent with `frontiers`, so a single-head past version is not a valid
936/// root on its own. See `docs/critical-version-spec.md`.
937fn calc_shallow_doc_start(
938 oplog: &crate::OpLog,
939 frontiers: &Frontiers,
940 retained_to: &Frontiers,
941) -> Result<Frontiers, LoroEncodeError> {
942 if frontiers.is_empty() {
943 return clamp_to_shallow_root(oplog, Frontiers::default());
944 }
945
946 // Single-head or empty: the empty version is the answer when no critical
947 // version exists, e.g. for independent heads with no common history.
948 let root = oplog
949 .dag()
950 .try_latest_single_head_critical_version(frontiers, retained_to)?;
951
952 let mut ans = Frontiers::new();
953 for id in root.iter() {
954 let mut processed = false;
955 if let Some(op) = oplog.get_op_that_includes(id) {
956 if let crate::op::InnerContent::List(InnerListOp::StyleStart { .. }) = &op.content {
957 // StyleStart and StyleEnd operations are kept together in the GC snapshot
958 // when both exist, so we advance the frontier by one step to include both
959 // operations. (Id.counter + 1 is guaranteed to be the StyleEnd Op.)
960 //
961 // When this doc's history ends at the StyleStart, the end op does not
962 // exist here; the root keeps the lone start anchor, which the state
963 // encoding supports (loro-dev/loro#1165).
964 if oplog.vv().includes_id(id.inc(1)) {
965 ans.push(id.inc(1));
966 processed = true;
967 }
968 }
969 }
970
971 if !processed {
972 ans.push(id);
973 }
974 }
975
976 clamp_to_shallow_root(oplog, ans)
977}
978
979fn clamp_to_shallow_root(
980 oplog: &crate::OpLog,
981 frontiers: Frontiers,
982) -> Result<Frontiers, LoroEncodeError> {
983 if oplog.shallow_since_vv().is_empty() {
984 return Ok(frontiers);
985 }
986
987 let Some(vv) = oplog.dag().try_frontiers_to_vv(&frontiers)? else {
988 return Ok(oplog.shallow_since_frontiers().clone());
989 };
990
991 if vv.includes_vv(&oplog.shallow_since_vv().to_vv()) {
992 Ok(frontiers)
993 } else {
994 Ok(oplog.shallow_since_frontiers().clone())
995 }
996}
997
998/// Retains container state required by the exported version.
999///
1000/// The supplied keys retain alive containers and roots. History also needs
1001/// deleted normal containers whose creating operations belong to `version`.
1002/// The scan reads encoded keys without decoding container state. Validation
1003/// completes before the KV store is filtered.
1004///
1005/// # Errors
1006///
1007/// Returns an encoding error for malformed keys or unknown normal containers
1008/// retained by history.
1009fn retain_containers_at_version(
1010 state_kv: &KvWrapper,
1011 mut retained_containers: BTreeSet<Vec<u8>>,
1012 version: &VersionVector,
1013) -> Result<(), LoroEncodeError> {
1014 for key in state_kv.keys() {
1015 let container = ContainerID::try_from_bytes(&key)?;
1016 if let ContainerID::Normal { peer, counter, .. } = container {
1017 if version.includes_id(ID::new(peer, counter)) {
1018 if container.is_unknown() {
1019 return Err(LoroEncodeError::UnknownContainer);
1020 }
1021 retained_containers.insert(key);
1022 }
1023 }
1024 }
1025 state_kv.retain_keys(&retained_containers);
1026 Ok(())
1027}
1028
1029/// Builds the container-state copy required by a full-history snapshot.
1030///
1031/// `state` MUST already represent `version`.
1032/// The returned copy retains alive containers and deleted normal containers
1033/// required by the retained history.
1034///
1035/// # Errors
1036///
1037/// Returns an encoding error for invalid container state, malformed keys,
1038/// or unsupported retained containers.
1039fn prepare_snapshot_container_state(
1040 state: &mut DocState,
1041 version: &VersionVector,
1042) -> Result<KvWrapper, LoroEncodeError> {
1043 let alive_containers = state.ensure_all_alive_containers()?;
1044 if has_unknown_container(alive_containers.iter().copied()) {
1045 return Err(LoroEncodeError::UnknownContainer);
1046 }
1047
1048 let alive_container_keys = alive_indices_to_bytes(state, &alive_containers);
1049 state.store.flush();
1050 let state_kv = state.store.get_kv_clone();
1051 retain_containers_at_version(&state_kv, alive_container_keys, version)?;
1052 Ok(state_kv)
1053}
1054
1055pub(crate) fn encode_snapshot_at<W: std::io::Write>(
1056 doc: &LoroDoc,
1057 frontiers: &Frontiers,
1058 w: &mut W,
1059) -> Result<(), LoroEncodeError> {
1060 let was_detached = doc.is_detached();
1061 let version_before_start = doc.state_frontiers().clone();
1062 doc._checkout_without_emitting(frontiers, true, false)
1063 .map_err(LoroEncodeError::from)?;
1064 let result = 'block: {
1065 let oplog = doc.oplog().lock();
1066 let mut state = doc.app_state().lock();
1067 let is_shallow = state.store.shallow_root_store().is_some();
1068 if is_shallow {
1069 break 'block Err(LoroEncodeError::from(LoroError::NotImplemented(
1070 "fork_at on shallow docs",
1071 )));
1072 }
1073
1074 if state.is_in_txn() {
1075 break 'block Err(LoroEncodeError::internal(
1076 "encode_snapshot_at: state is unexpectedly still in a transaction",
1077 ));
1078 }
1079 let oplog_bytes = match oplog.fork_changes_up_to(frontiers) {
1080 Ok(bytes) => bytes,
1081 Err(err) => break 'block Err(err.into()),
1082 };
1083 let Some(oplog_bytes) = oplog_bytes else {
1084 break 'block Err(LoroEncodeError::FrontiersNotFound(format!(
1085 "frontiers: {:?} when export in SnapshotAt mode",
1086 frontiers
1087 )));
1088 };
1089
1090 if oplog.is_shallow() {
1091 let Some(shallow_root_frontiers) = state.store.shallow_root_frontiers() else {
1092 break 'block Err(LoroEncodeError::internal(
1093 "encode_snapshot_at: shallow oplog is missing shallow root frontiers",
1094 ));
1095 };
1096 if oplog.shallow_since_frontiers() != shallow_root_frontiers {
1097 break 'block Err(LoroEncodeError::internal(
1098 "encode_snapshot_at: shallow root frontiers are inconsistent",
1099 ));
1100 }
1101 }
1102
1103 let version = match oplog.dag.try_frontiers_to_vv(frontiers) {
1104 Ok(version) => version,
1105 Err(err) => break 'block Err(err.into()),
1106 };
1107 let Some(version) = version else {
1108 break 'block Err(LoroEncodeError::FrontiersNotFound(format!(
1109 "frontiers: {:?} when export in SnapshotAt mode",
1110 frontiers
1111 )));
1112 };
1113 let state_kv = match prepare_snapshot_container_state(&mut state, &version) {
1114 Ok(state_kv) => state_kv,
1115 Err(error) => break 'block Err(error),
1116 };
1117 let bytes = state_kv.export();
1118 _encode_snapshot(
1119 &Snapshot {
1120 oplog_bytes,
1121 state_bytes: Some(bytes),
1122 shallow_root_state_bytes: Bytes::new(),
1123 },
1124 w,
1125 );
1126
1127 Ok(())
1128 };
1129 let restore_result = doc
1130 ._checkout_without_emitting(&version_before_start, false, false)
1131 .map_err(LoroEncodeError::from);
1132 doc.set_detached(was_detached);
1133 doc.app_state().lock().take_events();
1134
1135 match result {
1136 Err(err) => Err(err),
1137 Ok(()) => restore_result,
1138 }
1139}
1140
1141#[cfg(test)]
1142mod tests {
1143 use super::*;
1144 use crate::configure::Configure;
1145 use crate::container::idx::ContainerIdx;
1146 use crate::container::richtext::richtext_state::{PosType, RichtextStateChunk};
1147 use crate::container::richtext::AnchorType;
1148 use crate::encoding::fast_snapshot::_decode_snapshot_bytes;
1149 use crate::encoding::EncodeMode;
1150 use crate::encoding::ExportMode;
1151 use crate::handler::MapHandler;
1152 use crate::handler::TextHandler;
1153 use crate::state::{ContainerCreationContext, FastStateSnapshot, RichtextState};
1154 use crate::HandlerTrait;
1155 use crate::LoroDoc;
1156 use loro_common::LoroValue;
1157
1158 fn shallow_sections(blob: &[u8]) -> Snapshot {
1159 let parsed = crate::encoding::parse_header_and_body(blob, true).unwrap();
1160 _decode_snapshot_bytes(Bytes::copy_from_slice(parsed.body)).unwrap()
1161 }
1162
1163 /// Reassemble decomposed sections into a complete importable blob
1164 /// (magic + checksum + mode header, matching `encode_with`).
1165 fn assemble_snapshot_blob(sections: &Snapshot) -> Vec<u8> {
1166 let mut blob = Vec::new();
1167 blob.extend(crate::encoding::MAGIC_BYTES);
1168 blob.extend([0u8; 16]);
1169 blob.extend(EncodeMode::FastSnapshot.to_bytes());
1170 _encode_snapshot(sections, &mut blob);
1171 let checksum = xxhash_rust::xxh32::xxh32(&blob[20..], crate::encoding::XXH_SEED);
1172 blob[16..20].copy_from_slice(&checksum.to_le_bytes());
1173 blob
1174 }
1175
1176 #[test]
1177 fn snapshot_at_alive_walk_error_restores_source() {
1178 let document = LoroDoc::new_auto_commit();
1179 document.set_peer_id(42).unwrap();
1180 let child = document
1181 .get_map("parent-a")
1182 .insert_container("child", MapHandler::new_detached())
1183 .unwrap();
1184 child.insert("value", 1).unwrap();
1185 document.commit_then_renew();
1186 let target = document.oplog_frontiers();
1187 document.get_map("unrelated").insert("later", 2).unwrap();
1188 document.commit_then_renew();
1189 let head = document.oplog_frontiers();
1190 let mut sections = shallow_sections(&document.export(ExportMode::Snapshot).unwrap());
1191 let state = crate::utils::kv_wrapper::KvWrapper::new_mem();
1192 state.import(sections.state_bytes.take().unwrap()).unwrap();
1193
1194 let other = LoroDoc::new_auto_commit();
1195 other.set_peer_id(42).unwrap();
1196 let other_child = other
1197 .get_map("parent-b")
1198 .insert_container("child", MapHandler::new_detached())
1199 .unwrap();
1200 other_child.insert("value", 1).unwrap();
1201 assert_eq!(child.id(), other_child.id());
1202 let other_sections = shallow_sections(&other.export(ExportMode::Snapshot).unwrap());
1203 let other_state = crate::utils::kv_wrapper::KvWrapper::new_mem();
1204 other_state
1205 .import(other_sections.state_bytes.unwrap())
1206 .unwrap();
1207 let child_key = child.id().to_bytes();
1208 state.insert(&child_key, other_state.get(&child_key).unwrap());
1209 sections.state_bytes = Some(state.export());
1210 let snapshot = assemble_snapshot_blob(&sections);
1211
1212 for detached in [false, true] {
1213 let imported = LoroDoc::new_auto_commit();
1214 imported.import(&snapshot).unwrap();
1215 if detached {
1216 imported.detach();
1217 }
1218 let unaffected = imported.get_map("unrelated").get_value();
1219 let error = imported
1220 .export(ExportMode::SnapshotAt {
1221 version: std::borrow::Cow::Borrowed(&target),
1222 })
1223 .unwrap_err();
1224 assert!(error.to_string().contains("snapshot state encodes parent"));
1225 assert_eq!(imported.state_frontiers(), head);
1226 assert_eq!(imported.is_detached(), detached);
1227 assert_eq!(imported.get_map("unrelated").get_value(), unaffected);
1228 }
1229 }
1230
1231 /// Decode the style values of a text container straight out of exported
1232 /// state KV bytes, so assertions don't depend on whether the secret is
1233 /// visible through LZ4 compression.
1234 fn text_style_values(kv_bytes: &Bytes, cid: &ContainerID) -> Vec<(ID, LoroValue)> {
1235 let kv = KvWrapper::new_mem();
1236 kv.import(kv_bytes.clone()).unwrap();
1237 let value = kv
1238 .get(&cid.to_bytes())
1239 .expect("text container should be present in the exported state");
1240 let offset = ContainerWrapper::payload_offset(&value).unwrap();
1241 let (text, rest) = RichtextState::decode_value(&value[offset..]).unwrap();
1242 let idx = ContainerIdx::from_index_and_type(0, ContainerType::Text);
1243 let configure = Configure::default();
1244 let ctx = ContainerCreationContext {
1245 configure: &configure,
1246 peer: 0,
1247 };
1248 let state = RichtextState::decode_snapshot_fast(idx, (text, rest), ctx).unwrap();
1249 let mut styles = Vec::new();
1250 state.iter_raw(&mut |chunk| {
1251 if let RichtextStateChunk::Style {
1252 style,
1253 anchor_type: AnchorType::Start,
1254 } = chunk
1255 {
1256 styles.push((ID::new(style.peer, style.cnt), style.value.clone()));
1257 }
1258 });
1259 styles
1260 }
1261
1262 fn root_text_cid() -> ContainerID {
1263 ContainerID::new_root("text", ContainerType::Text)
1264 }
1265
1266 #[test]
1267 fn shallow_export_nulls_dead_style_values_for_root_and_nested_text() {
1268 let doc = LoroDoc::new_auto_commit();
1269 doc.set_peer_id(1).unwrap();
1270 let root_text = doc.get_text("text");
1271 root_text.insert(0, "abc", PosType::Unicode).unwrap();
1272 root_text
1273 .mark(0, 3, "comment", "root-secret".into(), PosType::Unicode)
1274 .unwrap();
1275 let nested_text = doc
1276 .get_map("meta")
1277 .insert_container("note", TextHandler::new_detached())
1278 .unwrap();
1279 nested_text.insert(0, "xyz", PosType::Unicode).unwrap();
1280 nested_text
1281 .mark(0, 3, "comment", "nested-secret".into(), PosType::Unicode)
1282 .unwrap();
1283 doc.commit_then_renew();
1284 root_text.delete(0, 3, PosType::Unicode).unwrap();
1285 nested_text.delete(0, 3, PosType::Unicode).unwrap();
1286 doc.commit_then_renew();
1287
1288 let blob = doc
1289 .export(ExportMode::shallow_snapshot(&doc.oplog_frontiers()))
1290 .unwrap();
1291 let sections = shallow_sections(&blob);
1292
1293 for cid in [root_text_cid(), nested_text.id()] {
1294 let styles = text_style_values(&sections.shallow_root_state_bytes, &cid);
1295 assert_eq!(styles.len(), 1, "container {cid}");
1296 assert_eq!(styles[0].1, LoroValue::Null, "container {cid}");
1297 }
1298 }
1299
1300 #[test]
1301 fn overlay_keeps_style_values_that_die_after_the_root() {
1302 let doc = LoroDoc::new_auto_commit();
1303 doc.set_peer_id(1).unwrap();
1304 let text = doc.get_text("text");
1305 text.insert(0, "hello", PosType::Unicode).unwrap();
1306 text.mark(0, 5, "comment", "keep-me".into(), PosType::Unicode)
1307 .unwrap();
1308 doc.commit_then_renew();
1309 let start = doc.oplog_frontiers();
1310
1311 // The style dies after the shallow root...
1312 text.delete(0, 5, PosType::Unicode).unwrap();
1313 // ...and enough tail ops force the export to carry the latest state.
1314 let filler = doc.get_map("filler");
1315 for i in 0..(MAX_OPS_NUM_TO_ENCODE_WITHOUT_LATEST_STATE + 1) {
1316 filler.insert(&i.to_string(), i as i64).unwrap();
1317 }
1318 doc.commit_then_renew();
1319
1320 let blob = doc.export(ExportMode::shallow_snapshot(&start)).unwrap();
1321 let sections = shallow_sections(&blob);
1322 let state_bytes = sections
1323 .state_bytes
1324 .expect("overlay state should be encoded");
1325
1326 let cid = root_text_cid();
1327 let keep = LoroValue::String("keep-me".into());
1328 assert_eq!(
1329 text_style_values(&sections.shallow_root_state_bytes, &cid)[0].1,
1330 keep,
1331 "style alive at the root must keep its value"
1332 );
1333 // The pair is dead in the latest state but was alive at the root, so a
1334 // checkout back into the retained range must still render it.
1335 assert_eq!(text_style_values(&state_bytes, &cid)[0].1, keep);
1336 }
1337
1338 #[test]
1339 fn overlay_redacts_pairs_dead_at_the_root() {
1340 let doc = LoroDoc::new_auto_commit();
1341 doc.set_peer_id(1).unwrap();
1342 let text = doc.get_text("text");
1343 text.insert(0, "abc", PosType::Unicode).unwrap();
1344 text.mark(0, 3, "comment", "dead-secret".into(), PosType::Unicode)
1345 .unwrap();
1346 doc.commit_then_renew();
1347 text.delete(0, 3, PosType::Unicode).unwrap();
1348 doc.commit_then_renew();
1349 let start = doc.oplog_frontiers();
1350
1351 // Make the latest text entry differ from the root entry so it survives
1352 // `remove_same` and must be redacted via the root's pair whitelist.
1353 text.insert(0, "later", PosType::Unicode).unwrap();
1354 let filler = doc.get_map("filler");
1355 for i in 0..(MAX_OPS_NUM_TO_ENCODE_WITHOUT_LATEST_STATE + 1) {
1356 filler.insert(&i.to_string(), i as i64).unwrap();
1357 }
1358 doc.commit_then_renew();
1359
1360 let blob = doc.export(ExportMode::shallow_snapshot(&start)).unwrap();
1361 let sections = shallow_sections(&blob);
1362 let cid = root_text_cid();
1363 assert_eq!(
1364 text_style_values(&sections.shallow_root_state_bytes, &cid)[0].1,
1365 LoroValue::Null
1366 );
1367 let state_bytes = sections
1368 .state_bytes
1369 .expect("overlay state should be encoded");
1370 assert_eq!(text_style_values(&state_bytes, &cid)[0].1, LoroValue::Null);
1371 }
1372
1373 #[test]
1374 fn legacy_unredacted_shallow_blob_is_cleaned_on_reexport() {
1375 let doc = LoroDoc::new_auto_commit();
1376 doc.set_peer_id(1).unwrap();
1377 let text = doc.get_text("text");
1378 text.insert(0, "abc", PosType::Unicode).unwrap();
1379 text.mark(0, 3, "comment", "legacy-secret".into(), PosType::Unicode)
1380 .unwrap();
1381 doc.commit_then_renew();
1382 text.delete(0, 3, PosType::Unicode).unwrap();
1383 doc.commit_then_renew();
1384
1385 let blob = doc
1386 .export(ExportMode::shallow_snapshot(&doc.oplog_frontiers()))
1387 .unwrap();
1388 let mut sections = shallow_sections(&blob);
1389
1390 // Rebuild the root state the way pre-redaction exports encoded it: the
1391 // doc's own state at the tip still holds the secret value.
1392 let unredacted_root = {
1393 let mut state = doc.app_state().lock();
1394 state.store.flush();
1395 let kv = state.store.get_kv_clone();
1396 drop(state);
1397 kv.insert(FRONTIERS_KEY, doc.oplog_frontiers().encode().into());
1398 kv.export()
1399 };
1400 let cid = root_text_cid();
1401 assert_eq!(
1402 text_style_values(&unredacted_root, &cid)[0].1,
1403 LoroValue::String("legacy-secret".into()),
1404 "test setup must produce an unredacted legacy root"
1405 );
1406 sections.shallow_root_state_bytes = unredacted_root;
1407
1408 // Import the legacy-shaped blob; re-exporting must clean the stored
1409 // root bytes on the reuse branch.
1410 let legacy_doc = LoroDoc::new();
1411 legacy_doc
1412 .import(&assemble_snapshot_blob(&sections))
1413 .unwrap();
1414 let reexported = legacy_doc
1415 .export(ExportMode::shallow_snapshot(&legacy_doc.oplog_frontiers()))
1416 .unwrap();
1417 let resections = shallow_sections(&reexported);
1418 assert_eq!(
1419 text_style_values(&resections.shallow_root_state_bytes, &cid)[0].1,
1420 LoroValue::Null
1421 );
1422 }
1423
1424 /// Regression test for the P1 found in review of the bounded container
1425 /// value cache (loro-dev/loro#1092): after a shallow-snapshot import the
1426 /// store is `AllLoaded`, and a container walk evicts most decoded values.
1427 /// Re-exporting the same shallow root must still enumerate every container
1428 /// created after the root — otherwise the latest-state overlay silently
1429 /// drops the evicted ones and the next import loses them.
1430 #[test]
1431 fn reexport_same_shallow_root_after_walk_eviction_keeps_overlay_containers() {
1432 // Doc A: base content behind the shallow root.
1433 let a = LoroDoc::new_auto_commit();
1434 a.set_peer_id(1).unwrap();
1435 a.get_text("text")
1436 .insert(0, "base", PosType::Unicode)
1437 .unwrap();
1438 a.commit_then_renew();
1439 let start = a.oplog_frontiers();
1440
1441 // Doc B: import the shallow snapshot, then create containers that live
1442 // only in the latest-state overlay (they are not in the root KV).
1443 let b = LoroDoc::new_auto_commit();
1444 b.set_peer_id(2).unwrap();
1445 b.import(&a.export(ExportMode::shallow_snapshot(&start)).unwrap())
1446 .unwrap();
1447 let n = 64;
1448 let list = b.get_list("list");
1449 for i in 0..n {
1450 let map = list
1451 .insert_container(i, MapHandler::new_detached())
1452 .unwrap();
1453 map.insert("key", i as i64).unwrap();
1454 }
1455 b.commit_then_renew();
1456 // 2 ops per container > MAX_OPS_NUM_TO_ENCODE_WITHOUT_LATEST_STATE
1457 // (16 in test builds), so this export ships the latest-state overlay.
1458 let blob = b.export(ExportMode::shallow_snapshot(&start)).unwrap();
1459
1460 // Doc C imports the blob (store is AllLoaded with lazy wrappers) and
1461 // walks every overlay container, evicting most of them from the
1462 // bounded value cache.
1463 let c = LoroDoc::new_auto_commit();
1464 c.import(&blob).unwrap();
1465 let list = c.get_list("list");
1466 for i in 0..n {
1467 let child_id = list.get(i).unwrap().as_container().unwrap().clone();
1468 assert_eq!(c.get_map(child_id).get("key"), Some((i as i64).into()));
1469 }
1470
1471 // Re-exporting the same shallow root reuses the stored root bytes and
1472 // rebuilds the overlay by enumerating all containers. With the broken
1473 // `load_all` short-circuit this dropped every evicted container.
1474 let reexported = c.export(ExportMode::shallow_snapshot(&start)).unwrap();
1475 assert!(
1476 shallow_sections(&reexported).state_bytes.is_some(),
1477 "test setup must take the overlay export path"
1478 );
1479
1480 let d = LoroDoc::new_auto_commit();
1481 d.import(&reexported).unwrap();
1482 let list = d.get_list("list");
1483 assert_eq!(list.len(), n);
1484 for i in 0..n {
1485 let child_id = list
1486 .get(i)
1487 .unwrap_or_else(|| panic!("container {i} lost after shallow re-export"))
1488 .as_container()
1489 .unwrap()
1490 .clone();
1491 assert_eq!(d.get_map(child_id).get("key"), Some((i as i64).into()));
1492 }
1493 }
1494
1495 #[test]
1496 fn forward_replay_gate_bounds_prefix_by_ops_ratio_and_bytes() {
1497 let min = MIN_RETAINED_OPS_FOR_FORWARD_ROOT_STATE;
1498 let max_ops = MAX_PRE_ROOT_OPS_FOR_FORWARD_REPLAY;
1499 let max_bytes = MAX_PRE_ROOT_BYTES_FOR_FORWARD_REPLAY;
1500
1501 // Tail below the minimum: never.
1502 assert!(!forward_replay_gate(min - 1, 0, 0));
1503 // Balanced prefix/tail: allowed.
1504 assert!(forward_replay_gate(min, min, 1));
1505 // Prefix larger than 16x the tail: blocked even though both op counts
1506 // are small.
1507 assert!(!forward_replay_gate(min, 17 * min, 1));
1508 // Prefix above the absolute op cap: blocked.
1509 assert!(!forward_replay_gate(max_ops, max_ops + 1, 1));
1510 // A byte-heavy but low-op prefix (a Map write is one atom regardless
1511 // of value size): blocked only by the byte leg.
1512 assert!(!forward_replay_gate(min, 1, max_bytes + 1));
1513 assert!(forward_replay_gate(min, 1, max_bytes));
1514 }
1515
1516 /// A byte-heavy, low-op prefix (a huge payload nested inside a Map value,
1517 /// later overwritten) must not be replayed into a temporary doc just
1518 /// because the tail clears the retained-ops threshold. The export must
1519 /// still be correct.
1520 #[test]
1521 fn byte_heavy_low_op_prefix_exports_correctly() {
1522 let doc = LoroDoc::new_auto_commit();
1523 doc.set_peer_id(1).unwrap();
1524 let map = doc.get_map("m");
1525 let big = "v".repeat(MAX_PRE_ROOT_BYTES_FOR_FORWARD_REPLAY + 1024);
1526 // Nested one level down: the estimator must recurse into it.
1527 let mut payload = crate::FxHashMap::default();
1528 payload.insert("payload".to_string(), LoroValue::String(big.into()));
1529 map.insert("k", LoroValue::Map(payload.into())).unwrap();
1530 map.insert("k", "small").unwrap();
1531 doc.commit_then_renew();
1532 let f = doc.oplog_frontiers();
1533 // Tail just past the (test-scale) retained-ops threshold.
1534 let text = doc.get_text("t");
1535 text.insert(
1536 0,
1537 &"x".repeat(MIN_RETAINED_OPS_FOR_FORWARD_ROOT_STATE + 1),
1538 PosType::Unicode,
1539 )
1540 .unwrap();
1541 doc.commit_then_renew();
1542
1543 let blob = doc.export(ExportMode::shallow_snapshot(&f)).unwrap();
1544 let imported = LoroDoc::new();
1545 imported.import(&blob).unwrap();
1546 assert_eq!(imported.get_deep_value(), doc.get_deep_value());
1547 assert_eq!(imported.shallow_since_frontiers(), f);
1548 }
1549
1550 #[test]
1551 fn prefix_content_bytes_estimate_counts_value_bytes() {
1552 let doc = LoroDoc::new_auto_commit();
1553 doc.set_peer_id(1).unwrap();
1554 // One atom carrying 2 MiB of payload.
1555 let big = "v".repeat(2 << 20);
1556 doc.get_map("m").insert("k", big.as_str()).unwrap();
1557 doc.get_text("t")
1558 .insert(0, "abc", PosType::Unicode)
1559 .unwrap();
1560 doc.commit_then_renew();
1561
1562 let oplog = doc.oplog().lock();
1563 let spans = vec![IdSpan::new(1, 0, 4)];
1564 let est = estimate_ops_content_bytes(&oplog, &spans, usize::MAX);
1565 assert!(
1566 est >= (2 << 20) + 3,
1567 "estimate must include the value bytes, got {est}"
1568 );
1569 // Early exit: a smaller cap stops the walk as soon as it is exceeded.
1570 let capped = estimate_ops_content_bytes(&oplog, &spans, 1024);
1571 assert!(capped > 1024 && capped <= 1024 + (2 << 20) + 64);
1572 }
1573
1574 #[test]
1575 fn prefix_content_bytes_estimate_counts_nested_style_and_commit_msg_bytes() {
1576 let doc = LoroDoc::new_auto_commit();
1577 doc.set_peer_id(1).unwrap();
1578 let big = "v".repeat(1 << 20);
1579
1580 // One atom whose payload is a nested map/list holding the big string.
1581 let mut inner = crate::FxHashMap::default();
1582 inner.insert("payload".to_string(), LoroValue::String(big.clone().into()));
1583 let nested = LoroValue::List(vec![LoroValue::Map(inner.into())].into());
1584 doc.get_map("m").insert("k", nested).unwrap();
1585
1586 // A style mark value.
1587 let text = doc.get_text("t");
1588 text.insert(0, "ab", PosType::Unicode).unwrap();
1589 text.mark(
1590 0,
1591 1,
1592 "comment",
1593 LoroValue::String(big.clone().into()),
1594 PosType::Unicode,
1595 )
1596 .unwrap();
1597
1598 // A commit message.
1599 doc.set_next_commit_message(&big);
1600 doc.commit_then_renew();
1601
1602 let oplog = doc.oplog().lock();
1603 let end = *oplog.vv().get(&1).unwrap();
1604 let spans = vec![IdSpan::new(1, 0, end)];
1605 let est = estimate_ops_content_bytes(&oplog, &spans, usize::MAX);
1606 assert!(
1607 est >= 3 * big.len(),
1608 "estimate must count nested values, style values and the commit message, got {est}"
1609 );
1610 }
1611
1612 #[test]
1613 fn prefix_content_bytes_estimate_counts_style_keys_and_root_names() {
1614 let doc = LoroDoc::new_auto_commit();
1615 doc.set_peer_id(1).unwrap();
1616 let big = "k".repeat(1 << 20);
1617
1618 // A huge style key: the block encoder copies keys into the block's
1619 // key register.
1620 let mut styles = crate::container::richtext::config::StyleConfigMap::new();
1621 styles.insert(
1622 big.as_str().into(),
1623 crate::container::richtext::config::StyleConfig {
1624 expand: crate::container::richtext::ExpandType::After,
1625 },
1626 );
1627 doc.config_text_style(styles);
1628 let text = doc.get_text("t");
1629 text.insert(0, "ab", PosType::Unicode).unwrap();
1630 text.mark(0, 1, big.as_str(), LoroValue::Bool(true), PosType::Unicode)
1631 .unwrap();
1632
1633 // A huge root container name: copied into the block's container arena.
1634 doc.get_text(big.as_str())
1635 .insert(0, "x", PosType::Unicode)
1636 .unwrap();
1637 doc.commit_then_renew();
1638
1639 let oplog = doc.oplog().lock();
1640 let end = *oplog.vv().get(&1).unwrap();
1641 let spans = vec![IdSpan::new(1, 0, end)];
1642 let est = estimate_ops_content_bytes(&oplog, &spans, usize::MAX);
1643 assert!(
1644 est >= 2 * big.len(),
1645 "estimate must count style keys and root container names, got {est}"
1646 );
1647 }
1648
1649 /// Unknown-container ops can carry OwnedValue::MarkStart / ListSet with
1650 /// variable-length key/value payloads (the decoder accepts any Value for
1651 /// unknown containers and owns it); the prefix estimator must count them.
1652 #[test]
1653 fn prefix_content_bytes_estimate_counts_unknown_owned_values() {
1654 use crate::change::Change;
1655 use crate::encoding::value::{MarkStart, OwnedValue};
1656 use crate::op::{FutureInnerContent, InnerContent, Op};
1657 use rle::RleVec;
1658
1659 let big = "v".repeat(1 << 20);
1660 let doc = LoroDoc::new();
1661 let mut oplog = doc.oplog().lock();
1662 let idx = oplog
1663 .arena
1664 .register_container(&ContainerID::new_root("u", ContainerType::Unknown(7)));
1665
1666 let mut ops: RleVec<[Op; 1]> = RleVec::new();
1667 ops.push(Op::new(
1668 ID::new(1, 0),
1669 InnerContent::Future(FutureInnerContent::Unknown {
1670 prop: 0,
1671 value: Box::new(OwnedValue::MarkStart(MarkStart {
1672 len: 1,
1673 key: big.as_str().into(),
1674 value: LoroValue::Null,
1675 info: 0,
1676 })),
1677 }),
1678 idx,
1679 ));
1680 ops.push(Op::new(
1681 ID::new(1, 1),
1682 InnerContent::Future(FutureInnerContent::Unknown {
1683 prop: 0,
1684 value: Box::new(OwnedValue::ListSet {
1685 peer_idx: 0,
1686 lamport: 0,
1687 value: LoroValue::String(big.clone().into()),
1688 }),
1689 }),
1690 idx,
1691 ));
1692 oplog.insert_new_change(
1693 Change::new(ops, Frontiers::default(), ID::new(1, 0), 0, 0),
1694 false,
1695 );
1696
1697 let est = estimate_ops_content_bytes(&oplog, &[IdSpan::new(1, 0, 2)], usize::MAX);
1698 assert!(
1699 est >= 2 * big.len(),
1700 "estimate must count MarkStart keys and ListSet values on unknown ops, got {est}"
1701 );
1702 }
1703
1704 /// Rewrites the parent id in the header of `target`'s entry in the shallow
1705 /// root state of a replay-only (`E`) shallow blob, keeping its payload.
1706 fn forge_root_state(blob: &[u8], edit: impl FnOnce(&KvWrapper)) -> Vec<u8> {
1707 let mut sections = shallow_sections(blob);
1708 assert!(
1709 sections.state_bytes.is_none(),
1710 "fixture must use the replay path"
1711 );
1712 let kv = KvWrapper::new_mem();
1713 kv.import(sections.shallow_root_state_bytes.clone())
1714 .unwrap();
1715 edit(&kv);
1716 sections.shallow_root_state_bytes = kv.export();
1717 assemble_snapshot_blob(&sections)
1718 }
1719
1720 fn with_header_parent(value: &[u8], parent: Option<ContainerID>) -> Bytes {
1721 let offset = ContainerWrapper::payload_offset(value).unwrap();
1722 let mut reader = &value[1..];
1723 let depth = leb128::read::unsigned(&mut reader).unwrap();
1724 let mut out = vec![value[0]];
1725 leb128::write::unsigned(&mut out, depth).unwrap();
1726 postcard::to_io(&parent, &mut out).unwrap();
1727 out.extend_from_slice(&value[offset..]);
1728 out.into()
1729 }
1730
1731 fn set_header_parent(kv: &KvWrapper, target: &ContainerID, parent: Option<ContainerID>) {
1732 let key = target.to_bytes();
1733 let value = kv.get(&key).expect("target container is stored");
1734 kv.insert(&key, with_header_parent(&value, parent));
1735 }
1736
1737 fn root_state_keys(blob: &[u8]) -> BTreeSet<Vec<u8>> {
1738 let kv = KvWrapper::new_mem();
1739 kv.import(shallow_sections(blob).shallow_root_state_bytes)
1740 .unwrap();
1741 kv.keys()
1742 }
1743
1744 /// Every export of a doc whose cached root has a forged header must succeed
1745 /// and keep the doc's content: the root is exported verbatim, and no
1746 /// referenced data is dropped.
1747 fn assert_exports_keep_content(doc: &LoroDoc, expected: &LoroValue, case: &str) {
1748 for mode in [
1749 ExportMode::shallow_snapshot(&doc.shallow_since_frontiers()),
1750 ExportMode::Snapshot,
1751 ] {
1752 let bytes = doc
1753 .export(mode)
1754 .unwrap_or_else(|e| panic!("{case}: export failed: {e}"));
1755 let again = LoroDoc::new();
1756 again.import(&bytes).unwrap();
1757 assert_eq!(
1758 &again.get_deep_value(),
1759 expected,
1760 "{case}: export lost data"
1761 );
1762 }
1763 // A fork copies the cached root verbatim and must not panic.
1764 assert_eq!(&doc.fork().get_deep_value(), expected, "{case}: fork");
1765 }
1766
1767 #[test]
1768 fn cached_root_with_forged_parent_header_never_drops_referenced_containers() {
1769 let doc = LoroDoc::new_auto_commit();
1770 doc.set_peer_id(1).unwrap();
1771 doc.get_map("decoy").insert("k", 1).unwrap();
1772 let fill = |map: &MapHandler| -> ContainerID {
1773 map.insert("secret", "KEEP-ME").unwrap();
1774 let body = map
1775 .insert_container("body", TextHandler::new_detached())
1776 .unwrap();
1777 body.insert(0, "inner", PosType::Unicode).unwrap();
1778 body.id()
1779 };
1780 let row = doc
1781 .get_map("rows")
1782 .insert_container("row", MapHandler::new_detached())
1783 .unwrap();
1784 let row_body = fill(&row);
1785 let item = doc
1786 .get_list("list")
1787 .insert_container(0, MapHandler::new_detached())
1788 .unwrap();
1789 let item_body = fill(&item);
1790 let moved = doc
1791 .get_movable_list("movable")
1792 .insert_container(0, MapHandler::new_detached())
1793 .unwrap();
1794 let moved_body = fill(&moved);
1795 let tree = doc.get_tree("tree");
1796 let node = tree.create(crate::TreeParentId::Root).unwrap();
1797 let meta = tree.get_meta(node).unwrap();
1798 let meta_body = fill(&meta);
1799 doc.commit_then_renew();
1800 let root = doc.oplog_frontiers();
1801 doc.get_map("other").insert("after", 1).unwrap();
1802 doc.commit_then_renew();
1803 let expected = doc.get_deep_value();
1804 let blob = doc.export(ExportMode::shallow_snapshot(&root)).unwrap();
1805
1806 let decoy = ContainerID::new_root("decoy", ContainerType::Map);
1807 let missing = ContainerID::new_normal(ID::new(99, 7), ContainerType::Map);
1808 let targets = [
1809 ("map row", row.id(), Some(row_body.clone())),
1810 ("list element", item.id(), Some(item_body)),
1811 ("movable list element", moved.id(), Some(moved_body)),
1812 ("tree meta", meta.id(), Some(meta_body)),
1813 ("inner text", row_body, None),
1814 ];
1815 let mut cases = 0;
1816 for (name, target, child) in targets {
1817 let mut parents = vec![
1818 ("decoy root", Some(decoy.clone())),
1819 ("missing id", Some(missing.clone())),
1820 ("itself", Some(target.clone())),
1821 ("none", None),
1822 ];
1823 if let Some(child) = child {
1824 parents.push(("own child (cycle)", Some(child)));
1825 }
1826 for (how, parent) in parents {
1827 let case = format!("{name} claims parent {how}");
1828 let forged =
1829 forge_root_state(&blob, |kv| set_header_parent(kv, &target, parent.clone()));
1830 let shallow = LoroDoc::new();
1831 shallow.import(&forged).unwrap();
1832 assert_eq!(shallow.get_deep_value(), expected, "{case}: import");
1833 assert_exports_keep_content(&shallow, &expected, &case);
1834 cases += 1;
1835 }
1836 }
1837 assert_eq!(cases, 24);
1838 }
1839
1840 #[test]
1841 fn cached_root_keeps_children_of_unknown_containers() {
1842 let doc = LoroDoc::new_auto_commit();
1843 doc.set_peer_id(1).unwrap();
1844 let tmp = ContainerID::new_root("tmp", ContainerType::Map);
1845 let row = doc
1846 .get_map("tmp")
1847 .insert_container("row", MapHandler::new_detached())
1848 .unwrap();
1849 row.insert("secret", "KEEP-ME").unwrap();
1850 doc.commit_then_renew();
1851 let root = doc.oplog_frontiers();
1852 doc.get_map("other").insert("after", 1).unwrap();
1853 doc.commit_then_renew();
1854 let blob = doc.export(ExportMode::shallow_snapshot(&root)).unwrap();
1855
1856 // Re-home `row` under a root of a container type this version does not
1857 // know: its child references cannot be read, so the child must stay.
1858 let unknown = ContainerID::new_root("future", ContainerType::Unknown(9));
1859 let forged = forge_root_state(&blob, |kv| {
1860 let tmp_value = kv.remove(&tmp.to_bytes()).unwrap();
1861 let offset = ContainerWrapper::payload_offset(&tmp_value).unwrap();
1862 let mut header = with_header_parent(&tmp_value, None)[..offset].to_vec();
1863 header[0] = ContainerType::Unknown(9).to_u8();
1864 kv.insert(&unknown.to_bytes(), header.into());
1865 set_header_parent(kv, &row.id(), Some(unknown.clone()));
1866 });
1867 let shallow = LoroDoc::new();
1868 shallow.import(&forged).unwrap();
1869 assert!(root_state_keys(&forged).contains(&row.id().to_bytes()));
1870 for mode in [
1871 ExportMode::shallow_snapshot(&shallow.shallow_since_frontiers()),
1872 ExportMode::Snapshot,
1873 ] {
1874 let bytes = shallow.export(mode).unwrap();
1875 assert!(
1876 root_state_keys(&bytes).contains(&row.id().to_bytes()),
1877 "child of an unknown container was dropped"
1878 );
1879 LoroDoc::new().import(&bytes).unwrap();
1880 }
1881 }
1882
1883 /// An encoded wrapper of an unknown container type with an empty payload.
1884 fn unknown_entry(kind: u8, parent: Option<ContainerID>) -> Bytes {
1885 let mut out = vec![kind];
1886 leb128::write::unsigned(&mut out, 1).unwrap();
1887 postcard::to_io(&parent, &mut out).unwrap();
1888 out.into()
1889 }
1890
1891 #[test]
1892 fn unknown_types_do_not_shield_unrelated_dead_containers() {
1893 let doc = LoroDoc::new_auto_commit();
1894 doc.set_peer_id(1).unwrap();
1895 // Op 0@1 is a scalar write, so no real container has id 0@1.
1896 doc.get_map("decoy").insert("k", 1).unwrap();
1897 let row = doc
1898 .get_map("rows")
1899 .insert_container("row", MapHandler::new_detached())
1900 .unwrap();
1901 row.insert("secret", "KEEP-ME").unwrap();
1902 doc.commit_then_renew();
1903 let root = doc.oplog_frontiers();
1904 doc.get_map("other").insert("after", 1).unwrap();
1905 doc.commit_then_renew();
1906 let expected = doc.get_deep_value();
1907 let blob = doc.export(ExportMode::shallow_snapshot(&root)).unwrap();
1908
1909 let rows = ContainerID::new_root("rows", ContainerType::Map);
1910 // A pre-root map nothing references, carrying a copy of `row`'s content.
1911 let dead = ContainerID::new_normal(ID::new(1, 0), ContainerType::Map);
1912 let unknown = ContainerType::Unknown(9);
1913 let cases: [(&str, Option<ContainerID>, Option<(ContainerID, Bytes)>); 4] = [
1914 (
1915 "dead entry claims a missing unknown root parent",
1916 Some(ContainerID::new_root("ghost", unknown)),
1917 None,
1918 ),
1919 (
1920 "dead entry claims a missing unknown normal parent",
1921 Some(ContainerID::new_normal(ID::new(5, 5), unknown)),
1922 None,
1923 ),
1924 (
1925 "unreferenced unknown root is stored",
1926 Some(rows.clone()),
1927 Some((
1928 ContainerID::new_root("future", unknown),
1929 unknown_entry(9, None),
1930 )),
1931 ),
1932 (
1933 "unreferenced unknown normal entry is stored",
1934 Some(rows.clone()),
1935 Some((
1936 ContainerID::new_normal(ID::new(1, 0), unknown),
1937 unknown_entry(9, Some(rows.clone())),
1938 )),
1939 ),
1940 ];
1941 for (case, dead_parent, extra) in cases {
1942 let forged = forge_root_state(&blob, |kv| {
1943 let value = kv.get(&row.id().to_bytes()).unwrap();
1944 kv.insert(&dead.to_bytes(), with_header_parent(&value, dead_parent));
1945 if let Some((id, value)) = &extra {
1946 kv.insert(&id.to_bytes(), value.clone());
1947 }
1948 });
1949 assert!(root_state_keys(&forged).contains(&dead.to_bytes()));
1950 let shallow = LoroDoc::new();
1951 shallow.import(&forged).unwrap();
1952 // An unknown root shows up as `Null`; everything else is unchanged.
1953 let imported = shallow.get_deep_value();
1954 for key in ["decoy", "rows", "other"] {
1955 assert_eq!(
1956 imported.as_map().unwrap().get(key),
1957 expected.as_map().unwrap().get(key),
1958 "{case}: import"
1959 );
1960 }
1961 for mode in [
1962 ExportMode::shallow_snapshot(&shallow.shallow_since_frontiers()),
1963 ExportMode::Snapshot,
1964 ] {
1965 let bytes = shallow.export(mode).unwrap();
1966 let keys = root_state_keys(&bytes);
1967 assert!(!keys.contains(&dead.to_bytes()), "{case}: dead entry kept");
1968 assert!(keys.contains(&row.id().to_bytes()), "{case}: live row lost");
1969 if let Some((id, _)) = &extra {
1970 // Roots are always retained; an unreferenced normal entry is not.
1971 assert_eq!(keys.contains(&id.to_bytes()), id.is_root(), "{case}");
1972 }
1973 let again = LoroDoc::new();
1974 again.import(&bytes).unwrap();
1975 assert_eq!(again.get_deep_value(), imported, "{case}");
1976 }
1977 }
1978 }
1979}