forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

container_store.rs1186 lines, 43.9 KiBHistoryRawDownload
1use super::{ContainerCreationContext, State};
2use crate::arena::LoadAllFlag;
3use crate::sync::{AtomicU64, Mutex};
4use crate::{
5 arena::SharedArena, configure::Configure, container::idx::ContainerIdx,
6 utils::kv_wrapper::KvWrapper, version::Frontiers,
7};
8use bytes::Bytes;
9use inner_store::InnerStore;
10use loro_common::{ContainerID, InternalString, LoroResult, LoroValue};
11use once_cell::sync::OnceCell;
12use std::sync::Arc;
13
14pub(crate) use container_wrapper::ContainerWrapper;
15
16mod container_wrapper;
17mod inner_store;
18
19/// Encoding Schema for Container Store
20///
21/// KV-Store:
22/// - Key: Encoded Container ID
23/// - Value: Encoded Container State
24///
25/// ─ ─ ─ ─ ─ ─ ─ For Each Container Type ─ ─ ─ ─ ─ ─ ─ ─
26///
27/// ┌────────────────┬──────────────────────────────────┐
28/// │ u16 Depth │ ParentID │
29/// └────────────────┴──────────────────────────────────┘
30/// ┌───────────────────────────────────────────────────┐
31/// │ ┌───────────────────────────────────────────────┐ │
32/// │ │ Into<LoroValue> │ │
33/// │ └───────────────────────────────────────────────┘ │
34/// │ │
35/// │ Container Specific Encode │
36/// │ │
37/// │ │
38/// │ │
39/// │ │
40/// └───────────────────────────────────────────────────┘
41pub(crate) struct ContainerStore {
42 arena: SharedArena,
43 store: InnerStore,
44 shallow_root_store: Option<Arc<GcStore>>,
45 conf: Configure,
46 peer: Arc<AtomicU64>,
47}
48
49pub(crate) const FRONTIERS_KEY: &[u8] = b"fr";
50impl std::fmt::Debug for ContainerStore {
51 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
52 f.debug_struct("ContainerStore")
53 .field("store", &self.store)
54 .finish()
55 }
56}
57
58#[derive(Debug)]
59pub(crate) struct GcStore {
60 pub shallow_root_frontiers: Frontiers,
61 pub encoded_state_bytes: Bytes,
62 pub store: Mutex<InnerStore>,
63 /// This root with the containers the retention walk does not reach removed,
64 /// computed on the first export that reuses the root (see
65 /// `shallow_snapshot::prune_cached_root`). `None` means nothing is removed,
66 /// which holds unless the root came from an exporter that kept containers
67 /// deleted before the root. The root never changes, so neither does this.
68 pub pruned_root: OnceCell<Option<PrunedRootState>>,
69}
70
71/// A cached shallow root state with unretained containers removed.
72#[derive(Debug)]
73pub(crate) struct PrunedRootState {
74 /// Encoded pruned root state, including the frontiers key.
75 pub state_bytes: Bytes,
76 /// Keys removed from the cached root.
77 pub removed: Vec<Bytes>,
78}
79
80macro_rules! ctx {
81 ($self:expr) => {
82 ContainerCreationContext {
83 configure: &$self.conf,
84 peer: $self.peer.load(std::sync::atomic::Ordering::Relaxed),
85 }
86 };
87}
88
89impl ContainerStore {
90 pub fn new(arena: SharedArena, conf: Configure, peer: Arc<AtomicU64>) -> Self {
91 ContainerStore {
92 store: InnerStore::new(arena.clone(), conf.clone()),
93 arena,
94 conf,
95 shallow_root_store: None,
96 peer,
97 }
98 }
99
100 pub fn can_import_snapshot(&self) -> bool {
101 if self.shallow_root_store.is_some() {
102 return false;
103 }
104
105 self.store.can_import_snapshot()
106 }
107
108 pub(crate) fn set_decoded_value_cache_limit(&mut self, limit: usize) {
109 self.conf.set_decoded_value_cache_limit(limit);
110 self.store.trim_value_cache();
111 if let Some(root) = &self.shallow_root_store {
112 root.store.lock().trim_value_cache();
113 }
114 }
115
116 pub fn get_container_mut(&mut self, idx: ContainerIdx) -> Option<&mut State> {
117 self.store
118 .get_mut(idx)
119 .map(|x| x.get_state_mut(idx, ctx!(self)))
120 }
121
122 #[allow(unused)]
123 pub fn get_container(&mut self, idx: ContainerIdx) -> Option<&State> {
124 self.store
125 .get_mut(idx)
126 .map(|x| x.get_state(idx, ctx!(self)))
127 }
128
129 pub fn shallow_root_store(&self) -> Option<&Arc<GcStore>> {
130 self.shallow_root_store.as_ref()
131 }
132
133 pub fn get_value(&mut self, idx: ContainerIdx) -> Option<LoroValue> {
134 self.store
135 .with_container_for_read(idx, |c| c.get_value(idx, ctx!(self)))
136 }
137
138 pub(crate) fn get_value_ephemeral(&mut self, idx: ContainerIdx) -> Option<LoroValue> {
139 self.try_get_value_ephemeral(idx)
140 .expect("snapshot-backed container should decode")
141 }
142
143 pub(crate) fn try_get_value_ephemeral(
144 &mut self,
145 idx: ContainerIdx,
146 ) -> LoroResult<Option<LoroValue>> {
147 self.store.try_get_value_ephemeral(idx, ctx!(self))
148 }
149
150 pub(crate) fn try_get_parent_and_value_ephemeral(
151 &mut self,
152 idx: ContainerIdx,
153 ) -> LoroResult<Option<(Option<ContainerID>, LoroValue)>> {
154 self.store
155 .try_get_parent_and_value_ephemeral(idx, ctx!(self))
156 }
157
158 pub(crate) fn try_get_parent_and_tree_meta_ids_ephemeral(
159 &mut self,
160 idx: ContainerIdx,
161 ) -> LoroResult<Option<(Option<ContainerID>, Vec<ContainerID>)>> {
162 self.store
163 .try_get_parent_and_tree_meta_ids_ephemeral(idx, ctx!(self))
164 }
165
166 pub(crate) fn get_parent_ephemeral(
167 &mut self,
168 idx: ContainerIdx,
169 ) -> LoroResult<Option<Option<ContainerID>>> {
170 self.store.get_parent_ephemeral(idx)
171 }
172
173 pub fn map_get(&mut self, idx: ContainerIdx, key: &str) -> Option<LoroValue> {
174 self.store
175 .with_container_for_read(idx, |c| c.map_get(idx, ctx!(self), key))?
176 }
177
178 pub fn map_len(&mut self, idx: ContainerIdx) -> usize {
179 self.store
180 .with_container_for_read(idx, |c| c.map_len(idx, ctx!(self)))
181 .unwrap_or(0)
182 }
183
184 pub fn map_keys(&mut self, idx: ContainerIdx) -> Vec<InternalString> {
185 self.store
186 .with_container_for_read(idx, |c| c.map_keys(idx, ctx!(self)))
187 .unwrap_or_default()
188 }
189
190 pub fn map_entries(&mut self, idx: ContainerIdx) -> Vec<(InternalString, LoroValue)> {
191 self.store
192 .with_container_for_read(idx, |c| c.map_entries(idx, ctx!(self)))
193 .unwrap_or_default()
194 }
195
196 pub fn list_get(&mut self, idx: ContainerIdx, index: usize) -> Option<LoroValue> {
197 self.store
198 .with_container_for_read(idx, |c| c.list_get(idx, ctx!(self), index))?
199 }
200
201 pub fn list_len(&mut self, idx: ContainerIdx) -> usize {
202 self.store
203 .with_container_for_read(idx, |c| c.list_len(idx, ctx!(self)))
204 .unwrap_or(0)
205 }
206
207 pub fn list_values(&mut self, idx: ContainerIdx) -> Vec<LoroValue> {
208 self.store
209 .with_container_for_read(idx, |c| c.list_values(idx, ctx!(self)))
210 .unwrap_or_default()
211 }
212
213 pub fn text_unicode_len(&mut self, idx: ContainerIdx) -> Option<usize> {
214 self.store
215 .with_container_for_read(idx, |c| c.text_unicode_len(idx, ctx!(self)))?
216 }
217
218 pub fn text_utf16_len(&mut self, idx: ContainerIdx) -> Option<usize> {
219 self.store
220 .with_container_for_read(idx, |c| c.text_utf16_len(idx, ctx!(self)))?
221 }
222
223 pub fn text_utf8_len(&mut self, idx: ContainerIdx) -> Option<usize> {
224 self.store
225 .with_container_for_read(idx, |c| c.text_utf8_len(idx, ctx!(self)))?
226 }
227
228 pub fn has_decoded_state(&mut self, idx: ContainerIdx) -> bool {
229 self.store.has_decoded_state(idx)
230 }
231
232 pub fn encode(&mut self) -> Bytes {
233 self.store.encode()
234 }
235
236 pub(crate) fn flush(&mut self) {
237 self.store.flush()
238 }
239
240 pub fn shallow_root_frontiers(&self) -> Option<&Frontiers> {
241 self.shallow_root_store
242 .as_ref()
243 .map(|x| &x.shallow_root_frontiers)
244 }
245
246 pub(crate) fn shallow_root_state_for_export(&self) -> Option<(Bytes, KvWrapper)> {
247 let shallow_root = self.shallow_root_store.as_ref()?;
248 let shallow_root_kv = shallow_root.store.lock().get_kv_clone();
249 Some((shallow_root.encoded_state_bytes.clone(), shallow_root_kv))
250 }
251
252 pub(crate) fn decode(&mut self, bytes: Bytes) -> LoroResult<Option<Frontiers>> {
253 self.store.decode(bytes)
254 }
255
256 pub(crate) fn decode_gc(
257 &mut self,
258 shallow_bytes: Bytes,
259 start_frontiers: Frontiers,
260 config: Configure,
261 ) -> LoroResult<Option<Frontiers>> {
262 assert!(self.shallow_root_store.is_none());
263 let mut inner = InnerStore::new(self.arena.clone(), config);
264 let encoded_state_bytes = shallow_bytes.clone();
265 let f = inner.decode(shallow_bytes)?;
266 let encoded_state_bytes = if f.as_ref() == Some(&start_frontiers) {
267 encoded_state_bytes
268 } else {
269 let kv = inner.get_kv_clone();
270 kv.insert(FRONTIERS_KEY, start_frontiers.encode().into());
271 kv.export()
272 };
273 self.shallow_root_store = Some(Arc::new(GcStore {
274 shallow_root_frontiers: start_frontiers,
275 encoded_state_bytes,
276 store: Mutex::new(inner),
277 pruned_root: OnceCell::new(),
278 }));
279 Ok(f)
280 }
281
282 pub(crate) fn decode_state_by_two_bytes(
283 &mut self,
284 shallow_bytes: Bytes,
285 state_bytes: Bytes,
286 ) -> LoroResult<()> {
287 self.store
288 .decode_twice(shallow_bytes.clone(), state_bytes)?;
289 Ok(())
290 }
291
292 pub fn iter_and_decode_all(&mut self) -> impl Iterator<Item = &mut State> {
293 self.store.iter_all_containers_mut().map(|(idx, v)| {
294 v.get_state_mut(
295 idx,
296 ContainerCreationContext {
297 configure: &self.conf,
298 peer: self.peer.load(std::sync::atomic::Ordering::Relaxed),
299 },
300 )
301 })
302 }
303
304 pub fn get_kv_clone(&self) -> KvWrapper {
305 self.store.get_kv_clone()
306 }
307
308 pub fn contains_id(&mut self, id: &ContainerID) -> bool {
309 self.store.contains_id(id)
310 }
311
312 pub fn iter_all_containers(
313 &mut self,
314 ) -> impl Iterator<Item = (ContainerIdx, &mut ContainerWrapper)> {
315 self.store.iter_all_containers_mut()
316 }
317
318 pub fn iter_all_container_ids(&mut self) -> impl Iterator<Item = ContainerID> + '_ {
319 self.store.iter_all_container_ids()
320 }
321
322 pub fn load_root_containers(&mut self) -> LoadAllFlag {
323 self.store.load_roots();
324 LoadAllFlag
325 }
326
327 pub(super) fn begin_created_journal(&mut self) {
328 self.store.begin_created_journal();
329 }
330
331 pub(super) fn take_created_journal(&mut self) -> Vec<ContainerIdx> {
332 self.store.take_created_journal()
333 }
334
335 pub(super) fn remove_created(&mut self, created: &[ContainerIdx]) {
336 self.store.remove_created(created);
337 }
338
339 pub(super) fn get_or_create_mut(&mut self, idx: ContainerIdx) -> &mut State {
340 self.store
341 .get_or_insert_with(idx, || {
342 let state = super::create_state_(
343 idx,
344 &self.conf,
345 self.peer.load(std::sync::atomic::Ordering::Relaxed),
346 );
347 ContainerWrapper::new(state, &self.arena)
348 })
349 .get_state_mut(idx, ctx!(self))
350 }
351
352 pub(crate) fn ensure_container(&mut self, id: &loro_common::ContainerID) {
353 let idx = self.arena.register_container(id);
354 self.store.ensure_container(idx, || {
355 let state = super::create_state_(
356 idx,
357 &self.conf,
358 self.peer.load(std::sync::atomic::Ordering::Relaxed),
359 );
360 ContainerWrapper::new(state, &self.arena)
361 });
362 }
363
364 pub(super) fn get_or_create_imm(&mut self, idx: ContainerIdx) -> &State {
365 self.store
366 .get_or_insert_with(idx, || {
367 let state = super::create_state_(
368 idx,
369 &self.conf,
370 self.peer.load(std::sync::atomic::Ordering::Relaxed),
371 );
372 ContainerWrapper::new(state, &self.arena)
373 })
374 .get_state(idx, ctx!(self))
375 }
376
377 pub(crate) fn fork(
378 &mut self,
379 arena: SharedArena,
380 peer: Arc<AtomicU64>,
381 config: Configure,
382 ) -> ContainerStore {
383 ContainerStore {
384 store: self.store.fork(arena.clone(), &config),
385 arena,
386 conf: config,
387 peer,
388 shallow_root_store: None,
389 }
390 }
391
392 #[allow(unused)]
393 fn check_eq_after_parsing(&mut self, other: &mut ContainerStore) {
394 for (idx, container) in self.store.iter_all_containers_mut() {
395 let id = self.arena.get_container_id(idx).unwrap();
396 let other_idx = other.arena.register_container(&id);
397 let other_container = other
398 .store
399 .get_mut(other_idx)
400 .expect("container not found on other store");
401 let other_id = other.arena.get_container_id(other_idx).unwrap();
402 assert_eq!(
403 id, other_id,
404 "container id mismatch {:?} {:?}",
405 id, other_id
406 );
407 assert_eq!(
408 container.get_value(idx, ctx!(self)),
409 other_container.get_value(other_idx, ctx!(other)),
410 "value mismatch"
411 );
412
413 if container.encode() != other_container.encode() {
414 panic!(
415 "container mismatch Origin: {:#?}, New: {:#?}",
416 &container, &other_container
417 );
418 }
419
420 other_container
421 .decode_state(other_idx, ctx!(other))
422 .unwrap();
423 other_container.clear_bytes();
424 if container.encode() != other_container.encode() {
425 panic!(
426 "container mismatch Origin: {:#?}, New: {:#?}",
427 &container, &other_container
428 );
429 }
430 }
431 }
432}
433
434#[cfg(test)]
435mod test {
436 use super::*;
437 use crate::{
438 configure::DEFAULT_DECODED_VALUE_CACHE_LIMIT, cursor::PosType, handler::HandlerTrait,
439 state::TreeParentId, ContainerType, ListHandler, LoroDoc, MapHandler, MovableListHandler,
440 };
441
442 fn decode_container_store(bytes: Bytes) -> ContainerStore {
443 let mut new_store = ContainerStore::new(
444 SharedArena::new(),
445 Configure::default(),
446 Arc::new(AtomicU64::new(233)),
447 );
448
449 new_store.decode(bytes).unwrap();
450 new_store
451 }
452
453 fn init_doc() -> LoroDoc {
454 let doc = LoroDoc::new();
455 doc.start_auto_commit();
456 let text = doc.get_text("text");
457 text.insert(0, "hello", PosType::Unicode).unwrap();
458 let map = doc.get_map("map");
459 map.insert("key", "value").unwrap();
460
461 let list = doc.get_list("list");
462 list.push("item1").unwrap();
463
464 let tree = doc.get_tree("tree");
465 let root = tree.create(TreeParentId::Root).unwrap();
466 tree.create_at(TreeParentId::Node(root), 0).unwrap();
467
468 let movable_list = doc.get_movable_list("movable_list");
469 movable_list.insert(0, "movable_item").unwrap();
470
471 // Create child containers
472 let child_map = map
473 .insert_container("child_map", MapHandler::new_detached())
474 .unwrap();
475 child_map.insert("child_key", "child_value").unwrap();
476
477 let child_list = list
478 .insert_container(0, ListHandler::new_detached())
479 .unwrap();
480 child_list.push("child_item").unwrap();
481 let child_movable_list = movable_list
482 .insert_container(0, MovableListHandler::new_detached())
483 .unwrap();
484 child_movable_list.insert(0, "child_movable_item").unwrap();
485 doc
486 }
487
488 fn export_container_store(doc: &LoroDoc) -> Bytes {
489 let mut state = doc.app_state().lock();
490 state.ensure_all_alive_containers().unwrap();
491 state.store.encode()
492 }
493
494 #[test]
495 fn test_container_store_exports_imports() {
496 let doc = init_doc();
497 let bytes = export_container_store(&doc);
498 let mut new_store = decode_container_store(bytes);
499 let mut s = doc.app_state().lock();
500 s.store.check_eq_after_parsing(&mut new_store);
501 }
502
503 #[test]
504 fn first_lazy_read_caches_value() {
505 let doc = init_doc();
506 let bytes = export_container_store(&doc);
507 let mut store = decode_container_store(bytes);
508 let map_id = ContainerID::new_root("map", ContainerType::Map);
509 let map_idx = store.arena.register_container(&map_id);
510
511 assert!(!store.store.has_cached_value_for_test(map_idx));
512 assert_eq!(store.map_len(map_idx), 2);
513 assert!(store.store.has_cached_value_for_test(map_idx));
514
515 // The cache is bounded (loro-dev/loro#1092): reading more containers
516 // than the bound evicts older cached values, and re-reading an evicted
517 // container transparently re-decodes it from the KV store.
518 let n = DEFAULT_DECODED_VALUE_CACHE_LIMIT * 2;
519 let source = doc_with_many_child_maps(n);
520 let bytes = export_container_store(&source);
521 let mut store = decode_container_store(bytes);
522 let list_idx = store
523 .arena
524 .register_container(&ContainerID::new_root("list", ContainerType::List));
525 let mut child_ids = Vec::new();
526 for i in 0..n {
527 let value = store.list_get(list_idx, i).unwrap();
528 child_ids.push(value.as_container().unwrap().clone());
529 let child_idx = store.arena.register_container(child_ids.last().unwrap());
530 assert_eq!(store.map_get(child_idx, "key"), Some((i as i64).into()));
531 }
532
533 assert!(
534 store.store.cached_value_count_for_test() <= DEFAULT_DECODED_VALUE_CACHE_LIMIT,
535 "cached decoded values must stay bounded, got {}",
536 store.store.cached_value_count_for_test()
537 );
538 // The first children were evicted; re-reading must fall back to KV.
539 let first_idx = store.arena.register_container(&child_ids[0]);
540 assert_eq!(store.map_get(first_idx, "key"), Some(0i64.into()));
541 }
542
543 #[test]
544 fn ephemeral_lazy_read_does_not_cache_value() {
545 let doc = init_doc();
546 let bytes = export_container_store(&doc);
547 let mut store = decode_container_store(bytes);
548 let map_id = ContainerID::new_root("map", ContainerType::Map);
549 let map_idx = store.arena.register_container(&map_id);
550
551 assert!(!store.store.has_cached_value_for_test(map_idx));
552 assert_eq!(
553 store
554 .get_value_ephemeral(map_idx)
555 .and_then(|value| value.as_map().map(|map| map.len())),
556 Some(2)
557 );
558 assert!(!store.store.has_cached_value_for_test(map_idx));
559 }
560
561 #[test]
562 fn combined_ephemeral_parent_and_value_read_does_not_cache_value() {
563 let doc = init_doc();
564 let bytes = export_container_store(&doc);
565 let mut store = decode_container_store(bytes);
566 let map_id = ContainerID::new_root("map", ContainerType::Map);
567 let map_idx = store.arena.register_container(&map_id);
568
569 assert!(!store.store.has_cached_value_for_test(map_idx));
570 let (parent, value) = store
571 .try_get_parent_and_value_ephemeral(map_idx)
572 .unwrap()
573 .unwrap();
574 assert_eq!(parent, None);
575 assert_eq!(value.as_map().map(|map| map.len()), Some(2));
576 assert!(!store.store.has_cached_value_for_test(map_idx));
577 }
578
579 #[test]
580 fn snapshot_export_does_not_materialize_map_value_after_key_read() {
581 let source = init_doc();
582 let snapshot = source
583 .export(crate::encoding::ExportMode::Snapshot)
584 .unwrap();
585 let imported = LoroDoc::new();
586 imported.import(&snapshot).unwrap();
587 let map_id = ContainerID::new_root("map", ContainerType::Map);
588
589 assert_eq!(imported.get_map("map").get("key"), Some("value".into()));
590 {
591 let mut state = imported.app_state().lock();
592 let map_idx = state.store.arena.register_container(&map_id);
593 assert!(state.store.store.has_cached_value_for_test(map_idx));
594 assert!(!state
595 .store
596 .store
597 .has_materialized_map_value_for_test(map_idx));
598 }
599
600 imported
601 .export(crate::encoding::ExportMode::Snapshot)
602 .unwrap();
603
604 let mut state = imported.app_state().lock();
605 let map_idx = state.store.arena.register_container(&map_id);
606 assert!(!state
607 .store
608 .store
609 .has_materialized_map_value_for_test(map_idx));
610 }
611
612 #[test]
613 fn snapshot_export_keeps_imported_state_lazy() {
614 let source = init_doc();
615 let snapshot = source
616 .export(crate::encoding::ExportMode::Snapshot)
617 .unwrap();
618 let imported = LoroDoc::new();
619 imported.import(&snapshot).unwrap();
620 let map_id = ContainerID::new_root("map", ContainerType::Map);
621
622 {
623 let mut state = imported.app_state().lock();
624 let map_idx = state.store.arena.register_container(&map_id);
625 assert!(!state.store.store.has_cached_value_for_test(map_idx));
626 }
627
628 let exported = imported
629 .export(crate::encoding::ExportMode::Snapshot)
630 .unwrap();
631 assert!(!exported.is_empty());
632 let exported_again = imported
633 .export(crate::encoding::ExportMode::Snapshot)
634 .unwrap();
635 assert_eq!(exported_again, exported);
636
637 let mut state = imported.app_state().lock();
638 let map_idx = state.store.arena.register_container(&map_id);
639 assert!(!state.store.store.has_cached_value_for_test(map_idx));
640 }
641
642 #[test]
643 fn snapshot_export_includes_empty_root_without_version_change() {
644 let doc = LoroDoc::new_auto_commit();
645 doc.get_map("first");
646 doc.export(crate::encoding::ExportMode::Snapshot).unwrap();
647 let version_before = doc.state_frontiers();
648
649 let second_id = ContainerID::new_root("second", ContainerType::Map);
650 doc.get_map("second");
651 assert_eq!(doc.state_frontiers(), version_before);
652
653 let snapshot = doc.export(crate::encoding::ExportMode::Snapshot).unwrap();
654 let round_tripped = LoroDoc::new();
655 round_tripped.import(&snapshot).unwrap();
656 let mut state = round_tripped.app_state().lock();
657 assert!(state.store.contains_id(&second_id));
658 }
659
660 #[test]
661 fn snapshot_export_includes_new_empty_child() {
662 let doc = LoroDoc::new_auto_commit();
663 let root = doc.get_map("root");
664 root.insert("value", 1).unwrap();
665 doc.export(crate::encoding::ExportMode::Snapshot).unwrap();
666
667 let child = root
668 .insert_container("child", MapHandler::new_detached())
669 .unwrap();
670 let child_id = child.id();
671 let snapshot = doc.export(crate::encoding::ExportMode::Snapshot).unwrap();
672 let round_tripped = LoroDoc::new();
673 round_tripped.import(&snapshot).unwrap();
674 let mut state = round_tripped.app_state().lock();
675 assert!(state.store.contains_id(&child_id));
676 }
677
678 /// An empty child created by a remote peer has no ops of its own, so the importer only
679 /// applies the parent's diff. The diff-apply hook must still create a store entry for the
680 /// child, or the importer's own full snapshot would silently drop it.
681 #[test]
682 fn snapshot_export_includes_remote_empty_child() {
683 let a = LoroDoc::new_auto_commit();
684 let map_child_id = a
685 .get_map("map")
686 .insert_container("child", MapHandler::new_detached())
687 .unwrap()
688 .id();
689 let list_child_id = a
690 .get_list("list")
691 .insert_container(0, ListHandler::new_detached())
692 .unwrap()
693 .id();
694 let movable_child_id = a
695 .get_movable_list("movable")
696 .insert_container(0, MovableListHandler::new_detached())
697 .unwrap()
698 .id();
699 let updates = a
700 .export(crate::encoding::ExportMode::all_updates())
701 .unwrap();
702
703 let b = LoroDoc::new_auto_commit();
704 b.import(&updates).unwrap();
705 let snapshot = b.export(crate::encoding::ExportMode::Snapshot).unwrap();
706
707 let c = LoroDoc::new();
708 c.import(&snapshot).unwrap();
709 assert_eq!(a.get_deep_value(), c.get_deep_value());
710 let mut state = c.app_state().lock();
711 for id in [&map_child_id, &list_child_id, &movable_child_id] {
712 assert!(state.store.contains_id(id), "missing {id:?}");
713 }
714 }
715
716 /// A remote tree node's associated meta map has no ops until someone writes metadata; the
717 /// tree diff's `Create` action must ensure its store entry on the importer.
718 #[test]
719 fn snapshot_export_includes_remote_tree_meta() {
720 let a = LoroDoc::new_auto_commit();
721 let node = a.get_tree("tree").create(TreeParentId::Root).unwrap();
722 let meta_id = node.associated_meta_container();
723 let updates = a
724 .export(crate::encoding::ExportMode::all_updates())
725 .unwrap();
726
727 let b = LoroDoc::new_auto_commit();
728 b.import(&updates).unwrap();
729 let snapshot = b.export(crate::encoding::ExportMode::Snapshot).unwrap();
730
731 let c = LoroDoc::new();
732 c.import(&snapshot).unwrap();
733 let mut state = c.app_state().lock();
734 assert!(state.store.contains_id(&meta_id));
735 }
736
737 /// An ensured-but-empty mergeable child has no store entry anywhere — the parent map's
738 /// marker is its single source of truth. A full snapshot round-trip through an importer
739 /// must keep the child resolvable by id without materializing an entry for it.
740 #[test]
741 fn snapshot_export_keeps_empty_marker_child_resolvable_without_entry() {
742 let a = LoroDoc::new_auto_commit();
743 let child_id = a
744 .get_map("state")
745 .ensure_mergeable_text("notes")
746 .unwrap()
747 .id();
748 let updates = a
749 .export(crate::encoding::ExportMode::all_updates())
750 .unwrap();
751
752 let b = LoroDoc::new_auto_commit();
753 b.import(&updates).unwrap();
754 let snapshot = b.export(crate::encoding::ExportMode::Snapshot).unwrap();
755
756 let c = LoroDoc::new();
757 c.import(&snapshot).unwrap();
758 let mut state = c.app_state().lock();
759 assert!(!state.store.contains_id(&child_id));
760 assert!(
761 state.does_container_exist(&child_id),
762 "empty mergeable child must resolve from the marker after round-trip"
763 );
764 }
765
766 #[test]
767 fn deep_value_read_keeps_imported_state_lazy() {
768 let source = init_doc();
769 let expected = source.get_deep_value();
770 let child_map_id = source
771 .get_map("map")
772 .get("child_map")
773 .and_then(|value| value.as_container().cloned())
774 .unwrap();
775 let snapshot = source
776 .export(crate::encoding::ExportMode::Snapshot)
777 .unwrap();
778 let imported = LoroDoc::new();
779 imported.import(&snapshot).unwrap();
780 let map_id = ContainerID::new_root("map", ContainerType::Map);
781
782 assert_eq!(imported.get_deep_value(), expected);
783 assert_eq!(imported.get_deep_value(), expected);
784
785 let mut state = imported.app_state().lock();
786 let map_idx = state.store.arena.register_container(&map_id);
787 let child_map_idx = state.store.arena.register_container(&child_map_id);
788 assert!(!state.store.store.has_cached_value_for_test(map_idx));
789 assert!(!state.store.store.has_cached_value_for_test(child_map_idx));
790 }
791
792 #[test]
793 fn snapshot_export_persists_empty_alive_child() {
794 let source = LoroDoc::new_auto_commit();
795 let child = source
796 .get_map("root")
797 .insert_container("empty", MapHandler::new_detached())
798 .unwrap();
799 let child_id = child.id();
800 let updates = source
801 .export(crate::encoding::ExportMode::all_updates())
802 .unwrap();
803 let target = LoroDoc::new();
804 target.import(&updates).unwrap();
805 {
806 // The diff-apply hook creates the empty child's store entry at import time; full
807 // snapshot export relies on this invariant instead of walking the alive graph.
808 let mut state = target.app_state().lock();
809 assert!(state.store.contains_id(&child_id));
810 }
811
812 let snapshot = target
813 .export(crate::encoding::ExportMode::Snapshot)
814 .unwrap();
815 let round_tripped = LoroDoc::new();
816 round_tripped.import(&snapshot).unwrap();
817
818 let mut state = round_tripped.app_state().lock();
819 assert!(state.store.contains_id(&child_id));
820 }
821
822 fn doc_with_many_child_maps(n: usize) -> LoroDoc {
823 let doc = LoroDoc::new_auto_commit();
824 let list = doc.get_list("list");
825 for i in 0..n {
826 let map = list
827 .insert_container(i, MapHandler::new_detached())
828 .unwrap();
829 map.insert("key", i as i64).unwrap();
830 }
831 doc
832 }
833
834 /// Count the actual lazy-value misses before each handler read, rather than
835 /// relying on timings. A full walk above the limit otherwise decodes every
836 /// child again on the next walk (loro-dev/loro#1191).
837 fn walk_child_maps_and_count_decodes(doc: &LoroDoc, n: usize) -> usize {
838 let list = doc.get_list("list");
839 let mut decodes = 0;
840 for i in 0..n {
841 let id = list.get(i).unwrap().as_container().unwrap().clone();
842 let idx = doc.arena().register_container(&id);
843 if !doc
844 .app_state()
845 .lock()
846 .store
847 .store
848 .has_cached_value_for_test(idx)
849 {
850 decodes += 1;
851 }
852 assert_eq!(doc.get_map(id).get("key"), Some((i as i64).into()));
853 }
854 decodes
855 }
856
857 fn cached_value_count(doc: &LoroDoc) -> usize {
858 doc.app_state()
859 .lock()
860 .store
861 .store
862 .cached_value_count_for_test()
863 }
864
865 #[test]
866 fn repeated_handle_walks_respect_decoded_value_cache_limit() {
867 // Exercise the production-sized budget even in the unit-test build.
868 let limit = 2048;
869 for n in [limit / 2, limit * 2] {
870 let source = doc_with_many_child_maps(n);
871 let snapshot = source
872 .export(crate::encoding::ExportMode::Snapshot)
873 .unwrap();
874 let doc = LoroDoc::new_auto_commit();
875 doc.set_decoded_value_cache_limit(limit);
876 doc.import(&snapshot).unwrap();
877
878 assert_eq!(walk_child_maps_and_count_decodes(&doc, n), n);
879 let warm_decodes = if n > limit { n } else { 0 };
880 assert_eq!(walk_child_maps_and_count_decodes(&doc, n), warm_decodes);
881 assert_eq!(walk_child_maps_and_count_decodes(&doc, n), warm_decodes);
882
883 // Include the root list in the budget. After one warm-up walk, no
884 // child needs decoding, even when the document exceeds the default.
885 doc.set_decoded_value_cache_limit(n + 1);
886 walk_child_maps_and_count_decodes(&doc, n);
887 assert_eq!(walk_child_maps_and_count_decodes(&doc, n), 0);
888 assert_eq!(walk_child_maps_and_count_decodes(&doc, n), 0);
889
890 // A short window is enough to check tiny limits; repeatedly
891 // decoding the large root list is deliberately expensive at zero.
892 let n = n.min(32);
893 doc.set_decoded_value_cache_limit(1);
894 assert!(cached_value_count(&doc) <= 1);
895 assert_eq!(walk_child_maps_and_count_decodes(&doc, n), n);
896 assert!(cached_value_count(&doc) <= 1);
897
898 doc.set_decoded_value_cache_limit(0);
899 assert_eq!(cached_value_count(&doc), 0);
900 assert_eq!(walk_child_maps_and_count_decodes(&doc, n), n);
901 assert_eq!(walk_child_maps_and_count_decodes(&doc, n), n);
902 assert_eq!(cached_value_count(&doc), 0);
903 }
904 }
905
906 #[test]
907 fn lowering_decoded_value_cache_limit_preserves_local_edits() {
908 let n = DEFAULT_DECODED_VALUE_CACHE_LIMIT * 2;
909 let source = doc_with_many_child_maps(n);
910 let snapshot = source
911 .export(crate::encoding::ExportMode::Snapshot)
912 .unwrap();
913 let doc = LoroDoc::new_auto_commit();
914 // Setting the limit before import must also work.
915 doc.set_decoded_value_cache_limit(n + 1);
916 doc.import(&snapshot).unwrap();
917 walk_child_maps_and_count_decodes(&doc, n);
918
919 let id = doc
920 .get_list("list")
921 .get(0)
922 .unwrap()
923 .as_container()
924 .unwrap()
925 .clone();
926 let first = doc.get_map(id);
927 first.insert("edited", true).unwrap();
928 // This also exercises the stale queue entry left by lazy -> State.
929 doc.set_decoded_value_cache_limit(0);
930 assert_eq!(cached_value_count(&doc), 0);
931 assert_eq!(first.get("edited"), Some(true.into()));
932 walk_child_maps_and_count_decodes(&doc, n);
933
934 let restored = LoroDoc::new();
935 restored
936 .import(&doc.export(crate::encoding::ExportMode::Snapshot).unwrap())
937 .unwrap();
938 assert_eq!(restored.get_deep_value(), doc.get_deep_value());
939 }
940
941 /// Regression test for loro-dev/loro#1092: walking an imported document
942 /// container by container must not pin every decoded value in memory.
943 #[test]
944 fn handle_reads_bound_cached_container_values() {
945 let n = DEFAULT_DECODED_VALUE_CACHE_LIMIT * 4;
946 let source = doc_with_many_child_maps(n);
947 let bytes = export_container_store(&source);
948 let mut store = decode_container_store(bytes);
949
950 let list_idx = store
951 .arena
952 .register_container(&ContainerID::new_root("list", ContainerType::List));
953 assert_eq!(store.list_len(list_idx), n);
954 for i in 0..n {
955 let value = store.list_get(list_idx, i).unwrap();
956 let child_id = value.as_container().unwrap().clone();
957 let child_idx = store.arena.register_container(&child_id);
958 assert_eq!(store.map_get(child_idx, "key"), Some((i as i64).into()));
959 }
960
961 assert!(
962 store.store.cached_value_count_for_test() <= DEFAULT_DECODED_VALUE_CACHE_LIMIT,
963 "cached decoded values must stay bounded, got {}",
964 store.store.cached_value_count_for_test()
965 );
966 }
967
968 /// Evicted containers are pure KV caches: re-reading and editing them after
969 /// eviction must return and preserve the correct values.
970 #[test]
971 fn evicted_containers_stay_readable_and_editable() {
972 let n = DEFAULT_DECODED_VALUE_CACHE_LIMIT * 4;
973 let source = doc_with_many_child_maps(n);
974 let snapshot = source
975 .export(crate::encoding::ExportMode::Snapshot)
976 .unwrap();
977 let imported = LoroDoc::new_auto_commit();
978 imported.import(&snapshot).unwrap();
979
980 let read_all = |doc: &LoroDoc| {
981 let list = doc.get_list("list");
982 for i in 0..n {
983 let value = list.get(i).unwrap();
984 let child_id = value.as_container().unwrap().clone();
985 let child = doc.get_map(child_id);
986 assert_eq!(child.get("key"), Some((i as i64).into()));
987 }
988 };
989
990 // The first walk evicts the early children; the second walk re-reads
991 // them through the KV fallback.
992 read_all(&imported);
993 read_all(&imported);
994
995 // Mutating an evicted-then-reloaded container must persist.
996 let first_id = imported
997 .get_list("list")
998 .get(0)
999 .unwrap()
1000 .as_container()
1001 .unwrap()
1002 .clone();
1003 imported.get_map(first_id).insert("edited", true).unwrap();
1004
1005 let snapshot = imported
1006 .export(crate::encoding::ExportMode::Snapshot)
1007 .unwrap();
1008 let round_tripped = LoroDoc::new();
1009 round_tripped.import(&snapshot).unwrap();
1010 assert_eq!(round_tripped.get_deep_value(), imported.get_deep_value());
1011 }
1012
1013 /// `load_all` (and GC snapshot imports) put the store in `AllLoaded` mode;
1014 /// evicted entries must still be re-created from the KV store there.
1015 #[test]
1016 fn evicted_entries_stay_readable_when_all_loaded() {
1017 let n = DEFAULT_DECODED_VALUE_CACHE_LIMIT * 4;
1018 let source = doc_with_many_child_maps(n);
1019 let bytes = export_container_store(&source);
1020 let mut store = decode_container_store(bytes);
1021
1022 let list_idx = store
1023 .arena
1024 .register_container(&ContainerID::new_root("list", ContainerType::List));
1025 store.store.load_all();
1026
1027 for i in 0..n {
1028 let value = store.list_get(list_idx, i).unwrap();
1029 let child_id = value.as_container().unwrap().clone();
1030 let child_idx = store.arena.register_container(&child_id);
1031 assert_eq!(store.map_get(child_idx, "key"), Some((i as i64).into()));
1032 }
1033
1034 assert!(
1035 store.store.cached_value_count_for_test() <= DEFAULT_DECODED_VALUE_CACHE_LIMIT,
1036 "cached decoded values must stay bounded, got {}",
1037 store.store.cached_value_count_for_test()
1038 );
1039
1040 // `AllLoaded` must not blind full enumeration to evicted entries: once
1041 // an eviction has happened, `load_all` re-scans the KV store instead of
1042 // short-circuiting on `load_state`.
1043 assert_eq!(store.store.iter_all_container_ids().count(), n + 1);
1044
1045 // The first children were evicted during the walk; re-reading them must
1046 // fall back to the KV store even in AllLoaded mode.
1047 for i in 0..n {
1048 let value = store.list_get(list_idx, i).unwrap();
1049 let child_id = value.as_container().unwrap().clone();
1050 let child_idx = store.arena.register_container(&child_id);
1051 assert_eq!(store.map_get(child_idx, "key"), Some((i as i64).into()));
1052 }
1053 }
1054
1055 /// Mergeable children and tree meta maps are reachable through a parent
1056 /// marker / a tree node rather than a plain value slot. Evicting their
1057 /// cached values must not lose them: re-read through the parent/path,
1058 /// mutate, and snapshot round-trip.
1059 #[test]
1060 fn evicted_mergeable_child_and_tree_meta_survive_round_trip() {
1061 let filler = DEFAULT_DECODED_VALUE_CACHE_LIMIT * 2;
1062 let source = LoroDoc::new_auto_commit();
1063 source
1064 .get_map("state")
1065 .ensure_mergeable_text("notes")
1066 .unwrap()
1067 .insert(0, "hello", PosType::Unicode)
1068 .unwrap();
1069 let node = source.get_tree("tree").create(TreeParentId::Root).unwrap();
1070 source
1071 .get_tree("tree")
1072 .get_meta(node)
1073 .unwrap()
1074 .insert("k", "v")
1075 .unwrap();
1076 let list = source.get_list("list");
1077 for i in 0..filler {
1078 let map = list
1079 .insert_container(i, MapHandler::new_detached())
1080 .unwrap();
1081 map.insert("key", i as i64).unwrap();
1082 }
1083 let snapshot = source
1084 .export(crate::encoding::ExportMode::Snapshot)
1085 .unwrap();
1086
1087 let doc = LoroDoc::new_auto_commit();
1088 doc.import(&snapshot).unwrap();
1089
1090 // Cache the mergeable child and the tree meta values, then evict them
1091 // by reading more containers than the cache bound.
1092 let notes = doc.get_map("state").ensure_mergeable_text("notes").unwrap();
1093 assert_eq!(notes.to_string(), "hello");
1094 let meta = doc.get_tree("tree").get_meta(node).unwrap();
1095 assert_eq!(meta.get("k"), Some("v".into()));
1096 let list = doc.get_list("list");
1097 for i in 0..filler {
1098 let child_id = list.get(i).unwrap().as_container().unwrap().clone();
1099 assert_eq!(doc.get_map(child_id).get("key"), Some((i as i64).into()));
1100 }
1101 {
1102 let mut state = doc.app_state().lock();
1103 assert!(
1104 state.store.store.cached_value_count_for_test()
1105 <= DEFAULT_DECODED_VALUE_CACHE_LIMIT,
1106 "the walk must have evicted cached values, got {}",
1107 state.store.store.cached_value_count_for_test()
1108 );
1109 }
1110
1111 // Re-read through the parent marker / tree path after eviction, then
1112 // mutate both.
1113 let notes = doc.get_map("state").ensure_mergeable_text("notes").unwrap();
1114 assert_eq!(notes.to_string(), "hello");
1115 notes.insert(5, "!", PosType::Unicode).unwrap();
1116 let meta = doc.get_tree("tree").get_meta(node).unwrap();
1117 assert_eq!(meta.get("k"), Some("v".into()));
1118 meta.insert("k2", "v2").unwrap();
1119
1120 let snapshot = doc.export(crate::encoding::ExportMode::Snapshot).unwrap();
1121 let round_tripped = LoroDoc::new();
1122 round_tripped.import(&snapshot).unwrap();
1123 assert_eq!(round_tripped.get_deep_value(), doc.get_deep_value());
1124 assert_eq!(
1125 round_tripped
1126 .get_map("state")
1127 .ensure_mergeable_text("notes")
1128 .unwrap()
1129 .to_string(),
1130 "hello!"
1131 );
1132 assert_eq!(
1133 round_tripped
1134 .get_tree("tree")
1135 .get_meta(node)
1136 .unwrap()
1137 .get("k2"),
1138 Some("v2".into())
1139 );
1140 }
1141
1142 /// A wrapper that is mutated while enqueued in the value-cache queue
1143 /// materializes into a full state, leaving a stale queue entry behind.
1144 /// Eviction must skip the stale entry without losing the mutation or
1145 /// wedging the queue.
1146 #[test]
1147 fn stale_queue_entry_after_lazy_to_state_conversion() {
1148 let n = DEFAULT_DECODED_VALUE_CACHE_LIMIT * 2;
1149 let source = doc_with_many_child_maps(n);
1150 let snapshot = source
1151 .export(crate::encoding::ExportMode::Snapshot)
1152 .unwrap();
1153 let doc = LoroDoc::new_auto_commit();
1154 doc.import(&snapshot).unwrap();
1155
1156 // Read child 0 (cached + enqueued), then mutate it: the lazy wrapper
1157 // materializes into a full state and its queue entry becomes stale.
1158 let list = doc.get_list("list");
1159 let first_id = list.get(0).unwrap().as_container().unwrap().clone();
1160 let first_map = doc.get_map(first_id);
1161 assert_eq!(first_map.get("key"), Some(0i64.into()));
1162 first_map.insert("edited", true).unwrap();
1163
1164 // Keep reading past the bound so eviction pops the stale entry.
1165 for i in 0..n {
1166 let child_id = list.get(i).unwrap().as_container().unwrap().clone();
1167 assert_eq!(doc.get_map(child_id).get("key"), Some((i as i64).into()));
1168 }
1169 {
1170 let mut state = doc.app_state().lock();
1171 assert!(
1172 state.store.store.cached_value_count_for_test()
1173 <= DEFAULT_DECODED_VALUE_CACHE_LIMIT,
1174 "cached decoded values must stay bounded, got {}",
1175 state.store.store.cached_value_count_for_test()
1176 );
1177 }
1178
1179 assert_eq!(first_map.get("edited"), Some(true.into()));
1180 let round_tripped = LoroDoc::new();
1181 round_tripped
1182 .import(&doc.export(crate::encoding::ExportMode::Snapshot).unwrap())
1183 .unwrap();
1184 assert_eq!(round_tripped.get_deep_value(), doc.get_deep_value());
1185 }
1186}