Skip to main content

cranpose_core/
memory_applier.rs

1use std::{any::TypeId, cmp::Reverse, collections::BinaryHeap};
2
3use smallvec::SmallVec;
4
5use crate::{
6    Applier, Node, NodeError, NodeId, NodeMarks, RecycleOrigin, RecyclePool, RecycledNode,
7    RuntimeHandle, bubble_passes,
8    collections::map::{HashMap, HashSet},
9    layout_dirt_roots,
10    node_marks::MarkPlace,
11    stable_index,
12};
13
14mod applier_impl;
15
16/// The stock [`Applier`]: it keeps nodes in memory under ids that stay stable for the life of the
17/// node.
18#[derive(Default)]
19pub struct MemoryApplier {
20    /// Behind one allocation, so lending the applier to a layout pass moves a
21    /// pointer.
22    pub(crate) state: Box<MemoryApplierState>,
23}
24
25#[derive(Default)]
26pub(crate) struct MemoryApplierState {
27    pub(crate) nodes: Vec<Option<Box<dyn Node>>>,
28    pub(crate) physical_stable_ids: Vec<u32>,
29    pub(crate) physical_warm_recycled_origins: Vec<RecycleOrigin>,
30    pub(crate) stable_index: stable_index::StableIndex,
31    pub(crate) free_ids: BinaryHeap<Reverse<usize>>,
32    pub(crate) high_ids: HashMap<NodeId, HighIdSlot>,
33    pub(crate) next_stable_id: NodeId,
34    pub(crate) layout_runtime: Option<RuntimeHandle>,
35    pub(crate) recycle_pools: HashMap<TypeId, RecyclePool>,
36    pub(crate) structural_change_parents: Vec<NodeId>,
37    pub(crate) bubble_passes: bubble_passes::BubblePasses,
38    pub(crate) layout_dirt_roots: layout_dirt_roots::LayoutDirtRoots,
39}
40
41// A node stored under an id too high for the dense table: the node while it
42// lives, whether it came from a warm shell, and the generation its id has
43// reached, which stays after the node goes.
44#[derive(Default)]
45pub(crate) struct HighIdSlot {
46    node: Option<Box<dyn Node>>,
47    origin: RecycleOrigin,
48    generation: u32,
49}
50
51/// Reusable ancestry storage for [`MemoryApplier::scene_nodes_attached_to_into`].
52///
53/// Attachment results are kept only for one batch, so callers can reuse this
54/// value without keeping stale attachment results after graph mutations.
55#[derive(Default)]
56pub struct SceneNodeAttachmentScratch {
57    attached: NodeMarks,
58    path: Vec<MarkPlace>,
59}
60
61const ATTACHED: u8 = 1;
62const DETACHED: u8 = 2;
63
64struct RemovalFrame {
65    node_id: NodeId,
66    children: SmallVec<[NodeId; 8]>,
67    next_child: usize,
68}
69
70/// Sizes of a [`MemoryApplier`]'s tables, for leak and memory checks. A `_len` field counts entries
71/// and a `_cap` field the capacity reserved.
72#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
73pub struct MemoryApplierDebugStats {
74    /// The id that the next created node gets.
75    pub next_stable_id: NodeId,
76    /// Live nodes.
77    pub nodes_len: usize,
78    /// Slots in the dense node table, both live and free.
79    pub nodes_cap: usize,
80    /// Entries in the table that gives each slot its stable id.
81    pub physical_stable_ids_len: usize,
82    /// Capacity reserved for the stable ids of table slots.
83    pub physical_stable_ids_cap: usize,
84    /// Live entries in the index from stable ids to table slots.
85    pub stable_to_physical_len: usize,
86    /// Capacity reserved for the index from stable ids to table slots.
87    pub stable_to_physical_cap: usize,
88    /// Stable ids that carry a generation counter.
89    pub stable_generations_len: usize,
90    /// Capacity reserved for the generation counters of stable ids.
91    pub stable_generations_cap: usize,
92    /// Dense table slots free for reuse.
93    pub free_ids_len: usize,
94    /// Capacity reserved for the free slot ids.
95    pub free_ids_cap: usize,
96    /// Nodes stored under ids too high for the dense table.
97    pub high_id_nodes_len: usize,
98    /// Capacity reserved for the high-id nodes.
99    pub high_id_nodes_cap: usize,
100    /// Generation counters kept for high-id nodes.
101    pub high_id_generations_len: usize,
102    /// Capacity reserved for the generations of high-id nodes.
103    pub high_id_generations_cap: usize,
104    /// Node types that have recycled nodes pooled.
105    pub recycled_type_count: usize,
106    /// Capacity reserved for the pools of recycled nodes.
107    pub recycled_type_cap: usize,
108    /// Pooled recycled nodes of all types.
109    pub recycled_node_count: usize,
110    /// Capacity reserved for the pooled recycled nodes.
111    pub recycled_node_capacity: usize,
112    /// Nodes recycled through the warm path, both live and pooled.
113    pub warm_recycled_node_id_count: usize,
114    /// Capacity reserved for the warm recycled nodes.
115    pub warm_recycled_node_id_capacity: usize,
116}
117
118impl MemoryApplier {
119    const EAGER_COMPACT_NODE_LEN: usize = 1_024;
120    pub(crate) const HIGH_ID_THRESHOLD: NodeId = NodeId(1_000_000_000);
121    const INVALID_STABLE_ID: u32 = u32::MAX;
122    const INITIAL_DENSE_NODE_CAP: usize = 32;
123    const LARGE_DENSE_NODE_GROWTH_THRESHOLD: usize = 32 * 1024;
124    const LARGE_DENSE_NODE_GROWTH_DIVISOR: usize = 4;
125
126    fn pack_stable_id(stable_id: NodeId) -> u32 {
127        u32::try_from(stable_id.0).expect("stable id overflow")
128    }
129
130    fn unpack_stable_id(stable_id: u32) -> NodeId {
131        NodeId(stable_id as usize)
132    }
133
134    fn next_dense_node_target_len(old_len: usize) -> usize {
135        if old_len < Self::INITIAL_DENSE_NODE_CAP {
136            return Self::INITIAL_DENSE_NODE_CAP;
137        }
138        if old_len < Self::LARGE_DENSE_NODE_GROWTH_THRESHOLD {
139            return old_len.saturating_mul(2);
140        }
141
142        let incremental_growth =
143            (old_len / Self::LARGE_DENSE_NODE_GROWTH_DIVISOR).max(Self::INITIAL_DENSE_NODE_CAP);
144        old_len.saturating_add(incremental_growth)
145    }
146
147    fn ensure_dense_node_storage_capacity(&mut self) {
148        let len = self
149            .state
150            .nodes
151            .len()
152            .max(self.state.physical_stable_ids.len())
153            .max(self.state.physical_warm_recycled_origins.len());
154        if len < self.state.nodes.capacity()
155            && len < self.state.physical_stable_ids.capacity()
156            && len < self.state.physical_warm_recycled_origins.capacity()
157        {
158            return;
159        }
160
161        let target = Self::next_dense_node_target_len(len);
162        if self.state.nodes.capacity() < target {
163            self.state
164                .nodes
165                .reserve_exact(target.saturating_sub(self.state.nodes.len()));
166        }
167        if self.state.physical_stable_ids.capacity() < target {
168            self.state
169                .physical_stable_ids
170                .reserve_exact(target.saturating_sub(self.state.physical_stable_ids.len()));
171        }
172        if self.state.physical_warm_recycled_origins.capacity() < target {
173            self.state.physical_warm_recycled_origins.reserve_exact(
174                target.saturating_sub(self.state.physical_warm_recycled_origins.len()),
175            );
176        }
177    }
178
179    /// Creates an applier with no nodes.
180    pub fn new() -> Self {
181        Self::default()
182    }
183
184    /// Resolves a scene-scope candidate the way structural records are
185    /// resolved: to its nearest non-virtual ancestor, and only while still
186    /// attached to `root`. A node detached after recording must not reach the
187    /// scoped scene update — an id the graph cannot resolve forces it to give
188    /// up and rebuild the whole scene.
189    pub fn scene_node_attached_to(&mut self, node_id: NodeId, root: NodeId) -> Option<NodeId> {
190        let (resolved, _) = self.first_non_virtual_ancestor(node_id)?;
191        self.is_attached_to(resolved, root).then_some(resolved)
192    }
193
194    /// [`Self::scene_node_attached_to`] for each of `nodes`, in order, with
195    /// every ancestor looked up at most once: a batch costs the distinct
196    /// ancestors of its nodes, not each node's depth.
197    pub fn scene_nodes_attached_to(
198        &mut self,
199        nodes: impl IntoIterator<Item = NodeId>,
200        root: NodeId,
201    ) -> Vec<Option<NodeId>> {
202        let mut result = Vec::new();
203        self.scene_nodes_attached_to_into(
204            nodes,
205            root,
206            &mut result,
207            &mut SceneNodeAttachmentScratch::default(),
208        );
209        result
210    }
211
212    /// Fills `output` with [`Self::scene_nodes_attached_to`] results, reusing
213    /// its storage and the ancestry cache in `scratch` across batches.
214    ///
215    /// Each distinct ancestor is inspected at most once per call. The cache
216    /// is cleared for each call, so graph mutations are observed by the next
217    /// batch.
218    ///
219    /// ```
220    /// use cranpose_core::{MemoryApplier, NodeId, SceneNodeAttachmentScratch};
221    ///
222    /// let mut applier = MemoryApplier::new();
223    /// let mut scratch = SceneNodeAttachmentScratch::default();
224    /// let mut attached: Vec<Option<NodeId>> = Vec::new();
225    /// let root = NodeId::default();
226    /// applier.scene_nodes_attached_to_into([], root, &mut attached, &mut scratch);
227    /// assert!(attached.is_empty());
228    /// ```
229    pub fn scene_nodes_attached_to_into(
230        &mut self,
231        nodes: impl IntoIterator<Item = NodeId>,
232        root: NodeId,
233        output: &mut Vec<Option<NodeId>>,
234        scratch: &mut SceneNodeAttachmentScratch,
235    ) {
236        let nodes = nodes.into_iter();
237        output.clear();
238        let (lower_bound, upper_bound) = nodes.size_hint();
239        if lower_bound == 0 && upper_bound == Some(0) {
240            scratch.path.clear();
241            return;
242        }
243        scratch.attached.reset(self);
244        scratch.attached.set(self, root, ATTACHED);
245        output.reserve(lower_bound);
246        scratch.path.clear();
247        for node_id in nodes {
248            let Some((resolved, mut current)) = self.first_non_virtual_ancestor(node_id) else {
249                output.push(None);
250                continue;
251            };
252            scratch.path.clear();
253            let answer = loop {
254                match scratch.attached.mark_at(current) {
255                    ATTACHED => break true,
256                    DETACHED => break false,
257                    _ => {}
258                }
259                scratch.path.push(current);
260                match self.parent_at(current) {
261                    Some(parent) if scratch.path.len() < 100_000 => {
262                        current = MarkPlace::of(self, parent);
263                    }
264                    _ => break false,
265                }
266            };
267            let mark = if answer { ATTACHED } else { DETACHED };
268            for visited in scratch.path.drain(..) {
269                *scratch.attached.entry_at(visited) = mark;
270            }
271            output.push(answer.then_some(resolved));
272        }
273    }
274
275    /// Drains the parents recorded via [`Applier::record_structural_change`],
276    /// keeping only nodes still attached to `root` (a parent that was itself
277    /// removed is covered by its own surviving ancestor's record). A virtual
278    /// parent — a subcompose slot wrapper the render graph never contains —
279    /// is reported as its nearest non-virtual ancestor: that is the node
280    /// whose graph child set the change altered, and an id the graph cannot
281    /// resolve would force the scoped scene update to give up and rebuild.
282    pub fn take_structural_change_parents_attached_to(&mut self, root: NodeId) -> Vec<NodeId> {
283        let mut candidates = Vec::new();
284        self.take_structural_change_parents_into(&mut candidates);
285        let mut seen = HashSet::<NodeId>::default();
286        candidates.retain_mut(|parent_id| {
287            let Some((resolved, _)) = self.first_non_virtual_ancestor(*parent_id) else {
288                return false;
289            };
290            *parent_id = resolved;
291            self.is_attached_to(resolved, root) && seen.insert(resolved)
292        });
293        candidates
294    }
295
296    /// Takes the recorded structural-change candidates into reusable storage.
297    /// Candidates are not resolved or attachment-filtered; callers that route
298    /// them into scenes should use [`Self::scene_nodes_attached_to_into`].
299    ///
300    /// ```
301    /// use cranpose_core::MemoryApplier;
302    ///
303    /// let mut applier = MemoryApplier::new();
304    /// let mut nodes = Vec::new();
305    /// applier.take_structural_change_parents_into(&mut nodes);
306    /// assert!(nodes.is_empty());
307    /// ```
308    pub fn take_structural_change_parents_into(&mut self, output: &mut Vec<NodeId>) {
309        output.clear();
310        std::mem::swap(&mut self.state.structural_change_parents, output);
311    }
312
313    // The first of `node_id` and its ancestors that is not virtual, and
314    // where it is stored; an id with no node is its own answer.
315    fn first_non_virtual_ancestor(&self, node_id: NodeId) -> Option<(NodeId, MarkPlace)> {
316        let mut current = node_id;
317        for _ in 0..100_000 {
318            let (place, is_virtual) = match self.state.stable_index.slot_and_virtual(current) {
319                Some((slot, is_virtual)) => (MarkPlace::Dense(slot), is_virtual),
320                None => (
321                    MarkPlace::Elsewhere(current),
322                    self.high_id_node(current).is_ok_and(Node::is_virtual),
323                ),
324            };
325            if !is_virtual {
326                return Some((current, place));
327            }
328            current = self.parent_at(place)?;
329        }
330        None
331    }
332
333    fn is_attached_to(&mut self, node_id: NodeId, root: NodeId) -> bool {
334        let mut current = node_id;
335        for _ in 0..100_000 {
336            if current == root {
337                return true;
338            }
339            match self.get_mut(current) {
340                Ok(node) => match node.parent() {
341                    Some(parent) => current = parent,
342                    None => return false,
343                },
344                Err(_) => return false,
345            }
346        }
347        false
348    }
349
350    /// Runs `f` on the node `id` as an `N`. Returns an error if the node does not exist or is not
351    /// an `N`.
352    pub fn with_node<N: Node + 'static, R>(
353        &mut self,
354        id: NodeId,
355        f: impl FnOnce(&mut N) -> R,
356    ) -> Result<R, NodeError> {
357        let typed = self
358            .get_mut(id)?
359            .as_any_mut()
360            .downcast_mut::<N>()
361            .ok_or_else(|| NodeError::TypeMismatch {
362                id,
363                expected: std::any::type_name::<N>(),
364            })?;
365        Ok(f(typed))
366    }
367
368    /// Returns the number of live nodes.
369    pub fn len(&self) -> usize {
370        self.state.nodes.iter().filter(|n| n.is_some()).count()
371    }
372
373    /// Returns the number of slots in the dense node table, both live and free.
374    pub fn capacity(&self) -> usize {
375        self.state.nodes.len()
376    }
377
378    /// Returns the number of free slots in the dense node table.
379    pub fn tombstone_count(&self) -> usize {
380        self.state.nodes.iter().filter(|n| n.is_none()).count()
381    }
382
383    /// Returns the number of freed table slots that new nodes can reuse.
384    pub fn freelist_len(&self) -> usize {
385        self.state.free_ids.len()
386    }
387
388    /// Ends a frame for the recycle pools: each keeps as many removed nodes as its recent frames
389    /// asked for, the most of one frame over the last two spans of
390    /// [`IDLE_PASSES`](crate::collections::pass_aged::IDLE_PASSES) frames, and lets the oldest of
391    /// the rest go. A pool whose frames ask for no node of its type keeps none. A shell calls it
392    /// at the end of each frame.
393    #[expect(
394        clippy::iter_over_hash_type,
395        reason = "each pool ends its frame on its own, so the order of the pools does not matter"
396    )]
397    pub fn end_recycle_frame(&mut self) {
398        for pool in self.state.recycle_pools.values_mut() {
399            pool.end_frame();
400        }
401    }
402
403    /// Lets every pooled recycled node go, and the room the pools took: the tree rests, and its
404    /// next nodes come fresh. A shell calls it when it trims at rest.
405    #[expect(
406        clippy::iter_over_hash_type,
407        reason = "each pool lets its nodes go on its own, so the order of the pools does not matter"
408    )]
409    pub fn trim_recycled_nodes(&mut self) {
410        for pool in self.state.recycle_pools.values_mut() {
411            pool.rest();
412        }
413        self.prune_stable_generations();
414    }
415
416    /// Returns the number of pooled recycled nodes of all types.
417    pub fn debug_recycled_node_count(&self) -> usize {
418        self.total_recycled_node_count()
419    }
420
421    /// Returns the number of pooled recycled nodes of type `N`.
422    pub fn debug_recycled_node_count_for<N: Node + 'static>(&self) -> usize {
423        let key = TypeId::of::<N>();
424        self.state
425            .recycle_pools
426            .get(&key)
427            .map_or(0, RecyclePool::len)
428    }
429
430    /// Returns the sizes of the applier's tables, for leak and memory checks.
431    pub fn debug_stats(&self) -> MemoryApplierDebugStats {
432        MemoryApplierDebugStats {
433            next_stable_id: self.state.next_stable_id,
434            nodes_len: self.len(),
435            nodes_cap: self.state.nodes.len(),
436            physical_stable_ids_len: self.state.physical_stable_ids.len(),
437            physical_stable_ids_cap: self.state.physical_stable_ids.capacity(),
438            stable_to_physical_len: self.state.stable_index.live(),
439            stable_to_physical_cap: self.state.stable_index.capacity(),
440            stable_generations_len: self.state.stable_index.occupied(),
441            stable_generations_cap: self.state.stable_index.capacity(),
442            free_ids_len: self.state.free_ids.len(),
443            free_ids_cap: self.state.free_ids.capacity(),
444            high_id_nodes_len: self.high_id_nodes().count(),
445            high_id_nodes_cap: self.state.high_ids.capacity(),
446            high_id_generations_len: self.state.high_ids.len(),
447            high_id_generations_cap: self.state.high_ids.capacity(),
448            recycled_type_count: self
449                .state
450                .recycle_pools
451                .values()
452                .filter(|pool| pool.len() > 0)
453                .count(),
454            recycled_type_cap: self.state.recycle_pools.capacity(),
455            recycled_node_count: self.total_recycled_node_count(),
456            recycled_node_capacity: self.total_recycled_node_capacity(),
457            warm_recycled_node_id_count: self.total_warm_recycled_node_id_count(),
458            warm_recycled_node_id_capacity: self.total_warm_recycled_node_id_capacity(),
459        }
460    }
461
462    /// Returns `true` if the applier holds no live nodes.
463    pub fn is_empty(&self) -> bool {
464        self.len() == 0
465    }
466
467    /// Calls `visit` with every live node, dense and high-id alike.
468    pub fn for_each_node_mut(&mut self, mut visit: impl FnMut(&mut dyn Node)) {
469        for node in self.state.nodes.iter_mut().flatten() {
470            visit(node.as_mut());
471        }
472        for node in self
473            .state
474            .high_ids
475            .values_mut()
476            .filter_map(|slot| slot.node.as_mut())
477        {
478            visit(node.as_mut());
479        }
480    }
481
482    /// Returns the heap bytes that the live nodes take, including what they own.
483    pub fn debug_live_node_heap_bytes(&self) -> usize {
484        let dense_nodes = self
485            .state
486            .nodes
487            .iter()
488            .flatten()
489            .map(|node| size_of_val(&**node) + node.debug_heap_bytes())
490            .sum::<usize>();
491        let high_id_nodes = self
492            .high_id_nodes()
493            .map(|node| size_of_val(node) + node.debug_heap_bytes())
494            .sum::<usize>();
495        dense_nodes + high_id_nodes
496    }
497
498    /// Returns the heap bytes that the pooled recycled nodes take, including what they own.
499    pub fn debug_recycled_node_heap_bytes(&self) -> usize {
500        self.state
501            .recycle_pools
502            .values()
503            .flat_map(RecyclePool::nodes)
504            .map(|node| size_of_val(&*node.node) + node.node.debug_heap_bytes())
505            .sum::<usize>()
506    }
507
508    /// Gives the applier the runtime of its composition, so code that runs during layout with only
509    /// the applier in hand can reach the runtime.
510    pub fn set_runtime_handle(&mut self, handle: RuntimeHandle) {
511        self.state.layout_runtime = Some(handle);
512    }
513
514    /// Removes the runtime handle.
515    pub fn clear_runtime_handle(&mut self) {
516        self.state.layout_runtime = None;
517    }
518
519    /// Returns the runtime handle set with `set_runtime_handle`, if any.
520    pub fn runtime_handle(&self) -> Option<RuntimeHandle> {
521        self.state.layout_runtime.clone()
522    }
523
524    fn total_recycled_node_count(&self) -> usize {
525        self.state
526            .recycle_pools
527            .values()
528            .map(RecyclePool::len)
529            .sum()
530    }
531
532    fn total_recycled_node_capacity(&self) -> usize {
533        self.state
534            .recycle_pools
535            .values()
536            .map(RecyclePool::capacity)
537            .sum()
538    }
539
540    fn total_warm_recycled_node_id_count(&self) -> usize {
541        self.live_warm_recycled_origin_count()
542            + self
543                .state
544                .recycle_pools
545                .values()
546                .map(|pool| pool.warm.len() + pool.returning.len())
547                .sum::<usize>()
548    }
549
550    fn total_warm_recycled_node_id_capacity(&self) -> usize {
551        self.live_warm_recycled_origin_capacity()
552            + self
553                .state
554                .recycle_pools
555                .values()
556                .map(|pool| pool.warm.capacity() + pool.returning.capacity())
557                .sum::<usize>()
558    }
559
560    // One lookup of the pool: a limit makes the pool, and no limit clears
561    // the limit of a pool that exists.
562    fn remember_recycle_pool_limit(&mut self, key: TypeId, recycle_pool_limit: Option<usize>) {
563        let pools = &mut self.state.recycle_pools;
564        if recycle_pool_limit.is_some() {
565            pools.entry(key).or_default().limit = recycle_pool_limit;
566        } else if let Some(pool) = pools.get_mut(&key) {
567            pool.limit = None;
568        }
569    }
570
571    fn warm_recycled_pool_len(&self, key: TypeId) -> usize {
572        self.state
573            .recycle_pools
574            .get(&key)
575            .map_or(0, |pool| pool.warm.len())
576    }
577
578    fn live_warm_recycled_origin_count(&self) -> usize {
579        self.state
580            .physical_warm_recycled_origins
581            .iter()
582            .zip(self.state.nodes.iter())
583            .filter(|(origin, node)| **origin == RecycleOrigin::Warm && node.is_some())
584            .count()
585            + self
586                .state
587                .high_ids
588                .values()
589                .filter(|slot| slot.origin == RecycleOrigin::Warm && slot.node.is_some())
590                .count()
591    }
592
593    fn high_id_nodes(&self) -> impl Iterator<Item = &dyn Node> {
594        self.state
595            .high_ids
596            .values()
597            .filter_map(|slot| slot.node.as_deref())
598    }
599
600    fn live_warm_recycled_origin_capacity(&self) -> usize {
601        self.state.physical_warm_recycled_origins.capacity() + self.state.high_ids.capacity()
602    }
603
604    fn push_recycled_node(
605        &mut self,
606        key: TypeId,
607        recycle_pool_limit: Option<usize>,
608        recycled: RecycledNode,
609    ) {
610        self.remember_recycle_pool_limit(key, recycle_pool_limit);
611        let pool = self.state.recycle_pools.entry(key).or_default();
612        pool.remember_prototype(recycled.node.as_ref());
613        pool.push(recycled);
614    }
615
616    // The shell is made only when the pool keeps it: a pool with no room,
617    // as with little memory left, costs a fresh node nothing.
618    fn seed_recycled_node_shell_impl(&mut self, key: TypeId, node: &dyn Node) {
619        let recycle_pool_limit = node.recycle_pool_limit();
620        if self.warm_recycled_pool_len(key) >= RecyclePool::made_ahead_limit(recycle_pool_limit) {
621            return;
622        }
623        let Some(shell) = node.rehouse_for_recycle() else {
624            return;
625        };
626
627        self.remember_recycle_pool_limit(key, recycle_pool_limit);
628        let stable_id = self.state.next_stable_id;
629        self.state.next_stable_id = self.state.next_stable_id.next();
630        let pool = self.state.recycle_pools.entry(key).or_default();
631        pool.remember_prototype(shell.as_ref());
632        pool.push_warm(RecycledNode::from_shell(
633            stable_id,
634            shell,
635            RecycleOrigin::Warm,
636        ));
637    }
638
639    fn prune_stable_generations(&mut self) {
640        let retained_len = self.state.stable_index.live() + self.total_recycled_node_count();
641        if retained_len == self.state.stable_index.occupied() {
642            return;
643        }
644
645        let recycled: HashSet<NodeId> = self
646            .state
647            .recycle_pools
648            .values()
649            .flat_map(RecyclePool::nodes)
650            .map(RecycledNode::stable_id)
651            .collect();
652        self.state
653            .stable_index
654            .retain_retired(|stable_id| recycled.contains(&stable_id));
655    }
656
657    /// Returns an indented text outline of the tree below `root` for debugging, or a `(no root)`
658    /// line when `root` is `None`.
659    pub fn dump_tree(&self, root: Option<NodeId>) -> String {
660        let mut output = String::new();
661        if let Some(root_id) = root {
662            self.dump_node(&mut output, root_id, 0);
663        } else {
664            output.push_str("(no root)\n");
665        }
666        output
667    }
668
669    fn dump_node(&self, output: &mut String, id: NodeId, depth: usize) {
670        let indent = "  ".repeat(depth);
671        let Ok(node) = self.get_ref(id) else {
672            if let Some(physical_id) = self.resolve_node_index(id) {
673                output.push_str(&format!(
674                    "{indent}[{id}] (missing physical node {physical_id})\n"
675                ));
676            } else {
677                output.push_str(&format!("{indent}[{id}] (missing)\n"));
678            }
679            return;
680        };
681        let type_name = std::any::type_name_of_val(node);
682        output.push_str(&format!("{indent}[{id}] {type_name}\n"));
683
684        let mut children = SmallVec::<[NodeId; 8]>::new();
685        node.collect_children_into(&mut children);
686        for child_id in children {
687            self.dump_node(output, child_id, depth + 1);
688        }
689    }
690
691    /// Moves into `out` the nodes the layout dirty bubbles started from
692    /// since the last call, for a layout pass that starts from them, and
693    /// forgets them. `false` when there were more than the applier keeps:
694    /// `out` is then empty and the pass walks down from the root.
695    pub fn take_layout_dirt_roots(&mut self, out: &mut Vec<NodeId>) -> bool {
696        self.state.layout_dirt_roots.take_into(out)
697    }
698
699    /// Whether a layout dirty bubble started since the last
700    /// [`Self::take_layout_dirt_roots`].
701    pub fn has_layout_dirt_roots(&self) -> bool {
702        self.state.layout_dirt_roots.any()
703    }
704
705    #[inline]
706    pub(crate) fn resolve_node_index(&self, id: NodeId) -> Option<usize> {
707        self.state.stable_index.slot(id)
708    }
709
710    fn contains_node_id(&self, id: NodeId) -> bool {
711        self.resolve_node_index(id).is_some() || self.high_id_node(id).is_ok()
712    }
713
714    fn insert_high_id_node(
715        &mut self,
716        stable_id: NodeId,
717        node: Box<dyn Node>,
718        origin: RecycleOrigin,
719    ) {
720        let slot = self.state.high_ids.entry(stable_id).or_default();
721        slot.node = Some(node);
722        slot.origin = origin;
723    }
724
725    fn insert_available_with_id(&mut self, stable_id: NodeId, node: Box<dyn Node>) {
726        if stable_id >= Self::HIGH_ID_THRESHOLD {
727            self.insert_high_id_node(stable_id, node, RecycleOrigin::Cold);
728            return;
729        }
730
731        let is_virtual = node.is_virtual();
732        let physical_id = if let Some(Reverse(free_physical_id)) = self.state.free_ids.pop() {
733            self.state.nodes[free_physical_id] = Some(node);
734            self.state.physical_stable_ids[free_physical_id] = Self::pack_stable_id(stable_id);
735            self.state.physical_warm_recycled_origins[free_physical_id] = RecycleOrigin::Cold;
736            free_physical_id
737        } else {
738            self.ensure_dense_node_storage_capacity();
739            let physical_id = self.state.nodes.len();
740            self.state.nodes.push(Some(node));
741            self.state
742                .physical_stable_ids
743                .push(Self::pack_stable_id(stable_id));
744            self.state
745                .physical_warm_recycled_origins
746                .push(RecycleOrigin::Cold);
747            physical_id
748        };
749
750        self.state.next_stable_id = self.state.next_stable_id.max(stable_id.next());
751        self.state.physical_stable_ids[physical_id] = Self::pack_stable_id(stable_id);
752        self.state.stable_index.set_slot(stable_id, physical_id);
753        if is_virtual {
754            self.state.stable_index.mark_virtual(stable_id);
755        }
756    }
757
758    /// Borrows a live node without requiring exclusive access to the tree.
759    /// Returns [`NodeError::Missing`] when `id` does not name a live node.
760    #[inline]
761    pub fn get_ref(&self, id: NodeId) -> Result<&dyn Node, NodeError> {
762        match self.resolve_node_index(id) {
763            Some(physical_id) => self
764                .state
765                .nodes
766                .get(physical_id)
767                .and_then(Option::as_deref)
768                .ok_or(NodeError::Missing { id }),
769            None => self.high_id_node(id),
770        }
771    }
772
773    // The parent of the node at `place`, `None` for a root or a node that
774    // is gone.
775    #[inline]
776    pub(crate) fn parent_at(&self, place: MarkPlace) -> Option<NodeId> {
777        match place {
778            MarkPlace::Dense(slot) => self.state.nodes.get(slot)?.as_deref()?.parent(),
779            MarkPlace::Elsewhere(id) => self.high_id_node(id).ok()?.parent(),
780        }
781    }
782
783    pub(crate) fn high_id_node(&self, id: NodeId) -> Result<&dyn Node, NodeError> {
784        self.state
785            .high_ids
786            .get(&id)
787            .and_then(|slot| slot.node.as_deref())
788            .ok_or(NodeError::Missing { id })
789    }
790
791    fn high_id_node_mut(&mut self, id: NodeId) -> Result<&mut dyn Node, NodeError> {
792        self.state
793            .high_ids
794            .get_mut(&id)
795            .and_then(|slot| slot.node.as_deref_mut())
796            .ok_or(NodeError::Missing { id })
797    }
798
799    fn node_parent(&self, id: NodeId) -> Result<Option<NodeId>, NodeError> {
800        Ok(self.get_ref(id)?.parent())
801    }
802
803    fn collect_owned_children(
804        &self,
805        node_id: NodeId,
806        out: &mut SmallVec<[NodeId; 8]>,
807    ) -> Result<(), NodeError> {
808        self.get_ref(node_id)?.collect_owned_children_into(out);
809        out.retain(|child_id| {
810            self.node_parent(*child_id)
811                .is_ok_and(|parent| parent == Some(node_id))
812        });
813        Ok(())
814    }
815
816    fn remove_node_storage(&mut self, node_id: NodeId) -> Result<(), NodeError> {
817        if let Some(slot) = self.state.high_ids.get_mut(&node_id)
818            && let Some(node) = slot.node.take()
819        {
820            let origin = std::mem::take(&mut slot.origin);
821            slot.generation = slot.generation.wrapping_add(1);
822            if let Some(key) = node.recycle_key() {
823                let recycle_pool_limit = node.recycle_pool_limit();
824                self.push_recycled_node(
825                    key,
826                    recycle_pool_limit,
827                    RecycledNode::new(node_id, node, origin),
828                );
829            }
830            return Ok(());
831        }
832
833        let physical_id = self
834            .resolve_node_index(node_id)
835            .ok_or(NodeError::Missing { id: node_id })?;
836        if let Some(node) = self.state.nodes[physical_id].take()
837            && let Some(key) = node.recycle_key()
838        {
839            let recycle_pool_limit = node.recycle_pool_limit();
840            let origin = self
841                .state
842                .physical_warm_recycled_origins
843                .get_mut(physical_id)
844                .map_or_default(std::mem::take);
845            self.push_recycled_node(
846                key,
847                recycle_pool_limit,
848                RecycledNode::new(node_id, node, origin),
849            );
850        }
851        self.state.physical_stable_ids[physical_id] = Self::INVALID_STABLE_ID;
852        self.state.stable_index.release(node_id);
853        self.state.free_ids.push(Reverse(physical_id));
854        Ok(())
855    }
856
857    fn remove_subtree_postorder(&mut self, id: NodeId) -> Result<usize, NodeError> {
858        self.get_ref(id)?;
859
860        let mut root_children = SmallVec::<[NodeId; 8]>::new();
861        self.collect_owned_children(id, &mut root_children)?;
862        if root_children.is_empty() {
863            self.remove_node_storage(id)?;
864            return Ok(1);
865        }
866
867        let mut stack = SmallVec::<[RemovalFrame; 4]>::new();
868        stack.push(RemovalFrame {
869            node_id: id,
870            children: root_children,
871            next_child: 0,
872        });
873        let mut max_depth = stack.len();
874
875        while let Some(frame) = stack.last_mut() {
876            if frame.next_child < frame.children.len() {
877                let child_id = frame.children[frame.next_child];
878                frame.next_child += 1;
879
880                if let Ok(child) = self.get_mut(child_id) {
881                    child.on_removed_from_parent();
882                    child.unmount();
883                }
884
885                let mut child_children = SmallVec::<[NodeId; 8]>::new();
886                self.collect_owned_children(child_id, &mut child_children)?;
887                stack.push(RemovalFrame {
888                    node_id: child_id,
889                    children: child_children,
890                    next_child: 0,
891                });
892                max_depth = max_depth.max(stack.len());
893                continue;
894            }
895
896            let node_id = frame.node_id;
897            stack.pop();
898            self.remove_node_storage(node_id)?;
899        }
900
901        Ok(max_depth)
902    }
903
904    #[cfg(test)]
905    pub(crate) fn debug_remove_max_traversal_depth(
906        &mut self,
907        id: NodeId,
908    ) -> Result<usize, NodeError> {
909        self.remove_subtree_postorder(id)
910    }
911}