Skip to main content

cranpose_core/
subcompose.rs

1//! State tracking for measure-time subcomposition.
2//!
3//! The [`SubcomposeState`] keeps book of which slots are active, which nodes can
4//! be reused, and which precompositions need to be disposed. Reuse follows a
5//! two-phase lookup: first [`SlotId`]s that match exactly are preferred. If no
6//! exact match exists, the [`SlotReusePolicy`] is consulted to determine whether
7//! a node produced for another slot is compatible with the requested slot.
8
9use std::{any::Any, collections::VecDeque, fmt, rc::Rc};
10
11use smallvec::SmallVec;
12
13use crate::{
14    CallbackHolder, NodeId, RecomposeScope, SlotTable, SlotsHost,
15    collections::map::{HashMap, HashSet},
16};
17
18pub type DebugSlotGroup = (usize, crate::Key, Option<usize>, usize);
19
20/// Identifier for a subcomposed slot.
21///
22/// This mirrors the `slotId` concept in Jetpack Compose where callers provide
23/// stable identifiers for reusable children during measure-time composition.
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
25pub struct SlotId(pub u64);
26
27impl SlotId {
28    #[inline]
29    pub fn new(raw: u64) -> Self {
30        Self(raw)
31    }
32
33    #[inline]
34    pub fn raw(self) -> u64 {
35        self.0
36    }
37}
38
39/// Policy that decides which previously composed slots should be retained for
40/// potential reuse during the next subcompose pass.
41///
42/// Note: This trait does NOT require Send + Sync because the compose runtime
43/// is single-threaded (uses Rc/RefCell throughout).
44pub trait SlotReusePolicy: 'static {
45    /// Returns the subset of slots that should be retained for reuse after the
46    /// current measurement pass. Slots that are not part of the returned set
47    /// will be disposed.
48    fn get_slots_to_retain(&self, active: &[SlotId]) -> HashSet<SlotId>;
49
50    /// Determines whether a node that previously rendered the slot `existing`
51    /// can be reused when the caller requests `requested`.
52    ///
53    /// Implementations should document what constitutes compatibility (for
54    /// example, identical slot identifiers, matching layout classes, or node
55    /// types). Returning `true` allows [`SubcomposeState`] to move the node
56    /// across slots instead of disposing it.
57    fn are_compatible(&self, existing: SlotId, requested: SlotId) -> bool;
58
59    /// Registers the content type for a slot.
60    ///
61    /// Policies that support content-type-based reuse (like [`ContentTypeReusePolicy`])
62    /// should override this to record the type. The default implementation is a no-op.
63    ///
64    /// Call this before subcomposing an item to enable content-type-aware slot reuse.
65    fn register_content_type(&self, _slot_id: SlotId, _content_type: u64) {}
66
67    /// Removes the content type for a slot (e.g., when transitioning to None).
68    ///
69    /// Policies that track content types should override this to clean up.
70    /// The default implementation is a no-op.
71    fn remove_content_type(&self, _slot_id: SlotId) {}
72}
73
74/// Default reuse policy that mirrors Jetpack Compose behaviour: dispose
75/// everything from the tail so that the next measurement can decide which
76/// content to keep alive. Compatibility defaults to exact slot matches.
77#[derive(Debug, Default)]
78pub struct DefaultSlotReusePolicy;
79
80impl SlotReusePolicy for DefaultSlotReusePolicy {
81    fn get_slots_to_retain(&self, active: &[SlotId]) -> HashSet<SlotId> {
82        let _ = active;
83        HashSet::default()
84    }
85
86    fn are_compatible(&self, existing: SlotId, requested: SlotId) -> bool {
87        existing == requested
88    }
89}
90
91/// Reuse policy that allows cross-slot reuse when content types match.
92///
93/// This policy enables efficient recycling of layout nodes across different
94/// slot IDs when they share the same content type (e.g., list items with
95/// similar structure but different data).
96///
97/// # Example
98///
99/// ```rust,ignore
100/// use cranpose_core::{ContentTypeReusePolicy, SubcomposeState, SlotId};
101///
102/// let mut policy = ContentTypeReusePolicy::new();
103///
104/// // Register content types for slots
105/// policy.set_content_type(SlotId::new(0), 1); // Header type
106/// policy.set_content_type(SlotId::new(1), 2); // Item type
107/// policy.set_content_type(SlotId::new(2), 2); // Item type (same as slot 1)
108///
109/// // Slot 1 can reuse slot 2's node since they share content type 2
110/// assert!(policy.are_compatible(SlotId::new(2), SlotId::new(1)));
111/// ```
112pub struct ContentTypeReusePolicy {
113    slot_types: std::cell::RefCell<HashMap<SlotId, u64>>,
114}
115
116impl std::fmt::Debug for ContentTypeReusePolicy {
117    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118        let types = self.slot_types.borrow();
119        f.debug_struct("ContentTypeReusePolicy")
120            .field("slot_types", &*types)
121            .finish()
122    }
123}
124
125impl Default for ContentTypeReusePolicy {
126    fn default() -> Self {
127        Self::new()
128    }
129}
130
131impl ContentTypeReusePolicy {
132    /// Creates a new content-type-aware reuse policy.
133    pub fn new() -> Self {
134        Self {
135            slot_types: std::cell::RefCell::new(HashMap::default()),
136        }
137    }
138
139    /// Registers the content type for a slot.
140    ///
141    /// Call this when subcomposing an item with a known content type.
142    pub fn set_content_type(&self, slot: SlotId, content_type: u64) {
143        self.slot_types.borrow_mut().insert(slot, content_type);
144    }
145
146    /// Removes the content type for a slot (e.g., when disposed).
147    pub fn remove_content_type(&self, slot: SlotId) {
148        self.slot_types.borrow_mut().remove(&slot);
149    }
150
151    /// Clears all registered content types.
152    pub fn clear(&self) {
153        self.slot_types.borrow_mut().clear();
154    }
155
156    /// Returns the content type for a slot, if registered.
157    pub fn get_content_type(&self, slot: SlotId) -> Option<u64> {
158        self.slot_types.borrow().get(&slot).copied()
159    }
160}
161
162impl SlotReusePolicy for ContentTypeReusePolicy {
163    fn get_slots_to_retain(&self, active: &[SlotId]) -> HashSet<SlotId> {
164        let _ = active;
165        HashSet::default()
166    }
167
168    fn are_compatible(&self, existing: SlotId, requested: SlotId) -> bool {
169        if existing == requested {
170            return true;
171        }
172
173        let types = self.slot_types.borrow();
174        match (types.get(&existing), types.get(&requested)) {
175            (Some(existing_type), Some(requested_type)) => existing_type == requested_type,
176            (None, None) => true,
177            _ => false,
178        }
179    }
180
181    fn register_content_type(&self, slot_id: SlotId, content_type: u64) {
182        self.set_content_type(slot_id, content_type);
183    }
184
185    fn remove_content_type(&self, slot_id: SlotId) {
186        ContentTypeReusePolicy::remove_content_type(self, slot_id);
187    }
188}
189
190#[doc(hidden)]
191pub struct ExactSlotActivation<'a> {
192    pub nodes: &'a [NodeId],
193    pub was_recycled: bool,
194}
195
196/// Evicted roots and the slot state that stays alive until their nodes are disposed.
197/// Pass this batch to [`crate::Composer::dispose_subcomposed_nodes`].
198#[derive(Default)]
199pub struct SubcomposeDisposal {
200    pub(crate) nodes: Vec<NodeId>,
201    pub(crate) slot_hosts: Vec<Rc<SlotsHost>>,
202}
203
204impl SubcomposeDisposal {
205    /// Returns the roots awaiting disposal.
206    ///
207    /// ```
208    /// use cranpose_core::SubcomposeState;
209    /// let mut state = SubcomposeState::default();
210    /// let disposed = state.finish_pass();
211    /// assert!(disposed.nodes().is_empty());
212    /// ```
213    pub fn nodes(&self) -> &[NodeId] {
214        &self.nodes
215    }
216
217    fn append(&mut self, mut other: Self) {
218        self.nodes.append(&mut other.nodes);
219        self.slot_hosts.append(&mut other.slot_hosts);
220    }
221}
222
223#[derive(Default, Clone)]
224
225struct NodeSlotMapping {
226    slot_to_nodes: HashMap<SlotId, Vec<NodeId>>,
227    node_to_slot: HashMap<NodeId, SlotId>,
228    slot_to_scopes: HashMap<SlotId, Vec<RecomposeScope>>,
229}
230
231impl fmt::Debug for NodeSlotMapping {
232    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
233        f.debug_struct("NodeSlotMapping")
234            .field("slot_to_nodes", &self.slot_to_nodes)
235            .field("node_to_slot", &self.node_to_slot)
236            .finish()
237    }
238}
239
240impl NodeSlotMapping {
241    fn set_nodes(&mut self, slot: SlotId, nodes: &[NodeId]) {
242        self.slot_to_nodes.insert(slot, nodes.to_vec());
243        for node in nodes {
244            self.node_to_slot.insert(*node, slot);
245        }
246    }
247
248    fn set_scopes(&mut self, slot: SlotId, scopes: &[RecomposeScope]) {
249        self.slot_to_scopes.insert(slot, scopes.to_vec());
250    }
251
252    fn add_node(&mut self, slot: SlotId, node: NodeId) {
253        self.slot_to_nodes.entry(slot).or_default().push(node);
254        self.node_to_slot.insert(node, slot);
255    }
256
257    fn remove_by_node(&mut self, node: &NodeId) -> Option<SlotId> {
258        if let Some(slot) = self.node_to_slot.remove(node) {
259            if let Some(nodes) = self.slot_to_nodes.get_mut(&slot) {
260                if let Some(index) = nodes.iter().position(|candidate| candidate == node) {
261                    nodes.remove(index);
262                }
263                if nodes.is_empty() {
264                    self.slot_to_nodes.remove(&slot);
265                    self.slot_to_scopes.remove(&slot);
266                }
267            }
268            Some(slot)
269        } else {
270            None
271        }
272    }
273
274    fn get_nodes(&self, slot: &SlotId) -> Option<&[NodeId]> {
275        self.slot_to_nodes.get(slot).map(Vec::as_slice)
276    }
277
278    fn get_scopes(&self, slot: &SlotId) -> Option<&[RecomposeScope]> {
279        self.slot_to_scopes.get(slot).map(Vec::as_slice)
280    }
281
282    fn slot_has_invalid_scopes(&self, slot: SlotId) -> bool {
283        self.slot_to_scopes
284            .get(&slot)
285            .is_some_and(|scopes| scopes.iter().any(RecomposeScope::is_invalid))
286    }
287
288    fn slot_has_inactive_scopes(&self, slot: SlotId) -> bool {
289        self.slot_to_scopes
290            .get(&slot)
291            .is_some_and(|scopes| scopes.iter().any(|scope| !scope.is_active()))
292    }
293
294    fn deactivate_slot(&self, slot: SlotId) {
295        if let Some(scopes) = self.slot_to_scopes.get(&slot) {
296            for scope in scopes {
297                scope.deactivate();
298            }
299        }
300    }
301
302    fn invalidate_scopes(&self) {
303        for scopes in self.slot_to_scopes.values() {
304            for scope in scopes {
305                scope.invalidate();
306            }
307        }
308    }
309}
310
311/// Tracks the state of nodes produced by subcomposition, enabling reuse between
312/// measurement passes.
313pub struct SubcomposeState {
314    mapping: NodeSlotMapping,
315    active_order: Vec<SlotId>,
316    live_slots: HashSet<SlotId>,
317    current_pass_active_slots: HashSet<SlotId>,
318    reusable_by_type: HashMap<u64, VecDeque<(SlotId, NodeId)>>,
319    reusable_nodes_untyped: VecDeque<(SlotId, NodeId)>,
320    reusable_node_counts: HashMap<SlotId, usize>,
321    exact_reactivation_slots: HashSet<SlotId>,
322    slot_content_types: HashMap<SlotId, u64>,
323    precomposed_nodes: HashMap<SlotId, Vec<NodeId>>,
324    policy: Box<dyn SlotReusePolicy>,
325    pub(crate) current_index: usize,
326    pub(crate) reusable_count: usize,
327    pub(crate) precomposed_count: usize,
328    slot_compositions: HashMap<SlotId, Rc<SlotsHost>>,
329    slot_callbacks: HashMap<SlotId, CallbackHolder>,
330    max_reusable_per_type: usize,
331    max_reusable_untyped: usize,
332    last_slot_reused: Option<bool>,
333    retained_capture_keys: HashMap<SlotId, RetainedCaptureKey>,
334    content_generation: std::cell::Cell<u64>,
335    slot_composed_generation: HashMap<SlotId, (u64, u64)>,
336}
337
338struct RetainedCaptureKey {
339    value: Box<dyn Any>,
340    eq: fn(&dyn Any, &dyn Any) -> bool,
341}
342
343fn retained_capture_key_eq<K: PartialEq + 'static>(stored: &dyn Any, candidate: &dyn Any) -> bool {
344    match (stored.downcast_ref::<K>(), candidate.downcast_ref::<K>()) {
345        (Some(stored), Some(candidate)) => stored == candidate,
346        _ => false,
347    }
348}
349
350impl fmt::Debug for SubcomposeState {
351    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
352        f.debug_struct("SubcomposeState")
353            .field("mapping", &self.mapping)
354            .field("active_order", &self.active_order)
355            .field("reusable_by_type_count", &self.reusable_by_type.len())
356            .field("reusable_untyped_count", &self.reusable_nodes_untyped.len())
357            .field("precomposed_nodes", &self.precomposed_nodes)
358            .field("current_index", &self.current_index)
359            .field("reusable_count", &self.reusable_count)
360            .field("precomposed_count", &self.precomposed_count)
361            .field("slot_compositions_count", &self.slot_compositions.len())
362            .finish()
363    }
364}
365
366impl Default for SubcomposeState {
367    fn default() -> Self {
368        Self::new(Box::new(DefaultSlotReusePolicy))
369    }
370}
371
372const DEFAULT_MAX_REUSABLE_PER_TYPE: usize = 5;
373
374const DEFAULT_MAX_REUSABLE_UNTYPED: usize = 10;
375
376impl SubcomposeState {
377    /// Creates a new [`SubcomposeState`] using the supplied reuse policy.
378    pub fn new(policy: Box<dyn SlotReusePolicy>) -> Self {
379        Self {
380            mapping: NodeSlotMapping::default(),
381            active_order: Vec::new(),
382            live_slots: HashSet::default(),
383            current_pass_active_slots: HashSet::default(),
384            reusable_by_type: HashMap::default(),
385            reusable_nodes_untyped: VecDeque::new(),
386            reusable_node_counts: HashMap::default(),
387            exact_reactivation_slots: HashSet::default(),
388            slot_content_types: HashMap::default(),
389            precomposed_nodes: HashMap::default(),
390            policy,
391            current_index: 0,
392            reusable_count: 0,
393            precomposed_count: 0,
394            slot_compositions: HashMap::default(),
395            slot_callbacks: HashMap::default(),
396            max_reusable_per_type: DEFAULT_MAX_REUSABLE_PER_TYPE,
397            max_reusable_untyped: DEFAULT_MAX_REUSABLE_UNTYPED,
398            last_slot_reused: None,
399            retained_capture_keys: HashMap::default(),
400            content_generation: std::cell::Cell::new(0),
401            slot_composed_generation: HashMap::default(),
402        }
403    }
404
405    /// Sets the policy used for future reuse decisions.
406    pub fn set_policy(&mut self, policy: Box<dyn SlotReusePolicy>) {
407        self.policy = policy;
408    }
409
410    pub fn set_reusable_pool_limits(&mut self, per_type: usize, untyped: usize) {
411        self.max_reusable_per_type = per_type;
412        self.max_reusable_untyped = untyped;
413    }
414
415    /// Registers a content type for a slot.
416    ///
417    /// Stores the content type locally for efficient pool-based reuse lookup,
418    /// and also delegates to the policy for compatibility checking.
419    ///
420    /// Call this before subcomposing an item to enable content-type-aware slot reuse.
421    pub fn register_content_type(&mut self, slot_id: SlotId, content_type: u64) {
422        self.slot_content_types.insert(slot_id, content_type);
423        self.policy.register_content_type(slot_id, content_type);
424    }
425
426    /// Updates the content type for a slot, handling optional content types.
427    ///
428    /// If `content_type` is `Some(type)`, registers the type for the slot.
429    /// If `content_type` is `None`, removes any previously registered type.
430    /// This ensures stale types don't drive incorrect reuse.
431    pub fn update_content_type(&mut self, slot_id: SlotId, content_type: Option<u64>) {
432        match content_type {
433            Some(ct) => self.register_content_type(slot_id, ct),
434            None => {
435                self.slot_content_types.remove(&slot_id);
436                self.policy.remove_content_type(slot_id);
437            }
438        }
439    }
440
441    /// Returns the content type for a slot, if registered.
442    pub fn get_content_type(&self, slot_id: SlotId) -> Option<u64> {
443        self.slot_content_types.get(&slot_id).copied()
444    }
445
446    /// Returns the active slot that owns a registered root node.
447    ///
448    /// Descendants must be resolved to their slot root by the caller. Reusable
449    /// and removed slots are excluded.
450    pub fn active_slot_for_node(&self, node_id: NodeId) -> Option<SlotId> {
451        self.mapping
452            .node_to_slot
453            .get(&node_id)
454            .copied()
455            .filter(|slot| self.live_slots.contains(slot))
456    }
457
458    /// Starts a new subcompose pass.
459    ///
460    /// Call this before subcomposing the current frame so the state can
461    /// track which slots are active and dispose the inactive ones later.
462    pub fn begin_pass(&mut self) {
463        self.current_index = 0;
464        self.current_pass_active_slots.clear();
465    }
466
467    /// Returns the current active slot cursor for the in-progress pass.
468    pub fn active_slot_cursor(&self) -> usize {
469        self.current_index
470    }
471
472    /// Restores the active slot cursor for work that should not become part of
473    /// the rendered active set, such as lazy-list prefetch measurement.
474    pub fn restore_active_slot_cursor(&mut self, cursor: usize) {
475        self.current_index = cursor.min(self.active_order.len());
476    }
477
478    /// Moves an active slot out of the rendered set and into the reusable pool.
479    pub fn recycle_active_slot(&mut self, slot_id: SlotId) -> SubcomposeDisposal {
480        self.recycle_active_slot_internal(slot_id, false)
481    }
482
483    pub fn recycle_prefetched_active_slot(&mut self, slot_id: SlotId) -> SubcomposeDisposal {
484        self.recycle_active_slot_internal(slot_id, true)
485    }
486
487    pub fn recycle_active_slots_where(
488        &mut self,
489        mut predicate: impl FnMut(SlotId) -> bool,
490    ) -> SubcomposeDisposal {
491        let slots: Vec<_> = self
492            .active_order
493            .iter()
494            .copied()
495            .filter(|slot| !self.current_pass_active_slots.contains(slot))
496            .filter(|slot| predicate(*slot))
497            .collect();
498        let mut disposed = SubcomposeDisposal::default();
499        for slot in slots {
500            disposed.append(self.recycle_active_slot(slot));
501        }
502        disposed
503    }
504
505    fn recycle_active_slot_internal(
506        &mut self,
507        slot_id: SlotId,
508        allow_exact_reactivation: bool,
509    ) -> SubcomposeDisposal {
510        let Some(position) = self
511            .active_order
512            .iter()
513            .position(|candidate| *candidate == slot_id)
514        else {
515            return SubcomposeDisposal::default();
516        };
517        self.active_order.remove(position);
518        if position < self.current_index {
519            self.current_index = self.current_index.saturating_sub(1);
520        }
521        self.move_slot_to_reusable(slot_id, allow_exact_reactivation);
522        self.enforce_reusable_pool_limits()
523    }
524
525    /// Finishes a subcompose pass, disposing slots that were not used.
526    pub fn finish_pass(&mut self) -> SubcomposeDisposal {
527        self.dispose_or_reuse_starting_from_index(self.current_index)
528    }
529
530    /// Returns the SlotsHost for the given slot ID, creating a new one if it doesn't exist.
531    /// Each slot gets its own isolated slot table, avoiding cursor-based conflicts when
532    /// items are subcomposed in different orders.
533    pub fn get_or_create_slots(&mut self, slot_id: SlotId) -> Rc<SlotsHost> {
534        Rc::clone(
535            self.slot_compositions
536                .entry(slot_id)
537                .or_insert_with(|| Rc::new(SlotsHost::new(SlotTable::new()))),
538        )
539    }
540
541    /// Returns the latest callback holder for the given slot, creating one if needed.
542    pub fn callback_holder(&mut self, slot_id: SlotId) -> CallbackHolder {
543        self.slot_callbacks.entry(slot_id).or_default().clone()
544    }
545
546    #[doc(hidden)]
547    pub fn activate_current_active_slot(&mut self, slot_id: SlotId) -> Option<&[NodeId]> {
548        self.activate_current_active_slot_at_cursor(slot_id)
549            .then(|| self.mapping.get_nodes(&slot_id))
550            .flatten()
551    }
552
553    fn activate_current_active_slot_at_cursor(&mut self, slot_id: SlotId) -> bool {
554        if self.current_pass_active_slots.contains(&slot_id)
555            || self.exact_reactivation_slots.contains(&slot_id)
556            || self.reusable_node_counts.contains_key(&slot_id)
557            || self
558                .active_order
559                .get(self.current_index)
560                .copied()
561                .is_none_or(|active_slot| active_slot != slot_id)
562            || self.mapping.slot_has_invalid_scopes(slot_id)
563            || self.mapping.slot_has_inactive_scopes(slot_id)
564        {
565            return false;
566        }
567
568        if self.mapping.get_nodes(&slot_id).is_none() {
569            return false;
570        }
571        self.last_slot_reused = Some(true);
572        self.live_slots.insert(slot_id);
573        self.current_pass_active_slots.insert(slot_id);
574        self.current_index += 1;
575        true
576    }
577
578    /// Whether precomposed nodes are waiting to be consumed for this slot.
579    /// A pending precomposition means the retained mapping is about to be
580    /// superseded, so clean-slot reuse must reject and compose.
581    pub fn has_pending_precompositions(&self, slot_id: SlotId) -> bool {
582        self.precomposed_nodes.contains_key(&slot_id)
583    }
584
585    /// Whether the slot's stored capture key equals `key`. A missing key never
586    /// matches: a slot must compose at least once under the key discipline
587    /// before it may skip.
588    pub fn retained_capture_key_matches<K: PartialEq + 'static>(
589        &self,
590        slot_id: SlotId,
591        key: &K,
592    ) -> bool {
593        self.retained_capture_keys
594            .get(&slot_id)
595            .is_some_and(|retained| (retained.eq)(retained.value.as_ref(), key))
596    }
597
598    /// Records the capture key the slot is being composed under.
599    pub fn store_retained_capture_key<K: PartialEq + 'static>(&mut self, slot_id: SlotId, key: K) {
600        self.retained_capture_keys.insert(
601            slot_id,
602            RetainedCaptureKey {
603                value: Box::new(key),
604                eq: retained_capture_key_eq::<K>,
605            },
606        );
607    }
608
609    #[doc(hidden)]
610    pub fn activate_exact_slot(&mut self, slot_id: SlotId) -> Option<ExactSlotActivation<'_>> {
611        if self.activate_current_active_slot_at_cursor(slot_id) {
612            return Some(ExactSlotActivation {
613                nodes: self.mapping.get_nodes(&slot_id)?,
614                was_recycled: false,
615            });
616        }
617        let active_position = self
618            .active_order
619            .iter()
620            .position(|candidate| *candidate == slot_id);
621        let is_exact_reactivation = self.exact_reactivation_slots.contains(&slot_id);
622        if active_position.is_none() && !is_exact_reactivation
623            || self.mapping.slot_has_invalid_scopes(slot_id)
624        {
625            return None;
626        }
627
628        let node_count = self.mapping.get_nodes(&slot_id)?.len();
629        if active_position.is_none() {
630            for index in 0..node_count {
631                let node = self.mapping.get_nodes(&slot_id)?[index];
632                let _ = self.remove_from_reusable_pools(node);
633            }
634            for scope in self.mapping.get_scopes(&slot_id).unwrap_or_default() {
635                scope.reactivate();
636            }
637        }
638        self.mark_slot_active(slot_id, true);
639        Self::consume_precomposed_nodes(
640            &mut self.precomposed_nodes,
641            &mut self.precomposed_count,
642            slot_id,
643            self.mapping.get_nodes(&slot_id)?,
644        );
645        Some(ExactSlotActivation {
646            nodes: self.mapping.get_nodes(&slot_id)?,
647            was_recycled: active_position.is_none(),
648        })
649    }
650
651    /// Records that the nodes in `node_ids` are currently rendering the provided
652    /// `slot_id`.
653    pub fn register_active(
654        &mut self,
655        slot_id: SlotId,
656        node_ids: &[NodeId],
657        scopes: &[RecomposeScope],
658    ) {
659        let was_reused = self.mapping.get_nodes(&slot_id).is_some();
660        for scope in scopes {
661            scope.reactivate();
662        }
663        self.update_active_slot_mapping(slot_id, node_ids, scopes);
664        self.mark_slot_active(slot_id, was_reused);
665    }
666
667    fn mark_slot_active(&mut self, slot_id: SlotId, was_reused: bool) {
668        self.last_slot_reused = Some(was_reused);
669        self.live_slots.insert(slot_id);
670        self.current_pass_active_slots.insert(slot_id);
671        self.exact_reactivation_slots.remove(&slot_id);
672
673        if let Some(position) = self.active_order.iter().position(|slot| *slot == slot_id) {
674            if position < self.current_index {
675                return;
676            }
677            self.active_order.remove(position);
678        }
679        let insert_at = self.current_index.min(self.active_order.len());
680        self.active_order.insert(insert_at, slot_id);
681        self.current_index += 1;
682    }
683
684    fn update_active_slot_mapping(
685        &mut self,
686        slot_id: SlotId,
687        node_ids: &[NodeId],
688        scopes: &[RecomposeScope],
689    ) {
690        self.mapping.set_nodes(slot_id, node_ids);
691        self.mapping.set_scopes(slot_id, scopes);
692        Self::consume_precomposed_nodes(
693            &mut self.precomposed_nodes,
694            &mut self.precomposed_count,
695            slot_id,
696            node_ids,
697        );
698    }
699
700    fn consume_precomposed_nodes(
701        precomposed_nodes: &mut HashMap<SlotId, Vec<NodeId>>,
702        precomposed_count: &mut usize,
703        slot_id: SlotId,
704        node_ids: &[NodeId],
705    ) {
706        if let Some(nodes) = precomposed_nodes.get_mut(&slot_id) {
707            let before_len = nodes.len();
708            nodes.retain(|node| !node_ids.contains(node));
709            let removed = before_len - nodes.len();
710            *precomposed_count = precomposed_count.saturating_sub(removed);
711            if nodes.is_empty() {
712                precomposed_nodes.remove(&slot_id);
713            }
714        }
715    }
716
717    /// Stores a precomposed node for the provided slot. Precomposed nodes stay
718    /// detached from the tree until they are activated by `register_active`.
719    pub fn register_precomposed(&mut self, slot_id: SlotId, node_id: NodeId) {
720        self.precomposed_nodes
721            .entry(slot_id)
722            .or_default()
723            .push(node_id);
724        self.precomposed_count += 1;
725    }
726
727    fn increment_reusable_slot(&mut self, slot_id: SlotId) {
728        *self.reusable_node_counts.entry(slot_id).or_insert(0) += 1;
729        self.reusable_count += 1;
730    }
731
732    fn decrement_reusable_slot(&mut self, slot_id: SlotId) {
733        let Some(entry) = self.reusable_node_counts.get_mut(&slot_id) else {
734            self.reusable_count = self.reusable_count.saturating_sub(1);
735            return;
736        };
737        *entry = entry.saturating_sub(1);
738        if *entry == 0 {
739            self.reusable_node_counts.remove(&slot_id);
740        }
741        self.reusable_count = self.reusable_count.saturating_sub(1);
742    }
743
744    /// Whether `slot_id` still has a composition here: active, or kept in the
745    /// reuse pool where it can be reactivated. A slot that is neither has
746    /// been disposed, and nothing measured for it can be used again.
747    pub fn slot_is_retained(&self, slot_id: SlotId) -> bool {
748        self.live_slots.contains(&slot_id) || self.reusable_node_counts.contains_key(&slot_id)
749    }
750
751    fn prune_slot_if_unused(&mut self, slot_id: SlotId) -> Option<Rc<SlotsHost>> {
752        if self.slot_is_retained(slot_id) {
753            return None;
754        }
755
756        debug_assert!(
757            self.mapping.get_nodes(&slot_id).is_none(),
758            "inactive slot {slot_id:?} still has mapped nodes",
759        );
760
761        let host = self.slot_compositions.remove(&slot_id);
762        self.slot_callbacks.remove(&slot_id);
763        self.slot_content_types.remove(&slot_id);
764        self.retained_capture_keys.remove(&slot_id);
765        self.slot_composed_generation.remove(&slot_id);
766        self.policy.remove_content_type(slot_id);
767        if let Some(nodes) = self.precomposed_nodes.remove(&slot_id) {
768            self.precomposed_count = self.precomposed_count.saturating_sub(nodes.len());
769        }
770        host
771    }
772
773    /// Returns the node that previously rendered this slot, if it is still
774    /// considered reusable, and whether it was REBOUND — taken from another
775    /// slot, so its retained subtree is about to show different content. An
776    /// exact-slot reactivation hands the same item its own subtree back and
777    /// is not a rebinding.
778    ///
779    /// Lookup order:
780    /// 1. Exact slot match in the appropriate pool (not a rebinding)
781    /// 2. Any policy-compatible node from the same content-type pool
782    /// 3. Fallback to untyped pool with policy compatibility check
783    pub fn take_node_from_reusables(&mut self, slot_id: SlotId) -> Option<(NodeId, bool)> {
784        if let Some(nodes) = self.mapping.get_nodes(&slot_id) {
785            let first_node = nodes.first().copied();
786            if let Some(node_id) = first_node {
787                let _ = self.remove_from_reusable_pools(node_id);
788                self.exact_reactivation_slots.remove(&slot_id);
789                return Some((node_id, false));
790            }
791        }
792
793        let content_type = self.slot_content_types.get(&slot_id).copied();
794
795        if let Some(ct) = content_type
796            && let Some((old_slot, node_id)) = self.take_compatible_typed_reusable(ct, slot_id)
797        {
798            self.decrement_reusable_slot(old_slot);
799            self.move_node_to_slot(node_id, old_slot, slot_id);
800            return Some((node_id, true));
801        }
802
803        let exact_reactivation_slots = &self.exact_reactivation_slots;
804        let policy = &self.policy;
805        let position = self
806            .reusable_nodes_untyped
807            .iter()
808            .position(|(existing_slot, _)| {
809                !exact_reactivation_slots.contains(existing_slot)
810                    && policy.are_compatible(*existing_slot, slot_id)
811            });
812
813        if let Some(index) = position
814            && let Some((old_slot, node_id)) = self.reusable_nodes_untyped.remove(index)
815        {
816            self.decrement_reusable_slot(old_slot);
817            self.move_node_to_slot(node_id, old_slot, slot_id);
818            return Some((node_id, true));
819        }
820
821        None
822    }
823
824    fn take_compatible_typed_reusable(
825        &mut self,
826        content_type: u64,
827        requested_slot: SlotId,
828    ) -> Option<(SlotId, NodeId)> {
829        let reused = {
830            let policy = &self.policy;
831            let exact_reactivation_slots = &self.exact_reactivation_slots;
832            let pool = self.reusable_by_type.get_mut(&content_type)?;
833            let index = pool.iter().position(|(existing_slot, _)| {
834                !exact_reactivation_slots.contains(existing_slot)
835                    && policy.are_compatible(*existing_slot, requested_slot)
836            })?;
837            pool.remove(index)
838        };
839
840        if self
841            .reusable_by_type
842            .get(&content_type)
843            .is_some_and(std::collections::VecDeque::is_empty)
844        {
845            self.reusable_by_type.remove(&content_type);
846        }
847
848        reused
849    }
850
851    fn remove_from_reusable_pools(&mut self, node_id: NodeId) -> Option<SlotId> {
852        let mut typed_match = None;
853        for (&content_type, pool) in &self.reusable_by_type {
854            if let Some(position) = pool
855                .iter()
856                .position(|(_, pooled_node)| *pooled_node == node_id)
857            {
858                typed_match = Some((content_type, position));
859                break;
860            }
861        }
862        if let Some((content_type, position)) = typed_match {
863            let pool = self.reusable_by_type.get_mut(&content_type)?;
864            let (slot, _) = pool.remove(position)?;
865            if pool.is_empty() {
866                self.reusable_by_type.remove(&content_type);
867            }
868            self.decrement_reusable_slot(slot);
869            return Some(slot);
870        }
871        if let Some(position) = self
872            .reusable_nodes_untyped
873            .iter()
874            .position(|(_, n)| *n == node_id)
875            && let Some((slot, _)) = self.reusable_nodes_untyped.remove(position)
876        {
877            self.decrement_reusable_slot(slot);
878            return Some(slot);
879        }
880        None
881    }
882
883    fn move_node_to_slot(&mut self, node_id: NodeId, old_slot: SlotId, new_slot: SlotId) {
884        if old_slot == new_slot {
885            return;
886        }
887
888        self.mapping.remove_by_node(&node_id);
889        self.exact_reactivation_slots.remove(&old_slot);
890        self.mapping.add_node(new_slot, node_id);
891        self.slot_content_types.remove(&old_slot);
892        self.retained_capture_keys.remove(&old_slot);
893        self.retained_capture_keys.remove(&new_slot);
894        self.slot_composed_generation.remove(&old_slot);
895        self.slot_composed_generation.remove(&new_slot);
896        self.policy.remove_content_type(old_slot);
897        if let Some(slots) = self.slot_compositions.remove(&old_slot) {
898            self.slot_compositions.insert(new_slot, slots);
899        }
900        if let Some(callback) = self.slot_callbacks.remove(&old_slot) {
901            self.slot_callbacks.insert(new_slot, callback);
902        }
903        if let Some(nodes) = self.precomposed_nodes.get_mut(&old_slot) {
904            let before_len = nodes.len();
905            nodes.retain(|candidate| *candidate != node_id);
906            let removed = before_len - nodes.len();
907            self.precomposed_count = self.precomposed_count.saturating_sub(removed);
908            if nodes.is_empty() {
909                self.precomposed_nodes.remove(&old_slot);
910            }
911        }
912    }
913
914    /// Moves active slots starting from `start_index` to the reusable bucket.
915    /// Returns the list of node ids that were DISPOSED (not just moved to reusable).
916    /// Nodes that exceed max_reusable_per_type are disposed instead of cached.
917    pub fn dispose_or_reuse_starting_from_index(
918        &mut self,
919        start_index: usize,
920    ) -> SubcomposeDisposal {
921        if start_index >= self.active_order.len() {
922            return SubcomposeDisposal::default();
923        }
924
925        let retain = self
926            .policy
927            .get_slots_to_retain(&self.active_order[start_index..]);
928        let mut retained = Vec::new();
929        while self.active_order.len() > start_index {
930            let Some(slot) = self.active_order.pop() else {
931                break;
932            };
933            if retain.contains(&slot) {
934                retained.push(slot);
935                continue;
936            }
937            self.move_slot_to_reusable(slot, false);
938        }
939        retained.reverse();
940        self.active_order.extend(retained);
941
942        self.enforce_reusable_pool_limits()
943    }
944
945    fn move_slot_to_reusable(&mut self, slot: SlotId, allow_exact_reactivation: bool) {
946        self.live_slots.remove(&slot);
947        self.current_pass_active_slots.remove(&slot);
948        self.mapping.deactivate_slot(slot);
949        let forgot_effects = self
950            .slot_compositions
951            .get(&slot)
952            .is_some_and(|host| host.forget_effects());
953        if allow_exact_reactivation && !forgot_effects {
954            self.exact_reactivation_slots.insert(slot);
955        } else {
956            self.exact_reactivation_slots.remove(&slot);
957        }
958
959        let content_type = self.slot_content_types.get(&slot).copied();
960        let nodes: SmallVec<[NodeId; 4]> = self
961            .mapping
962            .get_nodes(&slot)
963            .into_iter()
964            .flatten()
965            .copied()
966            .collect();
967        for node in nodes {
968            if let Some(ct) = content_type {
969                self.reusable_by_type
970                    .entry(ct)
971                    .or_default()
972                    .push_back((slot, node));
973            } else {
974                self.reusable_nodes_untyped.push_back((slot, node));
975            }
976            self.increment_reusable_slot(slot);
977        }
978    }
979
980    fn enforce_reusable_pool_limits(&mut self) -> SubcomposeDisposal {
981        let mut disposed = SubcomposeDisposal::default();
982        let mut typed_disposals = Vec::new();
983        for pool in self.reusable_by_type.values_mut() {
984            while pool.len() > self.max_reusable_per_type {
985                if let Some((slot, node_id)) = pool.pop_front() {
986                    typed_disposals.push((slot, node_id));
987                }
988            }
989        }
990        for (slot, node_id) in typed_disposals {
991            self.decrement_reusable_slot(slot);
992            self.mapping.remove_by_node(&node_id);
993            self.exact_reactivation_slots.remove(&slot);
994            disposed.slot_hosts.extend(self.prune_slot_if_unused(slot));
995            disposed.nodes.push(node_id);
996        }
997
998        while self.reusable_nodes_untyped.len() > self.max_reusable_untyped {
999            if let Some((slot, node_id)) = self.reusable_nodes_untyped.pop_front() {
1000                self.decrement_reusable_slot(slot);
1001                self.mapping.remove_by_node(&node_id);
1002                self.exact_reactivation_slots.remove(&slot);
1003                disposed.slot_hosts.extend(self.prune_slot_if_unused(slot));
1004                disposed.nodes.push(node_id);
1005            }
1006        }
1007
1008        self.reusable_by_type.retain(|_, pool| !pool.is_empty());
1009        disposed
1010    }
1011
1012    /// Returns a snapshot of currently reusable nodes.
1013    pub fn reusable(&self) -> Vec<NodeId> {
1014        let mut nodes: Vec<NodeId> = self
1015            .reusable_by_type
1016            .values()
1017            .flat_map(|pool| pool.iter().map(|(_, n)| *n))
1018            .collect();
1019        nodes.extend(self.reusable_nodes_untyped.iter().map(|(_, n)| *n));
1020        nodes
1021    }
1022
1023    /// Returns the number of slots currently active (in use during this pass).
1024    ///
1025    /// This reflects the slots that were activated via `register_active()` during
1026    /// the current measurement pass.
1027    pub fn active_slots_count(&self) -> usize {
1028        self.active_order.len()
1029    }
1030
1031    /// Returns the number of reusable slots in the pool.
1032    ///
1033    /// These are slots that were previously active but are now available for reuse
1034    /// by compatible content types.
1035    pub fn reusable_slots_count(&self) -> usize {
1036        self.reusable_count
1037    }
1038
1039    /// Invalidates all tracked subcomposition scopes.
1040    ///
1041    /// Hosts should call this when parent-captured inputs change without directly invalidating
1042    /// the child scopes themselves. The next subcompose pass will then re-run active slot
1043    /// content instead of skipping with stale captures.
1044    /// Invalidating scopes alone is not a reliable "recompose on next
1045    /// measure" signal: the recomposer drains invalid scopes before measure
1046    /// runs, re-executing the RETAINED slot callbacks — parent-captured
1047    /// values baked into a replaced closure never flow in, yet the scopes
1048    /// come back valid. The generation bump is the unlaunderable half: only
1049    /// a measure-time compose of the slot brings it current, so clean-slot
1050    /// reuse stays blocked until the new content actually landed.
1051    pub fn invalidate_scopes(&self) {
1052        self.mapping.invalidate_scopes();
1053        self.content_generation
1054            .set(self.content_generation.get() + 1);
1055    }
1056
1057    /// Advances the content generation without invalidating scopes: every
1058    /// slot must re-compose once before clean-slot reuse may skip it again.
1059    /// Called when the owning node leaves its parent — a retained subtree
1060    /// that comes back from the reuse pool restarts its effects only if its
1061    /// slots actually recompose, and scope flags carry no durable trace of
1062    /// the detach (deactivation walks stop at nested slot-host boundaries).
1063    pub fn bump_content_generation(&self) {
1064        self.content_generation
1065            .set(self.content_generation.get() + 1);
1066    }
1067
1068    /// Whether the slot last composed under the current content generation
1069    /// and owner-chain deactivation epoch. False after any
1070    /// [`Self::invalidate_scopes`], and false after any composition up the
1071    /// owner chain was deactivated, until a measure-time compose of this
1072    /// slot runs.
1073    pub fn slot_content_generation_current(&self, slot_id: SlotId, owner_epoch: u64) -> bool {
1074        self.slot_composed_generation.get(&slot_id).copied()
1075            == Some((self.content_generation.get(), owner_epoch))
1076    }
1077
1078    /// Records that the slot just composed under the current generation and
1079    /// the given owner-chain deactivation epoch.
1080    pub fn mark_slot_composed_current(&mut self, slot_id: SlotId, owner_epoch: u64) {
1081        self.slot_composed_generation
1082            .insert(slot_id, (self.content_generation.get(), owner_epoch));
1083    }
1084
1085    /// Returns whether the last slot registered via [`Self::register_active`] was reused.
1086    ///
1087    /// Returns `Some(true)` if the slot already existed (was reused from pool or
1088    /// was recomposed), `Some(false)` if it was newly created, or `None` if no
1089    /// slot has been registered yet this pass.
1090    ///
1091    /// This is useful for tracking composition statistics in lazy layouts.
1092    pub fn was_last_slot_reused(&self) -> Option<bool> {
1093        self.last_slot_reused
1094    }
1095
1096    #[doc(hidden)]
1097    pub fn debug_scope_ids_by_slot(&self) -> Vec<(u64, Vec<usize>)> {
1098        self.mapping
1099            .slot_to_scopes
1100            .iter()
1101            .map(|(slot, scopes)| (slot.raw(), scopes.iter().map(RecomposeScope::id).collect()))
1102            .collect()
1103    }
1104
1105    #[doc(hidden)]
1106    pub fn debug_slot_table_for_slot(&self, slot_id: SlotId) -> Option<Vec<crate::SlotDebugEntry>> {
1107        let slots = self.slot_compositions.get(&slot_id)?;
1108        Some(slots.borrow().debug_dump_slot_entries())
1109    }
1110
1111    #[doc(hidden)]
1112    pub fn debug_slot_table_groups_for_slot(&self, slot_id: SlotId) -> Option<Vec<DebugSlotGroup>> {
1113        let slots = self.slot_compositions.get(&slot_id)?;
1114        Some(slots.borrow().debug_dump_groups())
1115    }
1116
1117    /// Returns a snapshot of precomposed nodes.
1118    pub fn precomposed(&self) -> &HashMap<SlotId, Vec<NodeId>> {
1119        &self.precomposed_nodes
1120    }
1121
1122    /// Removes any precomposed nodes whose slots were not activated during the
1123    /// current pass and returns their identifiers for disposal.
1124    pub fn drain_inactive_precomposed(&mut self) -> SubcomposeDisposal {
1125        let mut disposed = SubcomposeDisposal::default();
1126        let mut empty_slots = Vec::new();
1127        for (slot, nodes) in &mut self.precomposed_nodes {
1128            if !self.current_pass_active_slots.contains(slot) {
1129                disposed.nodes.extend(nodes.iter().copied());
1130                empty_slots.push(*slot);
1131            }
1132        }
1133        for slot in empty_slots {
1134            self.precomposed_nodes.remove(&slot);
1135            disposed.slot_hosts.extend(self.prune_slot_if_unused(slot));
1136        }
1137        self.precomposed_count = self.precomposed_count.saturating_sub(disposed.nodes.len());
1138        disposed
1139    }
1140}
1141
1142#[cfg(test)]
1143#[path = "tests/subcompose_tests.rs"]
1144mod tests;