From 0b8dae1401fc3a448b9c8a9d78db9819b4b8e26c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 12:37:46 -0800 Subject: [PATCH] Delete: removing objects one at a time keeps the id lookup cache Every Document::remove_many cleared the id lookup cache, and the next lookup with no cache walked the tree once to answer and again to rebuild it. Deleting objects one by id at a time with edit.clear walked the whole tree twice per Delete: 20,005 walks for 10,000 objects. - remove_many keeps the cache and records which children it took out of each parent. A cached path then counts a node's index among its siblings less the removed siblings before it, so the nodes left are found without a walk whichever objects were removed (top, bottom, middle, or the art below a layer's ruler guides). The cache has no path for a removed node or a node inside one. The cache is still dropped once the removed nodes are half of its entries, and when it does not have a listed node where it is. - index_path with no cache builds the cache and answers from it, in one walk. An id that appears more than once is still walked to, so the first in tree order is returned as before. Release build, deleting each object of one layer by id with nothing selected. Walks for 1,000 objects went from 2,005 to 14 in each order. For 10,000 objects, median of three runs: from the top: 20,005 walks, 5.53 s -> 15 walks, 4.28 s from the bottom: 20,005 walks, 11.24 s -> 15 walks, 10.87 s from the middle: 20,005 walks, 10.62 s -> 15 walks, 8.62 s Each Delete is still one undo step. The time left still grows with the square of the count: each Delete rebuilds the parent's child list and keeps a copy of the document for undo, and this change does not touch either. --- crates/doc/src/document.rs | 51 ++++++++-- crates/doc/src/id_index.rs | 125 ++++++++++++++++++++----- crates/doc/src/tests/lookups.rs | 114 ++++++++++++++++++++++ crates/engine/src/tests/large_edits.rs | 38 ++++++++ 4 files changed, 300 insertions(+), 28 deletions(-) diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 04a96c97fd..3e5743aec3 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -343,18 +343,27 @@ impl Document { /// tree order where `id` appears. pub fn index_path(&self, id: NodeId) -> Option> { crate::id_index::note_path_lookup(); + // No cache yet: build it, and answer from it (an id it doesn't have is not in the tree; one + // that appears more than once is walked to, as below). + let Some(cached) = self.index.get() else { + let fresh = self.index.rebuild(&self.layers); + return match fresh.get(&id) { + Some(Some(p)) => Some(p), + _ if fresh.contains_key(&id) => self.walk_index_path(id), + _ => None, + }; + }; // The cached path, while the node there still has the id ([`id_index`]). - let cached = self.index.get(); - match cached.as_ref().and_then(|m| m.get(&id)) { + match cached.get(&id) { Some(Some(p)) if self.node_at(&p).is_some_and(|n| n.id == id) => return Some(p), Some(None) => return self.walk_index_path(id), _ => {} } - // A stale path (the tree changed), an id the cache doesn't have (deleted or added since), - // or no cache yet: walk, and rebuild now and then. + // A stale path (the tree changed) or an id the cache doesn't have (deleted or added + // since): walk, and rebuild now and then. let found = self.walk_index_path(id); - let stale = cached.as_ref().is_some_and(|m| m.contains_key(&id)); - if cached.is_none() || ((stale || found.is_some()) && self.index.missed()) { + let stale = cached.contains_key(&id); + if (stale || found.is_some()) && self.index.missed() { self.index.rebuild(&self.layers); } found @@ -618,10 +627,38 @@ impl Document { /// children of each parent. Each id is listed once and none lies inside another listed node, as /// in a list of top-level objects. For an id that is not in the tree, is listed twice or lies /// inside another listed node, it fails with `NoNode` and leaves the document as it was. + /// + /// The lookup cache ([`id_index`]) is kept, with the listed nodes taken out of it, while it has + /// each listed node where it is, until the nodes removed since it was built are half its + /// entries; otherwise it is cleared. pub fn remove_many(&mut self, ids: &[NodeId]) -> Result>, DocError> { let places = self.places(ids)?; + // Each listed node's place in the cache's table, while the cache has it where it is. + let gone = self.index.get().and_then(|cache| { + let listed = places.iter().flat_map(|(up, kids)| kids.iter().map(move |&(i, k)| (up, i, k))); + listed + .map(|(up, i, k)| { + let id = ids.get(k)?; + let path = cache.get(id)??; + (path.split_last() == Some((&i, up.as_slice()))).then(|| cache.table_place(id)).flatten() + }) + .collect::>>() + }); let removed = self.take(places, ids.len())?; - self.index.clear(); + // The removed nodes, as the cache counts them (ruler guides included), up to `limit`. + let count = |limit: usize| { + let mut n = 0usize; + let mut each = |_: &Node| { + n += 1; + if n >= limit { std::ops::ControlFlow::Break(()) } else { std::ops::ControlFlow::Continue(()) } + }; + let _ = removed.iter().try_for_each(|r| r.try_walk(&mut each)); + n + }; + match gone { + Some(gone) if !self.index.removed(count) => self.index.take_out(&gone), + _ => self.index.clear(), + } Ok(removed) } diff --git a/crates/doc/src/id_index.rs b/crates/doc/src/id_index.rs index 149a8e488b..34453234ec 100644 --- a/crates/doc/src/id_index.rs +++ b/crates/doc/src/id_index.rs @@ -4,10 +4,15 @@ //! The tree is edited in many places through public fields, so the cache can't be kept in step //! with it. It is checked instead: a cached path is used only while the node at that path still //! has the id (a check as deep as the tree). A path that no longer checks out rebuilds the cache, -//! and an id the cache doesn't have (deleted, or added since) is looked up by walking, as before. +//! and an id the cache doesn't have (added since, or removed) is looked up by walking, as before. //! An id that appears more than once (a damaged file) is never cached, so lookups keep returning //! its first place in tree order. //! +//! [`crate::Document::remove_many`] keeps the cache and notes the nodes it removes, so the cache +//! places each node after a removed sibling one lower and finds no path for a removed node or one +//! inside it. Once the removed nodes are half the cache's entries, the cache is let go. The first +//! lookup with no cache builds it and answers from it. +//! //! The one case a cached lookup can answer differently from a walk: a second node with an //! existing id put in the tree *after* the cache was built, earlier in tree order than the first. //! The lookup then returns the original node (also one with that id) instead of the new one. The @@ -48,10 +53,25 @@ fn multiplier() -> u64 { /// A map keyed by node id with [`IdHasher`]. pub type IdMap = HashMap>; -/// Where each node is: its parent's entry (`u32::MAX` for a top-level layer) and its index among -/// its siblings. One flat table, so building it allocates nothing per node. -#[derive(Default)] + +/// The children removed from each parent since the table was built: the parent's entry (`u32::MAX` +/// for the top-level layers) and the removed children's indices in the table, sorted. +type Gaps = HashMap>; + +/// The cache as a document reads it: the table, and the nodes removed from the tree since it was +/// built. A node's index among its siblings is its index in the table less the removed siblings +/// before it. +#[derive(Clone)] pub(crate) struct Paths { + table: Arc, + gaps: Arc, +} + +/// Where each node was when the cache was built: its parent's entry (`u32::MAX` for a top-level +/// layer) and its index among its siblings. One flat table, so building it allocates nothing per +/// node. +#[derive(Default)] +struct Table { /// Each id's entry in `at`; `None` for an id that appears more than once. ids: IdMap>, at: Vec<(u32, u32)>, @@ -59,15 +79,15 @@ pub(crate) struct Paths { impl Paths { /// The index path of `id`: `Some(None)` when the id appears more than once, `None` when it - /// isn't in the table. + /// isn't in the table or it, or a node it is in, was removed. pub(crate) fn get(&self, id: &NodeId) -> Option>> { - let e = (*self.ids.get(id)?)?; + let e = (*self.table.ids.get(id)?)?; let mut path = Vec::new(); let mut cur = e; // Each step goes to a parent entry, made before its children: at most `at.len()` steps. - for _ in 0..=self.at.len() { - let Some(&(parent, i)) = self.at.get(cur as usize) else { return Some(None) }; - path.push(i as usize); + for _ in 0..=self.table.at.len() { + let Some(&(parent, i)) = self.table.at.get(cur as usize) else { return Some(None) }; + path.push(self.shifted(parent, i)? as usize); if parent == u32::MAX { path.reverse(); return Some(Some(path)); @@ -76,21 +96,37 @@ impl Paths { } Some(None) } + /// Where the table has `id` as it was built: its parent's entry and its index among its + /// siblings then; `None` when the id isn't in the table or appears more than once. + pub(crate) fn table_place(&self, id: &NodeId) -> Option<(u32, u32)> { + let e = (*self.table.ids.get(id)?)?; + self.table.at.get(e as usize).copied() + } pub(crate) fn contains_key(&self, id: &NodeId) -> bool { - self.ids.contains_key(id) + self.table.ids.contains_key(id) } pub(crate) fn len(&self) -> usize { - self.ids.len() + self.table.ids.len() } /// The entry of `id` in the table: `Some(None)` when the id appears more than once, `None` /// when it isn't in the table. pub(crate) fn entry(&self, id: &NodeId) -> Option> { - self.ids.get(id).copied() + self.table.ids.get(id).copied() } /// Entry `e`'s parent entry (`u32::MAX` for a top-level layer) and its index among its - /// siblings. + /// siblings; `None` when the node at `e` was removed. pub(crate) fn place(&self, e: u32) -> Option<(u32, u32)> { - self.at.get(e as usize).copied() + let (parent, i) = self.table.at.get(e as usize).copied()?; + Some((parent, self.shifted(parent, i)?)) + } + /// The index among its siblings of the child of `parent` at index `i` in the table: `i` less + /// the removed children before it, or `None` when that child was removed. + fn shifted(&self, parent: u32, i: u32) -> Option { + let Some(gone) = self.gaps.get(&parent) else { return Some(i) }; + match gone.binary_search(&i) { + Ok(_) => None, + Err(k) => Some(i - k as u32), + } } } @@ -134,9 +170,10 @@ pub(crate) fn note_path_lookup() { PATH_LOOKUPS.set(PATH_LOOKUPS.get().saturating_add(1)); } -/// The cache, shared by clones of a document (each checks every path it uses against its own tree). +/// The cache, shared by clones of a document (each checks every path it uses against its own tree), +/// the lookups that missed it, and the nodes removed from the tree since it was built. #[derive(Default)] -pub struct IdIndex(RwLock>>, std::sync::atomic::AtomicU32); +pub struct IdIndex(RwLock>>, std::sync::atomic::AtomicU32, std::sync::atomic::AtomicUsize); impl IdIndex { /// The current cache, if one was built. @@ -150,6 +187,18 @@ impl IdIndex { *g = None; } self.1.store(0, std::sync::atomic::Ordering::Relaxed); + self.2.store(0, std::sync::atomic::Ordering::Relaxed); + } + + /// Note the nodes removed from the tree while the cache is kept (their entries go stale); true + /// when the stale entries are half the cache or more, and it's time to let it go. `count(limit)` + /// counts the removed nodes, and may stop once it reaches `limit`, the number that makes half. + /// With no cache, `count` isn't called. + pub(crate) fn removed(&self, count: impl FnOnce(usize) -> usize) -> bool { + let Some(paths) = self.get() else { return false }; + let half = paths.len().div_ceil(2); + let n = count(half.saturating_sub(self.2.load(std::sync::atomic::Ordering::Relaxed))); + self.2.fetch_add(n, std::sync::atomic::Ordering::Relaxed).saturating_add(n) >= half } /// Whether a cache was built (and not cleared since). @@ -157,9 +206,42 @@ impl IdIndex { self.0.read().is_ok_and(|g| g.is_some()) } + /// Note the nodes that [`crate::Document::remove_many`] took out of the tree, each as its place + /// in the table ([`Paths::table_place`]): the cache then places their later siblings one lower + /// for each, and has no path for them or the nodes in them. With no cache, it does nothing. + pub(crate) fn take_out(&self, gone: &[(u32, u32)]) { + let Ok(mut g) = self.0.write() else { return }; + let Some(paths) = g.as_mut() else { return }; + // Clones of the document keep the cache as it was. + let gaps = Arc::make_mut(&mut Arc::make_mut(paths).gaps); + let mut gone = gone.to_vec(); + gone.sort_unstable(); + // One merge of sorted lists per parent, so a removal of many children costs one pass. + for run in gone.chunk_by(|a, b| a.0 == b.0) { + let Some(&(parent, _)) = run.first() else { continue }; + let list = gaps.entry(parent).or_default(); + let old = std::mem::take(list); + list.reserve(old.len() + run.len()); + let (mut a, mut b) = (old.into_iter().peekable(), run.iter().map(|&(_, i)| i).peekable()); + loop { + let next = match (a.peek(), b.peek()) { + (Some(x), Some(y)) if x <= y => a.next(), + (Some(_), Some(_)) | (None, Some(_)) => b.next(), + (Some(_), None) => a.next(), + (None, None) => break, + }; + if let Some(i) = next + && list.last() != Some(&i) + { + list.push(i); + } + } + } + } + /// Rebuild the cache from `layers` (one walk) and return it. pub(crate) fn rebuild(&self, layers: &[Arc]) -> Arc { - fn walk(nodes: &[Arc], parent: u32, out: &mut Paths) { + fn walk(nodes: &[Arc], parent: u32, out: &mut Table) { for (i, n) in nodes.iter().enumerate() { let e = out.at.len() as u32; out.at.push((parent, i as u32)); @@ -170,13 +252,14 @@ impl IdIndex { } } note_tree_walk(); - let mut out = Paths::default(); - walk(layers, u32::MAX, &mut out); - let out = Arc::new(out); + let mut table = Table::default(); + walk(layers, u32::MAX, &mut table); + let out = Arc::new(Paths { table: Arc::new(table), gaps: Arc::default() }); if let Ok(mut g) = self.0.write() { *g = Some(out.clone()); } self.1.store(0, std::sync::atomic::Ordering::Relaxed); + self.2.store(0, std::sync::atomic::Ordering::Relaxed); out } @@ -189,7 +272,7 @@ impl IdIndex { impl Clone for IdIndex { fn clone(&self) -> Self { - IdIndex(RwLock::new(self.get()), Default::default()) + IdIndex(RwLock::new(self.get()), Default::default(), self.2.load(std::sync::atomic::Ordering::Relaxed).into()) } } diff --git a/crates/doc/src/tests/lookups.rs b/crates/doc/src/tests/lookups.rs index d7c24934e0..295c347765 100644 --- a/crates/doc/src/tests/lookups.rs +++ b/crates/doc/src/tests/lookups.rs @@ -261,6 +261,120 @@ fn remove_many_matches_removing_one_at_a_time() { } } +/// A document with `n` squares on its one layer, bottom to top, and their ids. +fn squares(n: usize) -> (Document, Vec) { + let mut d = Document::new(612.0, 792.0); + let layer = d.layers[0].id; + let ids = (0..n) + .map(|k| { + let s = square(&mut d); + d.insert(Some(layer), k, s).unwrap() + }) + .collect(); + (d, ids) +} + +/// The first lookup with no cache, which builds it, finds what a walk finds, an id that appears +/// more than once and one not in the tree included. +#[test] +fn a_first_lookup_with_no_cache_finds_what_a_walk_finds() { + for seed in 1..10 { + let (d, ids) = tree(seed); + for id in ids.iter().chain(&[NodeId(999_999)]) { + d.drop_lookup_cache(); + assert_eq!(d.index_path(*id), d.walk_index_path(*id), "seed {seed}: {id:?}"); + } + } +} + +/// A lookup with no cache builds it in one walk of the tree. Removing objects from the top, the +/// bottom or the middle of a layer, or a group with the objects in it, keeps the cache: the objects +/// left are found where a walk finds them, without a walk. +#[test] +fn remove_many_keeps_the_cache_whichever_objects_it_removes() { + let (mut d, ids) = squares(100); + let layer = d.layers[0].id; + let inner: Vec> = (0..3).map(|_| Arc::new(square(&mut d))).collect(); + let members: Vec = inner.iter().map(|n| n.id).collect(); + let gid = d.alloc_id(); + let group = d.insert(Some(layer), 50, Node::group(gid, inner)).unwrap(); + d.drop_lookup_cache(); + let walks = tree_walks(); + assert!(d.node(ids[0]).is_some()); + assert_eq!(tree_walks() - walks, 1, "building the cache"); + let walks = tree_walks(); + d.remove_many(&ids[90..]).unwrap(); + d.remove_many(&ids[..10]).unwrap(); + d.remove_many(&[ids[30], ids[60], ids[45]]).unwrap(); + d.remove_many(&[group]).unwrap(); + let left: Vec = ids[10..90].iter().copied().filter(|id| ![ids[30], ids[45], ids[60]].contains(id)).collect(); + let found: Vec<_> = left.iter().map(|id| d.index_path(*id)).collect(); + assert_eq!(tree_walks() - walks, 0, "after the removals"); + let walked: Vec<_> = left.iter().map(|id| d.walk_index_path(*id)).collect(); + assert_eq!(found, walked); + assert!(found.iter().all(Option::is_some)); + let middle = [ids[30], ids[45], ids[60], group]; + let mut gone = ids[..10].iter().chain(&ids[90..]).chain(&middle).chain(&members); + assert!(gone.all(|id| d.node(*id).is_none())); +} + +/// A layer keeps its ruler guides above its art: removing the topmost object moves the guides down, +/// and the cache still finds them, and the art left, without a walk. +#[test] +fn remove_many_keeps_the_cache_in_a_layer_with_ruler_guides() { + let (mut d, ids) = squares(20); + let layer = d.layers[0].id; + let guides: Vec = (0..3) + .map(|k| { + let g = Node::new(d.alloc_id(), NodeKind::RulerGuide { vertical: k % 2 == 0, pos: k as f64, artboard: None }); + d.insert(Some(layer), usize::MAX, g).unwrap() + }) + .collect(); + d.drop_lookup_cache(); + d.node(ids[0]); + let walks = tree_walks(); + for id in ids.iter().rev().take(5) { + d.remove_many(&[*id]).unwrap(); + let rest = ids[..15].iter().chain(&guides); + assert!(rest.into_iter().all(|id| d.index_path(*id) == d.walk_index_path(*id) && d.node(*id).is_some_and(|n| n.id == *id))); + } + assert!(d.has_lookup_cache()); + // Each pass above walked once per id to compare: 18 ids, 5 passes. + assert_eq!(tree_walks() - walks, 18 * 5, "only the comparison walks"); +} + +/// Removing the top objects one at a time keeps the cache only while the removed nodes are less +/// than half of its entries, so it doesn't keep growing stale. A removed layer counts every node in +/// it, its ruler guides included. +#[test] +fn remove_many_lets_the_cache_go_once_half_of_it_is_removed() { + let (mut d, ids) = squares(100); + d.drop_lookup_cache(); + d.node(ids[0]); + // The layer and its 100 squares. + let entries = 101; + let mut removed = 0; + for id in ids.iter().rev() { + d.remove_many(&[*id]).unwrap(); + removed += 1; + assert_eq!(d.has_lookup_cache(), removed * 2 < entries, "after {removed} removals"); + if !d.has_lookup_cache() { + break; + } + } + assert!(removed < ids.len(), "the cache went before the last removal"); + + let (mut d, ids) = squares(100); + let top = d.add_layer(None); + let guides: Vec> = + (0..200).map(|k| Arc::new(Node::new(d.alloc_id(), NodeKind::RulerGuide { vertical: false, pos: k as f64, artboard: None }))).collect(); + d.children_mut(Some(top)).unwrap().extend(guides); + d.drop_lookup_cache(); + d.node(ids[0]); + d.remove_many(&[top]).unwrap(); + assert!(!d.has_lookup_cache(), "the removed layer and its 200 guides are most of the cache"); +} + #[test] fn insert_beside_matches_inserting_one_at_a_time() { for seed in 1..40 { diff --git a/crates/engine/src/tests/large_edits.rs b/crates/engine/src/tests/large_edits.rs index aa18cef1ec..b29977b75f 100644 --- a/crates/engine/src/tests/large_edits.rs +++ b/crates/engine/src/tests/large_edits.rs @@ -120,6 +120,44 @@ fn delete_of_100000_objects_takes_few_tree_walks() { undo_gives_back(&mut s, &before); } +#[test] +fn deleting_2000_objects_by_id_one_at_a_time_takes_few_tree_walks() { + // From the top down, from the bottom up, and from the middle out. + let orders: [fn(Vec) -> Vec; 3] = [ + |ids| ids.into_iter().rev().collect(), + |ids| ids, + |ids| { + let middle = ids.len() / 2; + let mut placed: Vec<(usize, NodeId)> = ids.into_iter().enumerate().collect(); + placed.sort_by_key(|(k, _)| k.abs_diff(middle)); + placed.into_iter().map(|(_, id)| id).collect() + }, + ]; + for order in orders { + let mut s = session(2_000, square); + s.execute("guide.add", &json!({"pos": 5.0})).unwrap(); + let doc = &s.doc().unwrap().doc; + let all: Vec = layer(&s, 0).into_iter().filter(|id| !doc.node(*id).unwrap().is_ruler_guide()).collect(); + assert_eq!(all.len(), 2_000); + let (kept, art) = (all[0], all[1..].to_vec()); + s.execute("select.set", &json!({"ids": [kept]})).unwrap(); + let ids = order(art); + let (mut s, steps) = soon(s, "edit.clear", move |s| { + let mut steps = vec![s.doc().unwrap().doc.clone()]; + for id in &ids { + s.execute("edit.clear", &json!({"ids": [id.0]})).unwrap(); + steps.push(s.doc().unwrap().doc.clone()); + } + steps + }); + assert_eq!(layer(&s, 0).len(), 2, "the kept object and the guide"); + assert!(selected(&s, &[kept])); + for before in steps.iter().rev().skip(1).take(3) { + undo_gives_back(&mut s, before); + } + } +} + #[test] fn delete_selection_of_100000_rows_takes_few_tree_walks() { let s = session(100_000, square);