forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

dead_containers_cache.rs391 lines, 15.5 KiBHistoryRawDownload
1use super::DocState;
2use crate::container::idx::ContainerIdx;
3use loro_common::ContainerType;
4use rustc_hash::FxHashSet;
5use smallvec::SmallVec;
6
7/// Containers known to be deleted. See `context/dead-container-cache.md`.
8#[derive(Default, Debug, Clone)]
9pub(super) struct DeadContainersCache {
10 /// Removed from a Map or List: no later version gives them back.
11 final_deletions: FxHashSet<ContainerIdx>,
12 /// Cut off at a Tree or MovableList edge: a later move can revive them.
13 revivable: FxHashSet<ContainerIdx>,
14}
15
16impl DeadContainersCache {
17 /// Must be called whenever the state may move to a version that is not a
18 /// descendant of the current one (checkout, reset), because that can
19 /// revive any container.
20 pub fn clear(&mut self) {
21 self.final_deletions.clear();
22 self.clear_revivable();
23 }
24
25 /// Must be called whenever a tree or movable-list change is applied going
26 /// forward, because it may move a deleted node or element back.
27 pub fn clear_revivable(&mut self) {
28 // Reusing a large table makes interleaved deletion queries and moves
29 // repeatedly clear its peak capacity, even with only one live entry.
30 self.revivable = FxHashSet::default();
31 }
32
33 fn contains(&self, idx: &ContainerIdx) -> bool {
34 self.final_deletions.contains(idx) || self.revivable.contains(idx)
35 }
36}
37
38impl DocState {
39 /// Called when a failed import is rolled back. The import may have registered parent links
40 /// that the arena rollback drops, and a deletion found through one of them while it ran
41 /// (e.g. by a query on another thread) is not true of the kept history.
42 /// See `context/failed-import-arena-indices.md`.
43 pub(crate) fn forget_parent_link_caches_after_failed_import(&mut self) {
44 self.dead_containers_cache.clear();
45 }
46
47 pub(crate) fn is_deleted(&mut self, idx: ContainerIdx) -> bool {
48 #[cfg(not(debug_assertions))]
49 {
50 if self.dead_containers_cache.contains(&idx) {
51 return true;
52 }
53 }
54
55 // Parent chains are shallow (depth 1 for a root container), so inline
56 // storage avoids a heap allocation on this per-op check.
57 let mut visited: SmallVec<[ContainerIdx; 4]> = SmallVec::new();
58 visited.push(idx);
59 let mut idx = idx;
60 let mut depends_on_mergeable_edge = false;
61 // The parent that no longer holds the chain, if any.
62 let (is_deleted, cut_at) = loop {
63 let id = self.arena.idx_to_id(idx).unwrap();
64 if id.is_mergeable() {
65 depends_on_mergeable_edge = true;
66 }
67 if let Some(parent_idx) = self.arena.get_parent(idx) {
68 if !self.contains_logical_child(parent_idx, &id) {
69 break (true, Some(parent_idx));
70 }
71
72 idx = parent_idx;
73 visited.push(idx);
74 } else {
75 // No parent in the arena: top-level Roots are always alive; anything else
76 // (including a mergeable Root whose parent edge was never wired) is treated
77 // as deleted. A later op can still attach it, so this is never cached.
78 break (!id.is_root() || id.is_mergeable(), None);
79 }
80 };
81
82 // Every container on the walked chain shares the answer: below the
83 // missing edge all of them are deleted, otherwise all are alive.
84 #[cfg(debug_assertions)]
85 for idx in visited.iter() {
86 assert!(
87 is_deleted || !self.dead_containers_cache.contains(idx),
88 "stale dead-container cache entry for {:?}",
89 self.arena.idx_to_id(*idx)
90 );
91 }
92
93 // A mergeable ancestor can be deleted and later reactivated by changing the parent map's
94 // marker. Do not cache deletion for any descendant whose liveness depends on that
95 // logical edge, including ordinary children nested inside a mergeable map.
96 if is_deleted && !depends_on_mergeable_edge {
97 match cut_at.map(|parent| parent.get_type()) {
98 Some(ContainerType::Map | ContainerType::List) => {
99 self.dead_containers_cache.final_deletions.extend(visited)
100 }
101 Some(ContainerType::Tree | ContainerType::MovableList) => {
102 self.dead_containers_cache.revivable.extend(visited)
103 }
104 _ => {}
105 }
106 }
107
108 is_deleted
109 }
110
111 #[cfg(test)]
112 pub(crate) fn dead_cache_entry(&self, idx: ContainerIdx) -> Option<bool> {
113 self.dead_containers_cache.contains(&idx).then_some(true)
114 }
115}
116
117#[cfg(test)]
118#[cfg(feature = "counter")]
119mod tests {
120 use loro_common::ContainerID;
121
122 use crate::{cursor::PosType, HandlerTrait, LoroDoc, TextHandler};
123
124 /// A mergeable child can be deleted and then reactivated: `delete(key)` clears its
125 /// marker (child unreachable), and a later `ensure_mergeable_<kind>(key)` writes the
126 /// marker back (child reachable again). While the child is unreachable, querying its
127 /// liveness must not cache a `deleted` entry because that answer depends on the mutable
128 /// mergeable marker edge.
129 ///
130 /// The scenario:
131 /// 1. Create the mergeable counter and capture its container idx.
132 /// 2. Delete the key, then query `is_deleted()`.
133 /// 3. Re-get the counter to rewrite the marker and reactivate the child.
134 /// 4. Assert the cache never held a `deleted` entry for that idx.
135 ///
136 /// It asserts the cache contents directly because `is_deleted()` only trusts the cache via a
137 /// release-only early return; inspecting the cache makes stale-cache regressions fail in both
138 /// debug and release builds.
139 #[test]
140 fn reactivated_mergeable_child_has_no_stale_dead_cache_entry() {
141 let doc = LoroDoc::new_auto_commit();
142 doc.set_peer_id(1).unwrap();
143 let root = doc.get_map("state");
144 let counter = root.ensure_mergeable_counter("revision").unwrap();
145 counter.increment(1.0).unwrap();
146 doc.commit_then_renew();
147
148 let cid: ContainerID = counter.id();
149 let idx = doc.state.lock().arena.id_to_idx(&cid).unwrap();
150
151 root.delete("revision").unwrap();
152 doc.commit_then_renew();
153 assert!(counter.is_deleted());
154 assert_eq!(
155 doc.state.lock().dead_cache_entry(idx),
156 None,
157 "mergeable-dependent deletion must not be cached"
158 );
159
160 root.ensure_mergeable_counter("revision").unwrap();
161 doc.commit_then_renew();
162 assert_eq!(
163 doc.state.lock().dead_cache_entry(idx),
164 None,
165 "reactivation must drop the stale deleted-cache entry"
166 );
167 }
168
169 /// The no-cache rule also applies to ordinary descendants under a mergeable ancestor. A
170 /// regular child container can look cache-safe by cid shape, but its liveness still depends on
171 /// the ancestor's marker edge.
172 #[test]
173 fn ordinary_child_under_reactivated_mergeable_map_has_no_stale_dead_cache_entry() {
174 let doc = LoroDoc::new_auto_commit();
175 doc.set_peer_id(1).unwrap();
176 let root = doc.get_map("state");
177 let profile = root.ensure_mergeable_map("profile").unwrap();
178 let text = profile
179 .insert_container("bio", TextHandler::new_detached())
180 .unwrap();
181 text.insert(0, "Ada", PosType::Unicode).unwrap();
182 doc.commit_then_renew();
183
184 let text_id: ContainerID = text.id();
185 let text_idx = doc.state.lock().arena.id_to_idx(&text_id).unwrap();
186
187 root.delete("profile").unwrap();
188 doc.commit_then_renew();
189 assert!(text.is_deleted());
190 assert_eq!(
191 doc.state.lock().dead_cache_entry(text_idx),
192 None,
193 "ordinary descendants behind a mergeable edge must not be cached as deleted"
194 );
195
196 root.ensure_mergeable_map("profile").unwrap();
197 doc.commit_then_renew();
198 assert!(!text.is_deleted());
199 assert_eq!(
200 doc.state.lock().dead_cache_entry(text_idx),
201 None,
202 "reactivated ordinary descendant must not leave a stale cache entry"
203 );
204 }
205
206 /// The same stale-cache hazard exists when reactivation arrives from a *peer* via import,
207 /// not just from a local `ensure_mergeable_*` call. The importing peer must not cache the
208 /// mergeable-dependent deleted result before the reactivation update arrives.
209 ///
210 /// The scenario, with two peers A (author) and B (importer):
211 /// 1. A creates the mergeable counter and deletes the key, then exports.
212 /// 2. B imports A's updates so the child exists but is unreachable, and queries
213 /// `is_deleted()`.
214 /// 3. A re-gets the counter (rewriting the marker, reactivating the child) and
215 /// exports just that new update.
216 /// 4. B imports the reactivation update.
217 /// 5. Assert B's cache never held a `deleted` entry for that idx.
218 ///
219 /// Like the local-reactivation test, this asserts cache contents directly rather than
220 /// through `is_deleted()`, because `is_deleted()` only trusts the cache via a release-only
221 /// early return; a public-API assertion would pass in debug even with the bug present.
222 #[test]
223 fn imported_mergeable_child_reactivation_clears_dead_cache() {
224 use crate::loro::ExportMode;
225
226 let doc_a = LoroDoc::new_auto_commit();
227 doc_a.set_peer_id(1).unwrap();
228 let root_a = doc_a.get_map("state");
229 let counter_a = root_a.ensure_mergeable_counter("revision").unwrap();
230 counter_a.increment(1.0).unwrap();
231 doc_a.commit_then_renew();
232 root_a.delete("revision").unwrap();
233 doc_a.commit_then_renew();
234
235 let cid: ContainerID = counter_a.id();
236
237 // B imports A's history: the child exists but is unreachable (marker cleared).
238 let doc_b = LoroDoc::new_auto_commit();
239 doc_b.set_peer_id(2).unwrap();
240 doc_b
241 .import(&doc_a.export(ExportMode::all_updates()).unwrap())
242 .unwrap();
243
244 let idx = doc_b.state.lock().arena.id_to_idx(&cid).unwrap();
245 assert!(doc_b.state.lock().is_deleted(idx));
246 assert_eq!(
247 doc_b.state.lock().dead_cache_entry(idx),
248 None,
249 "imported mergeable-dependent deletion must not be cached"
250 );
251
252 // A reactivates the child locally and exports just the new update.
253 let vv_before = doc_a.oplog_vv();
254 root_a.ensure_mergeable_counter("revision").unwrap();
255 doc_a.commit_then_renew();
256 let reactivation = doc_a.export(ExportMode::updates(&vv_before)).unwrap();
257
258 // B imports the reactivation. There must be no stale deleted-cache entry left to mask it.
259 doc_b.import(&reactivation).unwrap();
260 assert_eq!(
261 doc_b.state.lock().dead_cache_entry(idx),
262 None,
263 "imported reactivation must drop the stale deleted-cache entry"
264 );
265 }
266
267 /// A tree node under a deleted ancestor is revived by moving it out, so a
268 /// local move must drop the cached deletion of its metadata.
269 #[test]
270 fn local_tree_move_drops_revivable_deletions() {
271 use crate::state::TreeParentId;
272
273 let doc = LoroDoc::new_auto_commit();
274 doc.set_peer_id(1).unwrap();
275 let tree = doc.get_tree("tree");
276 let parent = tree.create(TreeParentId::Root).unwrap();
277 let child = tree.create(TreeParentId::Node(parent)).unwrap();
278 let meta = tree.get_meta(child).unwrap();
279 doc.commit_then_renew();
280 tree.delete(parent).unwrap();
281 doc.commit_then_renew();
282
283 let idx = doc.state.lock().arena.id_to_idx(&meta.id()).unwrap();
284 assert!(meta.is_deleted());
285 assert_eq!(doc.state.lock().dead_cache_entry(idx), Some(true));
286
287 tree.mov(child, TreeParentId::Root).unwrap();
288 assert_eq!(doc.state.lock().dead_cache_entry(idx), None);
289 doc.commit_then_renew();
290 assert!(!meta.is_deleted());
291 }
292
293 /// A movable-list element deleted locally is revived by a concurrent move
294 /// with a greater lamport, so importing movable-list changes must drop the
295 /// cached deletion.
296 #[test]
297 fn movable_list_import_drops_revivable_deletions() {
298 use crate::{loro::ExportMode, MapHandler};
299
300 let doc = LoroDoc::new_auto_commit();
301 doc.set_peer_id(1).unwrap();
302 let list = doc.get_movable_list("list");
303 list.insert(0, 0).unwrap();
304 let child = list
305 .insert_container(1, MapHandler::new_detached())
306 .unwrap();
307 doc.commit_then_renew();
308 let other = LoroDoc::new_auto_commit();
309 other.set_peer_id(2).unwrap();
310 other
311 .import(&doc.export(ExportMode::all_updates()).unwrap())
312 .unwrap();
313 other.get_map("pad").insert("k", 1).unwrap();
314 other.commit_then_renew();
315 other.get_movable_list("list").mov(1, 0).unwrap();
316 other.commit_then_renew();
317
318 list.delete(1, 1).unwrap();
319 doc.commit_then_renew();
320 let idx = doc.state.lock().arena.id_to_idx(&child.id()).unwrap();
321 assert!(child.is_deleted());
322 assert_eq!(doc.state.lock().dead_cache_entry(idx), Some(true));
323
324 doc.import(&other.export(ExportMode::all_updates()).unwrap())
325 .unwrap();
326 assert_eq!(doc.state.lock().dead_cache_entry(idx), None);
327 assert!(!child.is_deleted());
328 }
329
330 /// Map and list removals are final for every later version, so they are
331 /// cached for the child and everything below it.
332 #[test]
333 fn map_and_list_child_deletions_are_cached() {
334 use crate::{ListHandler, MapHandler};
335
336 let doc = LoroDoc::new_auto_commit();
337 doc.set_peer_id(1).unwrap();
338 let map = doc.get_map("map");
339 let in_map = map
340 .insert_container("k", MapHandler::new_detached())
341 .unwrap();
342 let nested = in_map
343 .insert_container("t", TextHandler::new_detached())
344 .unwrap();
345 let list = doc.get_list("list");
346 let in_list = list
347 .insert_container(0, ListHandler::new_detached())
348 .unwrap();
349 doc.commit_then_renew();
350 map.delete("k").unwrap();
351 list.delete(0, 1).unwrap();
352 doc.commit_then_renew();
353
354 assert!(nested.is_deleted());
355 assert!(in_list.is_deleted());
356 let state = doc.state.lock();
357 for id in [in_map.id(), nested.id(), in_list.id()] {
358 let idx = state.arena.id_to_idx(&id).unwrap();
359 assert_eq!(state.dead_cache_entry(idx), Some(true), "{id:?}");
360 }
361 }
362
363 /// While checked out to an older version, a map child created later is
364 /// cut at its map parent and cached as a final deletion. A forward
365 /// checkout is not a `DiffMode::Checkout` transition, but it must still
366 /// drop that entry.
367 #[test]
368 fn forward_checkout_drops_deletions_cached_behind_the_oplog() {
369 use crate::MapHandler;
370
371 let doc = LoroDoc::new_auto_commit();
372 doc.set_peer_id(1).unwrap();
373 let map = doc.get_map("m");
374 map.insert("a", 1).unwrap();
375 doc.commit_then_renew();
376 let v1 = doc.oplog_frontiers();
377 let child = map
378 .insert_container("c", MapHandler::new_detached())
379 .unwrap();
380 doc.commit_then_renew();
381
382 doc.checkout(&v1).unwrap();
383 let idx = doc.state.lock().arena.id_to_idx(&child.id()).unwrap();
384 assert!(child.is_deleted());
385 assert_eq!(doc.state.lock().dead_cache_entry(idx), Some(true));
386
387 doc.checkout_to_latest();
388 assert_eq!(doc.state.lock().dead_cache_entry(idx), None);
389 assert!(!child.is_deleted());
390 }
391}