Skip to main content

cranpose_core/
lib.rs

1#![doc = include_str!("../README.md")]
2#![deny(unsafe_code)]
3
4pub extern crate self as cranpose_core;
5
6mod callbacks;
7mod composer;
8pub mod composer_context;
9mod composition;
10mod composition_locals;
11pub mod concurrency;
12mod debug_trace;
13mod effect_key;
14mod emit;
15pub mod env_flags;
16#[cfg(any(feature = "internal", test))]
17mod frame_clock;
18mod hooks;
19mod launched_effect;
20pub mod owned;
21pub mod platform;
22mod recompose;
23mod retention;
24pub mod runtime;
25mod slot;
26pub mod snapshot_double_index_heap;
27pub mod snapshot_id_set;
28pub mod snapshot_pinning;
29pub mod snapshot_state_observer;
30pub mod snapshot_v2;
31mod snapshot_weak_set;
32mod state;
33pub mod subcompose;
34
35#[cfg(feature = "internal")]
36#[doc(hidden)]
37pub mod internal {
38    pub use crate::frame_clock::{FrameCallbackRegistration, FrameClock};
39}
40pub use callbacks::{CallbackHolder, CallbackHolder1, ParamSlot, ParamState, ReturnSlot};
41pub use composer::{BranchGroupGuard, CapturedCompositionContext, Composer, ValueSlotHandle};
42pub(crate) use composer::{ComposerCore, EmittedNode, ParentAttachMode, ParentFrame};
43pub use composition::{Composition, ROOT_RENDER_REPLAY_LIMIT};
44pub use composition_locals::{
45    CompositionLocal, CompositionLocalProvider, ProvidedValue, StaticCompositionLocal,
46    compositionLocalOf, compositionLocalOfWithPolicy, staticCompositionLocalOf,
47};
48pub(crate) use composition_locals::{LocalStateEntry, StaticLocalEntry};
49pub use concurrency::{
50    CollectEvents, CoroutineScope, Delay, EventChannel, EventSender, EventStream, EventStreamNext,
51    ProduceScope, collectAsState, delay, interval, launchBlocking, produceState,
52    rememberCoroutineScope, rememberEventStream, spawn_ui_task, withBlocking,
53};
54#[doc(hidden)]
55pub use debug_trace::{
56    debug_label_current_scope, debug_live_recompose_scope_count,
57    debug_recompose_scope_registry_stats, debug_scope_invalidation_sources, debug_scope_label,
58};
59pub use hooks::{
60    derivedStateOf, mutableStateList, mutableStateListOf, mutableStateMap, mutableStateMapOf,
61    mutableStateOf, mutableStateOfNeverEqual, ownedMutableStateOf, ownedMutableStateOfNeverEqual,
62    remember, rememberKeyed, rememberMutableStateOf, rememberMutableStateOfNeverEqual,
63    rememberUpdatedState, try_mutableStateOf,
64};
65#[cfg(feature = "internal")]
66#[doc(hidden)]
67pub use hooks::{withFrameMillis, withFrameNanos};
68pub use launched_effect::{
69    __launched_effect_async_impl, __launched_effect_impl, CancelToken, LaunchedEffect,
70    LaunchedEffectAsync, LaunchedEffectScope, TaskSite,
71};
72pub use owned::Owned;
73pub use platform::{Clock, RuntimeScheduler, SchedulerRef, scheduler_ref};
74pub use retention::{RetentionBudget, RetentionEvictionPolicy, RetentionMode, RetentionPolicy};
75#[doc(hidden)]
76pub use runtime::{
77    DefaultScheduler, Runtime, RuntimeHandle, StateId, TaskHandle, UiDispatcher,
78    current_runtime_handle, label_next_ui_task, schedule_frame, schedule_node_update,
79};
80pub use slot::{
81    SlotDebugAnchor, SlotDebugEntry, SlotDebugEntryKind, SlotDebugGroup, SlotDebugScope,
82    SlotDebugSnapshot, SlotRetentionDebugStats, SlotTable, SlotTableDebugStats,
83    SlotTableLocalDebugStats, SlotTableMutationDebugStats,
84};
85#[doc(hidden)]
86pub use snapshot_state_observer::SnapshotStateObserver;
87
88/// Runs the provided closure inside a mutable snapshot and applies the result.
89///
90/// Use this function when you need to update `MutableState` from outside the
91/// composition or layout phase, typically in event handlers or async tasks.
92///
93/// # Why is this needed?
94/// Cranpose uses a snapshot system (MVCC) to isolate state changes. Modifications
95/// made to `MutableState` are only visible to the current thread's active snapshot.
96/// To make changes visible to the rest of the system (and trigger recomposition),
97/// they must be "applied" by committing the snapshot. This helper handles that
98/// lifecycle for you.
99///
100/// # Example
101///
102/// ```ignore
103/// // Inside a button click handler
104/// run_in_mutable_snapshot(|| {
105///     count.set(count.value() + 1);
106/// });
107/// ```
108///
109/// # Important
110/// ALL UI event handlers (keyboard, mouse, touch, animations) that modify state
111/// MUST use this function or [`dispatch_ui_event`].
112pub fn run_in_mutable_snapshot<T>(block: impl FnOnce() -> T) -> Result<T, &'static str> {
113    let snapshot = snapshot_v2::take_mutable_snapshot(None, None);
114
115    let _applied_guard = AppliedSnapshotFlagGuard::enter();
116    let value = snapshot.enter(block);
117
118    match snapshot.apply() {
119        snapshot_v2::SnapshotApplyResult::Success => Ok(value),
120        snapshot_v2::SnapshotApplyResult::Failure => Err("Snapshot apply failed"),
121    }
122}
123
124struct AppliedSnapshotFlagGuard {
125    previous: bool,
126}
127
128impl AppliedSnapshotFlagGuard {
129    fn enter() -> Self {
130        let previous = IN_APPLIED_SNAPSHOT.with(|flag| {
131            let previous = flag.get();
132            flag.set(true);
133            previous
134        });
135        Self { previous }
136    }
137}
138
139impl Drop for AppliedSnapshotFlagGuard {
140    fn drop(&mut self) {
141        IN_APPLIED_SNAPSHOT.with(|flag| flag.set(self.previous));
142    }
143}
144
145/// Dispatches a UI event in a proper snapshot context.
146///
147/// This is a convenience wrapper around [`run_in_mutable_snapshot`] that returns
148/// `Option<T>` instead of `Result<T, &str>`.
149///
150/// # Example
151/// ```ignore
152/// // In a keyboard event handler:
153/// dispatch_ui_event(|| {
154///     text_field_state.edit(|buffer| {
155///         buffer.insert("a");
156///     });
157/// });
158/// ```
159pub fn dispatch_ui_event<T>(block: impl FnOnce() -> T) -> Option<T> {
160    run_in_mutable_snapshot(block).ok()
161}
162
163thread_local! {
164    pub(crate) static IN_EVENT_HANDLER: Cell<bool> = const { Cell::new(false) };
165    pub(crate) static IN_APPLIED_SNAPSHOT: Cell<bool> = const { Cell::new(false) };
166}
167
168#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
169pub struct CompositionPassDebugStats {
170    pub commands_len: usize,
171    pub commands_cap: usize,
172    pub command_payload_len_bytes: usize,
173    pub command_payload_cap_bytes: usize,
174    pub sync_children_len: usize,
175    pub sync_children_cap: usize,
176    pub sync_child_ids_len: usize,
177    pub sync_child_ids_cap: usize,
178    pub side_effects_len: usize,
179    pub side_effects_cap: usize,
180}
181
182#[must_use]
183pub struct EventHandlerScopeGuard {
184    previous: bool,
185}
186
187impl Drop for EventHandlerScopeGuard {
188    fn drop(&mut self) {
189        IN_EVENT_HANDLER.with(|flag| flag.set(self.previous));
190    }
191}
192
193pub fn enter_event_handler_scope() -> EventHandlerScopeGuard {
194    let previous = IN_EVENT_HANDLER.with(|flag| {
195        let previous = flag.get();
196        flag.set(true);
197        previous
198    });
199    EventHandlerScopeGuard { previous }
200}
201
202/// Returns true if currently in an event handler context.
203pub fn in_event_handler() -> bool {
204    IN_EVENT_HANDLER.with(Cell::get)
205}
206
207/// Returns true if currently in an applied snapshot context.
208pub fn in_applied_snapshot() -> bool {
209    IN_APPLIED_SNAPSHOT.with(Cell::get)
210}
211
212use std::{
213    any::{Any, TypeId},
214    cell::{Cell, Ref, RefCell, RefMut},
215    cmp::Reverse,
216    collections::BinaryHeap,
217    hash::{Hash, Hasher},
218    ops::{Deref, DerefMut},
219    rc::{Rc, Weak},
220    sync::OnceLock,
221};
222
223#[cfg(test)]
224pub use runtime::{TestRuntime, TestScheduler};
225use smallvec::SmallVec;
226
227use crate::collections::map::{HashMap, HashSet};
228
229pub type Key = u64;
230pub type NodeId = usize;
231
232#[cfg(any(test, debug_assertions))]
233#[derive(Clone, Debug, PartialEq, Eq)]
234struct LocationKeyDebugInfo {
235    file: String,
236    line: u32,
237    column: u32,
238}
239
240#[cfg(any(test, debug_assertions))]
241thread_local! {
242    static LOCATION_KEY_REGISTRY: RefCell<HashMap<Key, LocationKeyDebugInfo>> =
243        RefCell::new(HashMap::default());
244    static LOCATION_KEY_COLLISION_COUNT: Cell<usize> = const { Cell::new(0) };
245}
246
247#[cfg(any(test, debug_assertions))]
248fn register_location_key_debug_info(key: Key, file: &str, line: u32, column: u32) {
249    let info = LocationKeyDebugInfo {
250        file: file.to_owned(),
251        line,
252        column,
253    };
254    let collision = LOCATION_KEY_REGISTRY.with(|registry| {
255        let mut registry = registry.borrow_mut();
256        match registry.entry(key) {
257            std::collections::hash_map::Entry::Vacant(entry) => {
258                entry.insert(info);
259                None
260            }
261            std::collections::hash_map::Entry::Occupied(entry) => {
262                let existing = entry.get();
263                (existing != &info).then(|| (existing.clone(), info))
264            }
265        }
266    });
267    if let Some((existing, incoming)) = collision {
268        LOCATION_KEY_COLLISION_COUNT.with(|count| {
269            count.set(count.get().saturating_add(1));
270        });
271        log::error!("location key collision: key={key} first={existing:?} second={incoming:?}");
272    }
273}
274
275#[cfg(all(debug_assertions, not(test)))]
276fn location_key_diagnostics_enabled() -> bool {
277    crate::env_flag!("CRANPOSE_LOCATION_KEY_DIAGNOSTICS")
278}
279
280#[cfg(test)]
281pub(crate) fn register_location_key_debug_info_for_test(
282    key: Key,
283    file: &str,
284    line: u32,
285    column: u32,
286) {
287    register_location_key_debug_info(key, file, line, column);
288}
289
290#[cfg(test)]
291pub(crate) fn location_key_debug_collision_count_for_test() -> usize {
292    LOCATION_KEY_COLLISION_COUNT.with(Cell::get)
293}
294
295#[cfg(test)]
296pub(crate) fn location_key_debug_info_for_test(key: Key) -> Option<LocationKeyDebugInfo> {
297    LOCATION_KEY_REGISTRY.with(|registry| registry.borrow().get(&key).cloned())
298}
299
300#[cfg(test)]
301pub(crate) fn slot_validation_diagnostics_enabled() -> bool {
302    true
303}
304
305#[cfg(all(debug_assertions, not(test)))]
306pub(crate) fn slot_validation_diagnostics_enabled() -> bool {
307    crate::env_flag!("CRANPOSE_VALIDATE_SLOTS")
308}
309
310fn source_location_key(file: &str, line: u32, column: u32) -> Key {
311    avalanche_location_key(source_location_hash(file, line, column))
312}
313
314fn source_location_hash(file: &str, line: u32, column: u32) -> u64 {
315    let mut hash = 0xcbf2_9ce4_8422_2325u64;
316    hash = fnv1a_location_key_bytes(hash, file.as_bytes());
317    hash = fnv1a_location_key_bytes(hash, &[0xff]);
318    hash = fnv1a_location_key_bytes(hash, &line.to_le_bytes());
319    hash = fnv1a_location_key_bytes(hash, &[0xfe]);
320    hash = fnv1a_location_key_bytes(hash, &column.to_le_bytes());
321    hash
322}
323
324fn fnv1a_location_key_bytes(mut hash: u64, bytes: &[u8]) -> u64 {
325    for byte in bytes {
326        hash ^= u64::from(*byte);
327        hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
328    }
329    hash
330}
331
332fn avalanche_location_key(mut value: u64) -> u64 {
333    value ^= value >> 33;
334    value = value.wrapping_mul(0xff51_afd7_ed55_8ccd);
335    value ^= value >> 33;
336    value = value.wrapping_mul(0xc4ce_b9fe_1a85_ec53);
337    value ^ (value >> 33)
338}
339
340#[doc(hidden)]
341#[track_caller]
342pub fn caller_location_key() -> Key {
343    let caller = std::panic::Location::caller();
344    location_key(caller.file(), caller.line(), caller.column())
345}
346
347#[doc(hidden)]
348#[track_caller]
349pub fn composable_identity_key(definition: Key) -> Key {
350    (definition.wrapping_mul(0x0000_0100_0000_01b3) ^ caller_location_key())
351        .wrapping_mul(0x0000_0100_0000_01b3)
352}
353
354#[doc(hidden)]
355pub fn composable_definition_key(
356    file: &str,
357    line: u32,
358    column: u32,
359    marker: std::any::TypeId,
360) -> Key {
361    let mut hasher = std::collections::hash_map::DefaultHasher::new();
362    std::hash::Hash::hash(&marker, &mut hasher);
363    location_key(file, line, column) ^ avalanche_location_key(std::hash::Hasher::finish(&hasher))
364}
365
366#[doc(hidden)]
367pub fn cached_composable_definition_key(
368    cell: &OnceLock<Key>,
369    file: &str,
370    line: u32,
371    column: u32,
372    marker: TypeId,
373) -> Key {
374    *cell.get_or_init(|| composable_definition_key(file, line, column, marker))
375}
376
377pub fn location_key(file: &str, line: u32, column: u32) -> Key {
378    let key = source_location_key(file, line, column);
379    #[cfg(test)]
380    register_location_key_debug_info(key, file, line, column);
381    #[cfg(all(debug_assertions, not(test)))]
382    if location_key_diagnostics_enabled() {
383        register_location_key_debug_info(key, file, line, column);
384    }
385    key
386}
387
388#[doc(hidden)]
389pub fn __branch_group_scope_deferred(key: Key) -> Option<BranchGroupGuard> {
390    with_current_composer_opt(|composer| composer.__branch_group_deferred(key))
391}
392
393#[doc(hidden)]
394pub fn branch_location_key(file: &str, line: u32, column: u32, branch: u32) -> Key {
395    let mut hash = source_location_hash(file, line, column);
396    hash = fnv1a_location_key_bytes(hash, &[0xfd]);
397    hash = fnv1a_location_key_bytes(hash, &branch.to_le_bytes());
398    let key = avalanche_location_key(hash);
399    #[cfg(test)]
400    register_location_key_debug_info(key, file, line, column);
401    #[cfg(all(debug_assertions, not(test)))]
402    if location_key_diagnostics_enabled() {
403        register_location_key_debug_info(key, file, line, column);
404    }
405    key
406}
407
408#[doc(hidden)]
409pub fn cached_branch_location_key(
410    cell: &OnceLock<Key>,
411    file: &str,
412    line: u32,
413    column: u32,
414    branch: u32,
415) -> Key {
416    *cell.get_or_init(|| branch_location_key(file, line, column, branch))
417}
418
419/// Stable identifier for a slot in the slot table.
420///
421/// Anchors provide positional stability: they maintain their identity even when
422/// the slot table is reorganized (e.g., during conditional rendering or group moves).
423/// This prevents effect states from being prematurely removed during recomposition.
424#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, Default)]
425pub struct AnchorId {
426    id: u32,
427    generation: u32,
428}
429
430impl AnchorId {
431    pub(crate) const INVALID: AnchorId = AnchorId {
432        id: 0,
433        generation: 0,
434    };
435
436    pub(crate) fn new(id: usize) -> Self {
437        Self {
438            id: crate::slot::checked_usize_to_u32(id, "anchor id"),
439            generation: 1,
440        }
441    }
442
443    /// Check if this anchor is valid (non-zero).
444    pub fn is_valid(&self) -> bool {
445        self.id != 0
446    }
447}
448
449pub(crate) type ScopeId = usize;
450pub(crate) type FrameCallbackId = u64;
451type LocalStackSnapshot = Rc<Vec<composer::LocalContext>>;
452
453#[derive(Clone)]
454pub(crate) struct LocalKey(Rc<()>);
455
456impl LocalKey {
457    fn new() -> Self {
458        Self(Rc::new(()))
459    }
460
461    pub(crate) fn entry_source(&self) -> Key {
462        avalanche_location_key(Rc::as_ptr(&self.0) as usize as u64)
463    }
464}
465
466impl std::fmt::Debug for LocalKey {
467    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
468        f.debug_tuple("LocalKey")
469            .field(&(Rc::as_ptr(&self.0) as usize))
470            .finish()
471    }
472}
473
474impl PartialEq for LocalKey {
475    fn eq(&self, other: &Self) -> bool {
476        Rc::ptr_eq(&self.0, &other.0)
477    }
478}
479
480impl Eq for LocalKey {}
481
482impl Hash for LocalKey {
483    fn hash<H: Hasher>(&self, state: &mut H) {
484        Rc::as_ptr(&self.0).hash(state);
485    }
486}
487
488thread_local! {
489    static EMPTY_LOCAL_STACK: LocalStackSnapshot = Rc::new(Vec::new());
490    #[cfg(debug_assertions)]
491    static DEBUG_SCOPE_LABELS: RefCell<HashMap<usize, &'static str>> = RefCell::new(HashMap::default());
492    #[cfg(debug_assertions)]
493    static DEBUG_SCOPE_INVALIDATION_SOURCES: RefCell<HashMap<usize, HashSet<String>>> =
494        RefCell::new(HashMap::default());
495    #[cfg(all(test, debug_assertions))]
496    static DEBUG_SCOPE_TRACKING_OVERRIDE: Cell<Option<bool>> = const { Cell::new(None) };
497}
498
499fn empty_local_stack() -> LocalStackSnapshot {
500    EMPTY_LOCAL_STACK.with(Rc::clone)
501}
502
503enum RecomposeCallback {
504    Static(fn(&Composer)),
505    Dynamic(Box<dyn FnMut(&Composer) + 'static>),
506}
507
508pub(crate) struct RecomposeScopeInner {
509    runtime: RuntimeHandle,
510    invalid: Cell<bool>,
511    enqueued: Cell<bool>,
512    active: Cell<bool>,
513    deactivations: Cell<u64>,
514    composed_once: Cell<bool>,
515    pending_recompose: Cell<bool>,
516    force_reuse: Cell<bool>,
517    force_recompose: Cell<bool>,
518    retention_mode: Cell<RetentionMode>,
519    parent_hint: Cell<Option<NodeId>>,
520    recompose: RefCell<Option<RecomposeCallback>>,
521    parent_scope: RefCell<Option<Weak<RecomposeScopeInner>>>,
522    lifetime_owner_scope: RefCell<Option<Weak<RecomposeScopeInner>>>,
523    local_stack: RefCell<LocalStackSnapshot>,
524    slots_storage_key: Cell<usize>,
525    slots_runtime_state: RefCell<Option<std::rc::Weak<crate::composer::ComposerRuntimeState>>>,
526    state_subscriptions: RefCell<HashSet<StateId>>,
527    invalidation_sources: RefCell<Option<HashSet<StateId>>>,
528}
529
530impl RecomposeScopeInner {
531    fn new(runtime: RuntimeHandle) -> Self {
532        runtime.increment_live_recompose_scope_count();
533        Self {
534            runtime,
535            invalid: Cell::new(false),
536            enqueued: Cell::new(false),
537            active: Cell::new(true),
538            deactivations: Cell::new(0),
539            composed_once: Cell::new(false),
540            pending_recompose: Cell::new(false),
541            force_reuse: Cell::new(false),
542            force_recompose: Cell::new(false),
543            retention_mode: Cell::new(RetentionMode::DisposeWhenInactive),
544            parent_hint: Cell::new(None),
545            recompose: RefCell::new(None),
546            parent_scope: RefCell::new(None),
547            lifetime_owner_scope: RefCell::new(None),
548            local_stack: RefCell::new(empty_local_stack()),
549            slots_storage_key: Cell::new(0),
550            slots_runtime_state: RefCell::new(None),
551            state_subscriptions: RefCell::new(HashSet::default()),
552            invalidation_sources: RefCell::new(Some(HashSet::default())),
553        }
554    }
555
556    fn id(&self) -> ScopeId {
557        std::ptr::from_ref(self).addr()
558    }
559}
560
561impl Drop for RecomposeScopeInner {
562    fn drop(&mut self) {
563        let id = self.id();
564        self.runtime.decrement_live_recompose_scope_count();
565        let subscriptions = std::mem::take(self.state_subscriptions.get_mut());
566        for state_id in subscriptions {
567            self.runtime.unregister_state_scope(state_id, id);
568        }
569        #[cfg(debug_assertions)]
570        {
571            let _ = DEBUG_SCOPE_LABELS.try_with(|labels| {
572                labels.borrow_mut().remove(&id);
573            });
574            let _ = DEBUG_SCOPE_INVALIDATION_SOURCES.try_with(|sources| {
575                sources.borrow_mut().remove(&id);
576            });
577        }
578        if self.enqueued.replace(false) {
579            self.runtime.mark_scope_recomposed(id);
580        }
581    }
582}
583
584#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
585pub struct RecomposeScopeRegistryDebugStats {
586    pub len: usize,
587    pub capacity: usize,
588}
589
590#[derive(Clone)]
591pub struct RecomposeScope {
592    inner: Rc<RecomposeScopeInner>,
593}
594
595impl PartialEq for RecomposeScope {
596    fn eq(&self, other: &Self) -> bool {
597        Rc::ptr_eq(&self.inner, &other.inner)
598    }
599}
600
601impl Eq for RecomposeScope {}
602
603impl Hash for RecomposeScope {
604    fn hash<H: Hasher>(&self, state: &mut H) {
605        self.id().hash(state);
606    }
607}
608
609impl RecomposeScope {
610    fn new(runtime: RuntimeHandle) -> Self {
611        Self {
612            inner: Rc::new(RecomposeScopeInner::new(runtime)),
613        }
614    }
615
616    pub(crate) fn downgrade(&self) -> Weak<RecomposeScopeInner> {
617        Rc::downgrade(&self.inner)
618    }
619
620    pub fn id(&self) -> ScopeId {
621        self.inner.id()
622    }
623
624    pub fn is_invalid(&self) -> bool {
625        self.inner.invalid.get()
626    }
627
628    pub fn is_active(&self) -> bool {
629        self.inner.active.get()
630    }
631
632    /// Total deactivations along this scope's owner chain. A retained slot
633    /// composition records this at compose time; a later mismatch means some
634    /// enclosing composition was deactivated (its owned effects cancelled)
635    /// since the slot last composed, so the retained content must recompose
636    /// once to restart them — no flag on the slot's own scopes carries that
637    /// trace, because deactivation walks stop at slot-host boundaries.
638    pub fn owner_chain_deactivation_epoch(&self) -> u64 {
639        let mut total = 0u64;
640        let mut current = Some(self.clone());
641        while let Some(scope) = current {
642            total = total.wrapping_add(scope.inner.deactivations.get());
643            let structural_parent = scope.inner.parent_scope.borrow().clone();
644            let lifetime_owner = scope.inner.lifetime_owner_scope.borrow().clone();
645            let next = structural_parent.or(lifetime_owner);
646            current = next
647                .and_then(|parent| parent.upgrade())
648                .map(|inner| RecomposeScope { inner });
649        }
650        total
651    }
652
653    pub(crate) fn is_effectively_active(&self) -> bool {
654        let mut current = Some(self.clone());
655        while let Some(scope) = current {
656            if !scope.is_active() {
657                return false;
658            }
659            let structural_parent = scope.inner.parent_scope.borrow().clone();
660            let lifetime_owner = scope.inner.lifetime_owner_scope.borrow().clone();
661            let next = structural_parent.or(lifetime_owner);
662            current = match next {
663                Some(parent) => {
664                    let Some(inner) = parent.upgrade() else {
665                        return false;
666                    };
667                    Some(RecomposeScope { inner })
668                }
669                None => None,
670            };
671        }
672        true
673    }
674
675    fn record_state_subscription(&self, state_id: StateId) {
676        self.inner.state_subscriptions.borrow_mut().insert(state_id);
677    }
678
679    fn record_unknown_invalidation_source(&self) {
680        *self.inner.invalidation_sources.borrow_mut() = None;
681    }
682
683    fn record_state_invalidation_source(&self, state_id: StateId) {
684        let mut sources = self.inner.invalidation_sources.borrow_mut();
685        if let Some(source_set) = sources.as_mut() {
686            source_set.insert(state_id);
687        }
688    }
689
690    fn enqueue_invalidation(&self) {
691        self.inner.invalid.set(true);
692        if !self.is_effectively_active() {
693            return;
694        }
695        if !self.inner.enqueued.replace(true) {
696            self.inner
697                .runtime
698                .register_invalid_scope(self.id(), self.downgrade());
699        }
700    }
701
702    fn invalidate(&self) {
703        self.record_unknown_invalidation_source();
704        self.enqueue_invalidation();
705    }
706
707    pub(crate) fn invalidate_from_state(&self, state_id: StateId) {
708        self.record_state_invalidation_source(state_id);
709        self.enqueue_invalidation();
710    }
711
712    fn mark_recomposed(&self) {
713        self.inner.invalid.set(false);
714        self.inner.force_reuse.set(false);
715        self.inner.force_recompose.set(false);
716        self.inner
717            .invalidation_sources
718            .borrow_mut()
719            .replace(HashSet::default());
720        if self.inner.enqueued.replace(false) {
721            self.inner.runtime.mark_scope_recomposed(self.id());
722        }
723        let pending = self.inner.pending_recompose.replace(false);
724        if pending {
725            if self.inner.active.get() {
726                self.invalidate();
727            } else {
728                self.inner.invalid.set(true);
729            }
730        }
731    }
732
733    fn set_recompose(&self, callback: Box<dyn FnMut(&Composer) + 'static>) {
734        *self.inner.recompose.borrow_mut() = Some(RecomposeCallback::Dynamic(callback));
735    }
736
737    fn set_recompose_fn(&self, callback: fn(&Composer)) {
738        *self.inner.recompose.borrow_mut() = Some(RecomposeCallback::Static(callback));
739    }
740
741    fn run_recompose(&self, composer: &Composer) -> bool {
742        let callback = self.inner.recompose.borrow_mut().take();
743        if let Some(callback) = callback {
744            let callback = match callback {
745                RecomposeCallback::Static(callback) => {
746                    callback(composer);
747                    RecomposeCallback::Static(callback)
748                }
749                RecomposeCallback::Dynamic(mut callback) => {
750                    callback(composer);
751                    RecomposeCallback::Dynamic(callback)
752                }
753            };
754            let mut slot = self.inner.recompose.borrow_mut();
755            if slot.is_none() {
756                *slot = Some(callback);
757            }
758            true
759        } else {
760            false
761        }
762    }
763
764    fn has_recompose_callback(&self) -> bool {
765        self.inner.recompose.borrow().is_some()
766    }
767
768    fn snapshot_locals(&self, stack: LocalStackSnapshot) {
769        *self.inner.local_stack.borrow_mut() = stack;
770    }
771
772    fn local_stack(&self) -> LocalStackSnapshot {
773        self.inner.local_stack.borrow().clone()
774    }
775
776    fn set_parent_hint(&self, parent: Option<NodeId>) {
777        self.inner.parent_hint.set(parent);
778    }
779
780    fn set_parent_scope(&self, parent: Option<RecomposeScope>) {
781        *self.inner.parent_scope.borrow_mut() = parent.map(|scope| scope.downgrade());
782    }
783
784    fn parent_scope(&self) -> Option<RecomposeScope> {
785        self.inner
786            .parent_scope
787            .borrow()
788            .as_ref()
789            .and_then(Weak::upgrade)
790            .map(|inner| RecomposeScope { inner })
791    }
792
793    fn set_lifetime_owner_scope(&self, owner: Option<RecomposeScope>) {
794        *self.inner.lifetime_owner_scope.borrow_mut() = owner.map(|scope| scope.downgrade());
795    }
796
797    #[cfg(test)]
798    fn lifetime_owner_scope(&self) -> Option<RecomposeScope> {
799        self.inner
800            .lifetime_owner_scope
801            .borrow()
802            .as_ref()
803            .and_then(Weak::upgrade)
804            .map(|inner| RecomposeScope { inner })
805    }
806
807    fn callback_promotion_target(&self) -> Option<RecomposeScope> {
808        let mut current = self.parent_scope();
809        while let Some(scope) = current {
810            if scope.has_recompose_callback() {
811                return Some(scope);
812            }
813            current = scope.parent_scope();
814        }
815        None
816    }
817
818    fn parent_hint(&self) -> Option<NodeId> {
819        self.inner.parent_hint.get()
820    }
821
822    fn set_slots_host(&self, host: &Rc<SlotsHost>) {
823        self.inner.slots_storage_key.set(host.storage_key());
824        *self.inner.slots_runtime_state.borrow_mut() =
825            host.runtime_state().map(|state| Rc::downgrade(&state));
826    }
827
828    pub(crate) fn slots_storage_key(&self) -> Option<usize> {
829        let key = self.inner.slots_storage_key.get();
830        (key != 0).then_some(key)
831    }
832
833    pub(crate) fn slots_runtime_state(&self) -> Option<Rc<crate::composer::ComposerRuntimeState>> {
834        self.inner
835            .slots_runtime_state
836            .borrow()
837            .as_ref()
838            .and_then(std::rc::Weak::upgrade)
839    }
840
841    pub fn deactivate(&self) {
842        if !self.inner.active.replace(false) {
843            return;
844        }
845        self.inner
846            .deactivations
847            .set(self.inner.deactivations.get() + 1);
848        if self.inner.enqueued.replace(false) {
849            self.inner.runtime.mark_scope_recomposed(self.id());
850        }
851    }
852
853    pub(crate) fn defer_until_reactivated(&self) {
854        if self.inner.enqueued.replace(false) {
855            self.inner.runtime.mark_scope_recomposed(self.id());
856        }
857    }
858
859    pub fn reactivate(&self) {
860        self.inner.active.set(true);
861        if self.inner.invalid.get()
862            && self.is_effectively_active()
863            && !self.inner.enqueued.replace(true)
864        {
865            self.inner
866                .runtime
867                .register_invalid_scope(self.id(), self.downgrade());
868        }
869    }
870
871    pub fn force_reuse(&self) {
872        self.inner.force_reuse.set(true);
873        self.inner.force_recompose.set(false);
874        self.inner.pending_recompose.set(true);
875    }
876
877    pub(crate) fn request_pending_recompose(&self) {
878        self.inner.pending_recompose.set(true);
879    }
880
881    pub fn force_recompose(&self) {
882        self.inner.force_recompose.set(true);
883        self.inner.force_reuse.set(false);
884        self.inner.pending_recompose.set(false);
885    }
886
887    pub(crate) fn set_retention_mode(&self, mode: RetentionMode) {
888        self.inner.retention_mode.set(mode);
889    }
890
891    pub(crate) fn retention_mode(&self) -> RetentionMode {
892        self.inner.retention_mode.get()
893    }
894
895    pub fn should_recompose(&self) -> bool {
896        if self.inner.force_recompose.replace(false) {
897            self.inner.force_reuse.set(false);
898            return true;
899        }
900        if self.inner.force_reuse.replace(false) {
901            return false;
902        }
903        self.is_invalid()
904    }
905
906    pub fn has_composed_once(&self) -> bool {
907        self.inner.composed_once.get()
908    }
909
910    fn mark_composed_once(&self) {
911        self.inner.composed_once.set(true);
912    }
913
914    fn invalidated_only_by(&self, allowed_sources: &HashSet<StateId>) -> Option<bool> {
915        let sources = self.inner.invalidation_sources.borrow();
916        let sources = sources.as_ref()?;
917        if sources.is_empty() {
918            return None;
919        }
920        Some(
921            sources
922                .iter()
923                .all(|source| allowed_sources.contains(source)),
924        )
925    }
926
927    fn has_unknown_invalidation_source(&self) -> bool {
928        self.inner.invalidation_sources.borrow().is_none()
929    }
930}
931
932#[cfg(test)]
933impl RecomposeScope {
934    pub(crate) fn new_for_test(runtime: RuntimeHandle) -> Self {
935        Self::new(runtime)
936    }
937}
938
939#[derive(Debug, Clone, Copy, Default)]
940pub struct RecomposeOptions {
941    pub force_reuse: bool,
942    pub force_recompose: bool,
943    pub retention: RetentionMode,
944}
945
946#[derive(Debug, Clone, PartialEq, Eq)]
947pub enum NodeError {
948    Missing {
949        id: NodeId,
950    },
951    TypeMismatch {
952        id: NodeId,
953        expected: &'static str,
954    },
955    MissingContext {
956        id: NodeId,
957        reason: &'static str,
958    },
959    AlreadyExists {
960        id: NodeId,
961    },
962    MalformedCommandPayload {
963        tag: &'static str,
964    },
965    SlotHostUnavailable {
966        operation: &'static str,
967        reason: &'static str,
968    },
969    RecompositionLimitExceeded {
970        operation: &'static str,
971        limit: usize,
972    },
973}
974
975impl std::fmt::Display for NodeError {
976    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
977        match self {
978            NodeError::Missing { id } => write!(f, "node {id} missing"),
979            NodeError::TypeMismatch { id, expected } => {
980                write!(f, "node {id} type mismatch; expected {expected}")
981            }
982            NodeError::MissingContext { id, reason } => {
983                write!(f, "missing context for node {id}: {reason}")
984            }
985            NodeError::AlreadyExists { id } => {
986                write!(f, "node {id} already exists")
987            }
988            NodeError::MalformedCommandPayload { tag } => {
989                write!(f, "command queue missing or invalid {tag} payload")
990            }
991            NodeError::SlotHostUnavailable { operation, reason } => {
992                write!(f, "{operation} cannot access slot host: {reason}")
993            }
994            NodeError::RecompositionLimitExceeded { operation, limit } => {
995                write!(
996                    f,
997                    "{operation} exceeded {limit} iterations while reconciling composition"
998                )
999            }
1000        }
1001    }
1002}
1003
1004impl std::error::Error for NodeError {}
1005
1006pub use subcompose::{
1007    ContentTypeReusePolicy, DefaultSlotReusePolicy, SlotId, SlotReusePolicy, SubcomposeState,
1008};
1009
1010#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1011pub enum Phase {
1012    Compose,
1013    Measure,
1014    Layout,
1015}
1016
1017pub use composer_context::{note_nested_slots_host, with_composer as with_current_composer};
1018
1019#[allow(non_snake_case)]
1020pub fn withCurrentComposer<R>(f: impl FnOnce(&Composer) -> R) -> R {
1021    composer_context::with_composer(f)
1022}
1023
1024fn with_current_composer_opt<R>(f: impl FnOnce(&Composer) -> R) -> Option<R> {
1025    composer_context::try_with_composer(f)
1026}
1027
1028#[doc(hidden)]
1029pub fn current_recompose_scope_invalidated_only_by(
1030    allowed_sources: impl IntoIterator<Item = StateId>,
1031) -> Option<bool> {
1032    with_current_composer_opt(|composer| {
1033        let allowed_sources = allowed_sources.into_iter().collect();
1034        let mut scope = composer.current_recompose_scope();
1035        let mut saw_unknown_source = false;
1036        while let Some(current) = scope {
1037            if current.has_unknown_invalidation_source() {
1038                saw_unknown_source = true;
1039                scope = current.parent_scope();
1040                continue;
1041            }
1042            if let Some(matches) = current.invalidated_only_by(&allowed_sources) {
1043                return Some(matches);
1044            }
1045            scope = current.parent_scope();
1046        }
1047        saw_unknown_source.then_some(false)
1048    })
1049    .flatten()
1050}
1051
1052fn key_scoped<K: Hash, R>(
1053    key: &K,
1054    caller: &'static std::panic::Location<'static>,
1055    content: impl FnOnce() -> R,
1056) -> R {
1057    let seed = explicit_group_key_seed(key, caller);
1058    with_current_composer(|composer| composer.with_group_seed(seed, |_| content()))
1059}
1060
1061#[track_caller]
1062pub fn with_key<K: Hash>(key: &K, content: impl FnOnce()) {
1063    key_scoped(key, std::panic::Location::caller(), content);
1064}
1065
1066/// Scopes composition identity to `keys` for the duration of `content`.
1067///
1068/// Mirrors Jetpack Compose's `key(vararg keys) { content }`. A call keeps its
1069/// identity by call-site position alone by default, so a slot survives a
1070/// recomposition even when what a caller passes in changes; wrapping the
1071/// call in `key(keys, || ...)` folds `keys` into that identity instead, so
1072/// changing `keys` discards the previous state and starts fresh, and two
1073/// `key` calls at the same call site with different `keys` never share
1074/// state. Pass a tuple to key on more than one value, e.g.
1075/// `key((a, b), || ...)`.
1076#[track_caller]
1077pub fn key<K: Hash, R>(keys: K, content: impl FnOnce() -> R) -> R {
1078    key_scoped(&keys, std::panic::Location::caller(), content)
1079}
1080
1081/// Composes `content` under an identity that is `key` alone, the same at
1082/// every call site, so the subtree can be emitted from any parent and keep
1083/// its remembered values, its running effects and its nodes.
1084///
1085/// Move content by emitting it under a different parent, in the same pass
1086/// or a later one: when the old parent stops emitting it, the subtree is
1087/// retained under `key`; when a parent emits it, the retained subtree is
1088/// taken back. A site that asks for content still attached elsewhere
1089/// composes nothing and is recomposed once the content is retained, so the
1090/// order in which the two parents recompose does not matter.
1091///
1092/// Content is shown at most once. Two live sites with the same key leave
1093/// the later one empty. Retained content is kept
1094/// until a parent takes it back or [`forget_movable`] releases it, so an
1095/// item the app closes for good must be forgotten or its state stays in
1096/// memory. A subtree may cross into and out of a `SubcomposeLayout` slot,
1097/// whose content lives in a slot table of its own: the table that held it
1098/// gives up its anchors and the one taking it over issues new ones.
1099#[track_caller]
1100pub fn movable<K: Hash>(key: K, content: impl FnOnce()) {
1101    let id = hash_key(&key);
1102    with_current_composer(|composer| composer.with_movable_group(id, |_| content()));
1103}
1104
1105/// Content written once that keeps its identity wherever it is shown.
1106///
1107/// [`movable`] names content by a key, which means writing the content out
1108/// at every parent that might show it and trusting the keys to match. When
1109/// the parents are alternatives -- a pane docked in a stack or pulled out
1110/// into a window of its own, a tab in a strip or torn into its own window --
1111/// that is the same body written twice, and two bodies that must be kept in
1112/// step by hand are two bodies that drift.
1113///
1114/// This hands back the content as a value instead. Write the body once,
1115/// remember it, and call [`MovableContent::show`] from whichever parent is
1116/// showing it this pass:
1117///
1118/// ```ignore
1119/// let pane = rememberMovableContentOf(move || PaneBody(state));
1120/// if docked {
1121///     Box(Modifier::empty().offset(0.0, y), BoxSpec::default(), || pane.show());
1122/// } else {
1123///     Box(Modifier::empty().window(config), BoxSpec::default(), || pane.show());
1124/// }
1125/// ```
1126///
1127/// The identity comes from the `remember`, so two of these at one call site
1128/// -- one per row of a list -- are two pieces of content, and the same one
1129/// survives recomposition. Everything [`movable`] says about ordering,
1130/// showing content at most once, and releasing it still holds; release this
1131/// one with [`MovableContent::forget`].
1132///
1133/// Content that has to be recognised from somewhere this value cannot reach
1134/// -- another composable that shows the same pane in another arrangement --
1135/// wants [`movableContentOf`] instead, which takes the identity as a key.
1136///
1137/// Mirrors Jetpack Compose's `movableContentOf`.
1138#[allow(non_snake_case)]
1139#[track_caller]
1140pub fn rememberMovableContentOf(content: impl Fn() + 'static) -> MovableContent {
1141    let runtime = with_current_composer(composer::Composer::runtime_handle);
1142    let id = remember(|| runtime.next_movable_content_id()).with(|id| *id);
1143    MovableContent {
1144        id,
1145        content: Rc::new(content),
1146    }
1147}
1148
1149/// Movable content whose identity is `key`, the same at every call site.
1150///
1151/// The keyed twin of [`rememberMovableContentOf`], and the same identity
1152/// [`movable`] uses: content shown by this value and content shown by
1153/// `movable` under the same key is one piece of content. Reach for this when
1154/// the parents that can show it are in different composables, so no single
1155/// value can be handed to all of them.
1156#[allow(non_snake_case)]
1157pub fn movableContentOf<K: Hash>(key: K, content: impl Fn() + 'static) -> MovableContent {
1158    MovableContent {
1159        id: hash_key(&key),
1160        content: Rc::new(content),
1161    }
1162}
1163
1164/// Movable content held as a value. See [`rememberMovableContentOf`].
1165#[derive(Clone)]
1166pub struct MovableContent {
1167    id: Key,
1168    content: Rc<dyn Fn()>,
1169}
1170
1171impl MovableContent {
1172    /// Shows the content here. Calling this from a different parent than
1173    /// last pass moves the content, with its remembered values, its running
1174    /// effects and its nodes.
1175    pub fn show(&self) {
1176        let content = Rc::clone(&self.content);
1177        let id = self.id;
1178        with_current_composer(|composer| composer.with_movable_group(id, |_| content()));
1179    }
1180
1181    /// Releases the content's state once no parent is showing it, for
1182    /// content the application has closed for good. See [`forget_movable`].
1183    pub fn forget(&self) {
1184        forget_movable_id(self.id);
1185    }
1186}
1187
1188impl std::fmt::Debug for MovableContent {
1189    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1190        f.debug_struct("MovableContent")
1191            .field("id", &self.id)
1192            .finish()
1193    }
1194}
1195
1196impl PartialEq for MovableContent {
1197    fn eq(&self, other: &Self) -> bool {
1198        self.id == other.id && Rc::ptr_eq(&self.content, &other.content)
1199    }
1200}
1201
1202/// Releases the state of [`movable`] content with identity `key` that no
1203/// parent is showing. Call it when the item is closed for good, from an
1204/// event handler or inside composition. Content a parent is still showing
1205/// is unaffected. Needs a runtime: an active composition or one created on
1206/// this thread.
1207pub fn forget_movable<K: Hash>(key: K) {
1208    let id = hash_key(&key);
1209    forget_movable_id(id);
1210}
1211
1212fn forget_movable_id(id: Key) {
1213    let runtime = composer_context::try_with_composer(composer::Composer::runtime_handle)
1214        .or_else(runtime::current_runtime_handle);
1215    match runtime {
1216        Some(runtime) => runtime.forget_movable(id),
1217        None => log::error!("forget_movable called without an active runtime"),
1218    }
1219}
1220
1221#[derive(Default)]
1222struct DisposableEffectState {
1223    key: Option<effect_key::EffectKey>,
1224    cleanup: Option<Box<dyn FnOnce()>>,
1225}
1226
1227impl DisposableEffectState {
1228    fn should_run(&self, key: &effect_key::EffectKey) -> bool {
1229        match &self.key {
1230            Some(current) => key.differs_from(current),
1231            None => true,
1232        }
1233    }
1234
1235    fn set_key(&mut self, key: effect_key::EffectKey) {
1236        self.key = Some(key);
1237    }
1238
1239    fn set_cleanup(&mut self, cleanup: Option<Box<dyn FnOnce()>>) {
1240        self.cleanup = cleanup;
1241    }
1242
1243    fn run_cleanup(&mut self) {
1244        if let Some(cleanup) = self.cleanup.take() {
1245            cleanup();
1246        }
1247    }
1248}
1249
1250impl Drop for DisposableEffectState {
1251    fn drop(&mut self) {
1252        self.run_cleanup();
1253    }
1254}
1255
1256#[derive(Clone, Copy, Debug, Default)]
1257pub struct DisposableEffectScope;
1258
1259#[derive(Default)]
1260pub struct DisposableEffectResult {
1261    cleanup: Option<Box<dyn FnOnce()>>,
1262}
1263
1264impl DisposableEffectScope {
1265    pub fn on_dispose(&self, cleanup: impl FnOnce() + 'static) -> DisposableEffectResult {
1266        DisposableEffectResult::new(cleanup)
1267    }
1268}
1269
1270impl DisposableEffectResult {
1271    pub fn new(cleanup: impl FnOnce() + 'static) -> Self {
1272        Self {
1273            cleanup: Some(Box::new(cleanup)),
1274        }
1275    }
1276
1277    fn into_cleanup(self) -> Option<Box<dyn FnOnce()>> {
1278        self.cleanup
1279    }
1280}
1281
1282#[allow(non_snake_case)]
1283pub fn SideEffect(effect: impl FnOnce() + 'static) {
1284    with_current_composer(|composer| composer.register_side_effect(effect));
1285}
1286
1287pub fn __disposable_effect_impl<K, F>(group_key: Key, keys: K, effect: F)
1288where
1289    K: PartialEq + 'static,
1290    F: FnOnce(DisposableEffectScope) -> DisposableEffectResult + 'static,
1291{
1292    with_current_composer(|composer| {
1293        composer.with_group(group_key, |composer| {
1294            let key = effect_key::EffectKey::new(keys);
1295            let state = composer.remember_effect::<DisposableEffectState>();
1296            if state.with(|state| state.should_run(&key)) {
1297                state.update(|state| {
1298                    state.run_cleanup();
1299                    state.set_key(key);
1300                });
1301                let mut effect_opt = Some(effect);
1302                composer.register_side_effect(move || {
1303                    if let Some(effect) = effect_opt.take() {
1304                        let result = effect(DisposableEffectScope);
1305                        state.update(|state| state.set_cleanup(result.into_cleanup()));
1306                    }
1307                });
1308            }
1309        });
1310    });
1311}
1312
1313/// Runs `effect` when this call site first enters composition, and again
1314/// whenever `keys` no longer equals the value it ran with last time; the
1315/// previous run's [`DisposableEffectScope::on_dispose`] cleanup, if any,
1316/// runs first, and also when the call site leaves composition entirely.
1317///
1318/// `keys` may be a tuple to depend on more than one value, matching Jetpack
1319/// Compose's `DisposableEffect(vararg keys)`.
1320#[allow(non_snake_case)]
1321#[track_caller]
1322pub fn DisposableEffect<K, F>(keys: K, effect: F)
1323where
1324    K: PartialEq + 'static,
1325    F: FnOnce(DisposableEffectScope) -> DisposableEffectResult + 'static,
1326{
1327    __disposable_effect_impl(crate::caller_location_key(), keys, effect);
1328}
1329
1330#[macro_export]
1331macro_rules! clone_captures {
1332    ($($alias:ident $(= $value:expr)?),+ $(,)?; $body:expr) => {{
1333        $(let $alias = $crate::clone_captures!(@clone $alias $(= $value)?);)+
1334        $body
1335    }};
1336    (@clone $alias:ident = $value:expr) => {
1337        ($value).clone()
1338    };
1339    (@clone $alias:ident) => {
1340        $alias.clone()
1341    };
1342}
1343
1344pub fn with_node_mut<N: Node + 'static, R>(
1345    id: NodeId,
1346    f: impl FnOnce(&mut N) -> R,
1347) -> Result<R, NodeError> {
1348    with_current_composer(|composer| composer.with_node_mut(id, f))
1349}
1350
1351pub fn push_parent(id: NodeId) {
1352    with_current_composer(|composer| composer.push_parent(id));
1353}
1354
1355pub fn pop_parent() {
1356    with_current_composer(composer::Composer::pop_parent);
1357}
1358
1359pub trait Node: Any {
1360    fn mount(&mut self) {}
1361    fn update(&mut self) {}
1362    fn unmount(&mut self) {}
1363    /// Adds `child` to this node's child list, returning whether the list
1364    /// actually changed. A node that already holds the child returns `false`:
1365    /// callers record a structural change from this answer, and a structural
1366    /// change re-lowers the whole subtree, so claiming one for a no-op costs a
1367    /// full rebuild per call.
1368    fn insert_child(&mut self, _child: NodeId) -> bool {
1369        false
1370    }
1371    /// Removes `child` from this node's child list, returning whether the list
1372    /// actually changed. Only this node can answer that: a caller inspecting
1373    /// the child's parent pointer gets it wrong when the child was reparented
1374    /// while still listed here.
1375    fn remove_child(&mut self, _child: NodeId) -> bool {
1376        false
1377    }
1378    fn move_child(&mut self, _from: usize, _to: usize) {}
1379    fn update_children(&mut self, _children: &[NodeId]) {}
1380    fn children(&self) -> Vec<NodeId> {
1381        Vec::new()
1382    }
1383    /// Copies child IDs into the provided scratch buffer without allocating a
1384    /// fresh container for every traversal.
1385    fn collect_children_into(&self, out: &mut SmallVec<[NodeId; 8]>) {
1386        out.clear();
1387        out.extend(self.children());
1388    }
1389    fn collect_owned_children_into(&self, out: &mut SmallVec<[NodeId; 8]>) {
1390        self.collect_children_into(out);
1391    }
1392    /// Called after the node is created to record its own ID.
1393    /// Useful for nodes that need to store their ID for later operations.
1394    fn set_node_id(&mut self, _id: NodeId) {}
1395    /// Called when this node is attached to a parent.
1396    /// Nodes with parent tracking should set their parent reference here.
1397    fn on_attached_to_parent(&mut self, _parent: NodeId) {}
1398    /// Called when this node is removed from its parent.
1399    /// Nodes with parent tracking should clear their parent reference here.
1400    fn on_removed_from_parent(&mut self) {}
1401    /// Get this node's parent ID (for nodes that track parents).
1402    /// Returns None if node has no parent or doesn't track parents.
1403    fn parent(&self) -> Option<NodeId> {
1404        None
1405    }
1406    /// Mark this node as needing layout (for nodes with dirty flags).
1407    /// Called during bubbling to propagate dirtiness up the tree.
1408    fn mark_needs_layout(&self) {}
1409    /// Check if this node needs layout (for nodes with dirty flags).
1410    fn needs_layout(&self) -> bool {
1411        false
1412    }
1413    /// Mark this node as needing measure (size may have changed).
1414    /// Called during bubbling when children are added/removed.
1415    fn mark_needs_measure(&self) {}
1416    /// Check if this node needs measure (for nodes with dirty flags).
1417    fn needs_measure(&self) -> bool {
1418        false
1419    }
1420    /// Mark this node as needing semantics recomputation.
1421    fn mark_needs_semantics(&self) {}
1422    /// Check if this node needs semantics recomputation.
1423    fn needs_semantics(&self) -> bool {
1424        false
1425    }
1426    /// Set parent reference for dirty flag bubbling ONLY.
1427    /// This is a minimal version of on_attached_to_parent that doesn't trigger
1428    /// registry updates or other side effects. Used during measurement when we
1429    /// need to establish parent connections for bubble_measure_dirty without
1430    /// causing the full attachment lifecycle.
1431    ///
1432    /// An existing parent is preserved until the structural attach operation
1433    /// removes the node from its previous container.
1434    fn set_parent_for_bubbling(&mut self, parent: NodeId) {
1435        if self.parent().is_none() {
1436            self.on_attached_to_parent(parent);
1437        }
1438    }
1439
1440    /// Returns a recycle pool key when this node supports shell reuse.
1441    fn recycle_key(&self) -> Option<TypeId> {
1442        None
1443    }
1444
1445    /// Bounds how many recyclable shells of this node type should be retained.
1446    fn recycle_pool_limit(&self) -> Option<usize> {
1447        None
1448    }
1449
1450    /// Clears live attachments before the node shell enters a recycle pool.
1451    fn prepare_for_recycle(&mut self) {}
1452
1453    /// Optionally provides a compact replacement box for this recycled shell.
1454    ///
1455    /// Returning `Some` lets nodes move pooled survivors onto fresh compact
1456    /// storage so the recycle pool does not pin large spike-era allocations.
1457    fn rehouse_for_recycle(&self) -> Option<Box<dyn Node>> {
1458        None
1459    }
1460
1461    /// Optionally moves a live node onto a fresh box during applier compaction.
1462    ///
1463    /// This is used after large-majority teardowns where a small surviving live
1464    /// tree can otherwise pin allocator pages from a much larger spike-era node
1465    /// population. Implementations must preserve the node's live state.
1466    fn rehouse_for_live_compaction(&mut self) -> Option<Box<dyn Node>> {
1467        None
1468    }
1469
1470    /// Returns the node-owned heap retained beyond the node's own box allocation.
1471    fn debug_heap_bytes(&self) -> usize {
1472        0
1473    }
1474}
1475
1476/// Unified API for bubbling layout dirty flags from a node to the root (Applier context).
1477///
1478/// This is the canonical function for dirty bubbling during the apply phase (structural changes).
1479/// Call this after mutations like insert/remove/move that happen during apply.
1480///
1481/// # Behavior
1482/// 1. Marks the starting node as needing layout
1483/// 2. Walks up the parent chain, marking each ancestor
1484/// 3. Stops when it reaches a node that's already dirty (O(1) optimization)
1485/// 4. Stops at the root (node with no parent)
1486///
1487/// # Performance
1488/// This function is O(height) in the worst case, but typically O(1) due to early exit
1489/// when encountering an already-dirty ancestor.
1490///
1491/// # Usage
1492/// - Call from composer mutations (insert/remove/move) during apply phase
1493/// - Call from applier-level operations that modify the tree structure
1494pub fn bubble_layout_dirty(applier: &mut dyn Applier, node_id: NodeId) {
1495    bubble_layout_dirty_applier(applier, node_id);
1496}
1497
1498/// Unified API for bubbling measure dirty flags from a node to the root (Applier context).
1499///
1500/// Call this when a node's size may have changed (children added/removed, modifier changed).
1501/// This ensures that measure_layout will increment the cache epoch and re-measure the subtree.
1502///
1503/// # Behavior
1504/// 1. Marks the starting node as needing measure
1505/// 2. Walks up the parent chain, marking each ancestor
1506/// 3. Stops when it reaches a node that's already dirty (O(1) optimization)
1507/// 4. Stops at the root (node with no parent)
1508pub fn bubble_measure_dirty(applier: &mut dyn Applier, node_id: NodeId) {
1509    bubble_measure_dirty_applier(applier, node_id);
1510}
1511
1512/// Unified API for bubbling semantics dirty flags from a node to the root (Applier context).
1513///
1514/// This mirrors [`bubble_layout_dirty`] but toggles semantics-specific dirty
1515/// flags instead of layout ones, allowing semantics updates to propagate during
1516/// the apply phase without forcing layout work.
1517pub fn bubble_semantics_dirty(applier: &mut dyn Applier, node_id: NodeId) {
1518    bubble_semantics_dirty_applier(applier, node_id);
1519}
1520
1521/// Schedules semantics bubbling for a node using the active composer if present.
1522///
1523/// This defers the work to the apply phase where we can safely mutate the
1524/// applier tree without re-entrantly borrowing the composer during composition.
1525pub fn queue_semantics_invalidation(node_id: NodeId) {
1526    let _ = composer_context::try_with_composer(|composer| {
1527        composer.enqueue_semantics_invalidation(node_id);
1528    });
1529}
1530
1531/// Unified API for bubbling layout dirty flags from a node to the root (Composer context).
1532///
1533/// This is the canonical function for dirty bubbling during composition (property changes).
1534/// Call this after property changes that happen during composition via with_node_mut.
1535///
1536/// # Behavior
1537/// 1. Marks the starting node as needing layout
1538/// 2. Walks up the parent chain, marking each ancestor
1539/// 3. Stops when it reaches a node that's already dirty (O(1) optimization)
1540/// 4. Stops at the root (node with no parent)
1541///
1542/// # Performance
1543/// This function is O(height) in the worst case, but typically O(1) due to early exit
1544/// when encountering an already-dirty ancestor.
1545///
1546/// # Type Requirements
1547/// The node type N must implement Node (which includes mark_needs_layout, parent, etc.).
1548/// Typically this will be LayoutNode or similar layout-aware node types.
1549///
1550/// # Usage
1551/// - Call from property setters during composition (e.g., set_modifier, set_measure_policy)
1552/// - Call from widget composition when layout-affecting state changes
1553pub fn bubble_layout_dirty_in_composer<N: Node + 'static>(node_id: NodeId) {
1554    bubble_layout_dirty_composer::<N>(node_id);
1555}
1556
1557/// Unified API for bubbling measure dirty flags from a node to the root during composition.
1558///
1559/// This queues a dirty-bubble command on the active composer so measure invalidation
1560/// runs during the apply phase, avoiding re-entrant applier borrows while widgets are
1561/// mutating nodes via `with_node_mut`.
1562pub fn bubble_measure_dirty_in_composer(node_id: NodeId) {
1563    with_current_composer(|composer| {
1564        composer.commands_mut().push(Command::BubbleDirty {
1565            node_id,
1566            bubble: DirtyBubble {
1567                layout: false,
1568                measure: true,
1569                semantics: false,
1570            },
1571        });
1572    });
1573}
1574
1575/// Unified API for bubbling semantics dirty flags from a node to the root (Composer context).
1576///
1577/// This mirrors [`bubble_layout_dirty_in_composer`] but routes through the semantics
1578/// dirty flag instead of the layout one. Modifier nodes can request semantics
1579/// invalidations without triggering measure/layout work, and the runtime can
1580/// query the root to determine whether the semantics tree needs rebuilding.
1581pub fn bubble_semantics_dirty_in_composer<N: Node + 'static>(node_id: NodeId) {
1582    bubble_semantics_dirty_composer::<N>(node_id);
1583}
1584
1585fn bubble_layout_dirty_applier(applier: &mut dyn Applier, mut node_id: NodeId) {
1586    if let Ok(node) = applier.get_mut(node_id) {
1587        node.mark_needs_layout();
1588    }
1589
1590    loop {
1591        let parent_id = match applier.get_mut(node_id) {
1592            Ok(node) => node.parent(),
1593            Err(_) => None,
1594        };
1595
1596        match parent_id {
1597            Some(pid) => {
1598                if let Ok(parent) = applier.get_mut(pid) {
1599                    let parent_already_dirty = parent.needs_layout();
1600                    if !parent_already_dirty {
1601                        parent.mark_needs_layout();
1602                    }
1603                    node_id = pid;
1604                } else {
1605                    break;
1606                }
1607            }
1608            None => break,
1609        }
1610    }
1611}
1612
1613fn bubble_measure_dirty_applier(applier: &mut dyn Applier, mut node_id: NodeId) {
1614    if let Ok(node) = applier.get_mut(node_id) {
1615        node.mark_needs_measure();
1616    }
1617
1618    loop {
1619        let parent_id = match applier.get_mut(node_id) {
1620            Ok(node) => node.parent(),
1621            Err(_) => None,
1622        };
1623
1624        match parent_id {
1625            Some(pid) => {
1626                if let Ok(parent) = applier.get_mut(pid) {
1627                    if !parent.needs_measure() {
1628                        parent.mark_needs_measure();
1629                    }
1630                    node_id = pid;
1631                } else {
1632                    break;
1633                }
1634            }
1635            None => {
1636                break;
1637            }
1638        }
1639    }
1640}
1641
1642fn bubble_semantics_dirty_applier(applier: &mut dyn Applier, mut node_id: NodeId) {
1643    if let Ok(node) = applier.get_mut(node_id) {
1644        node.mark_needs_semantics();
1645    }
1646
1647    loop {
1648        let parent_id = match applier.get_mut(node_id) {
1649            Ok(node) => node.parent(),
1650            Err(_) => None,
1651        };
1652
1653        match parent_id {
1654            Some(pid) => {
1655                if let Ok(parent) = applier.get_mut(pid) {
1656                    if !parent.needs_semantics() {
1657                        parent.mark_needs_semantics();
1658                    }
1659                    node_id = pid;
1660                } else {
1661                    break;
1662                }
1663            }
1664            None => break,
1665        }
1666    }
1667}
1668
1669fn bubble_layout_dirty_composer<N: Node + 'static>(mut node_id: NodeId) {
1670    let _ = with_node_mut(node_id, |node: &mut N| {
1671        node.mark_needs_layout();
1672    });
1673
1674    while let Ok(Some(pid)) = with_node_mut(node_id, |node: &mut N| node.parent()) {
1675        let parent_id = pid;
1676
1677        let advanced = with_node_mut(parent_id, |node: &mut N| {
1678            if !node.needs_layout() {
1679                node.mark_needs_layout();
1680            }
1681            true
1682        })
1683        .unwrap_or(false);
1684
1685        if advanced {
1686            node_id = parent_id;
1687        } else {
1688            break;
1689        }
1690    }
1691}
1692
1693fn bubble_semantics_dirty_composer<N: Node + 'static>(mut node_id: NodeId) {
1694    let _ = with_node_mut(node_id, |node: &mut N| {
1695        node.mark_needs_semantics();
1696    });
1697
1698    while let Ok(Some(pid)) = with_node_mut(node_id, |node: &mut N| node.parent()) {
1699        let parent_id = pid;
1700
1701        let advanced = with_node_mut(parent_id, |node: &mut N| {
1702            if !node.needs_semantics() {
1703                node.mark_needs_semantics();
1704            }
1705            true
1706        })
1707        .unwrap_or(false);
1708
1709        if advanced {
1710            node_id = parent_id;
1711        } else {
1712            break;
1713        }
1714    }
1715}
1716
1717impl dyn Node {
1718    pub fn as_any_mut(&mut self) -> &mut dyn Any {
1719        self
1720    }
1721}
1722
1723pub struct RecycledNode {
1724    stable_id: NodeId,
1725    node: Box<dyn Node>,
1726    warm_origin: bool,
1727}
1728
1729impl RecycledNode {
1730    fn new(stable_id: NodeId, node: Box<dyn Node>, warm_origin: bool) -> Self {
1731        let node = node.rehouse_for_recycle().unwrap_or(node);
1732        Self {
1733            stable_id,
1734            node,
1735            warm_origin,
1736        }
1737    }
1738
1739    fn from_shell(stable_id: NodeId, node: Box<dyn Node>, warm_origin: bool) -> Self {
1740        Self {
1741            stable_id,
1742            node,
1743            warm_origin,
1744        }
1745    }
1746
1747    pub fn stable_id(&self) -> NodeId {
1748        self.stable_id
1749    }
1750
1751    fn warm_origin(&self) -> bool {
1752        self.warm_origin
1753    }
1754
1755    fn set_warm_origin(&mut self, warm_origin: bool) {
1756        self.warm_origin = warm_origin;
1757    }
1758
1759    pub fn node_mut(&mut self) -> &mut dyn Node {
1760        self.node.as_mut()
1761    }
1762
1763    pub fn into_parts(self) -> (NodeId, Box<dyn Node>, bool) {
1764        (self.stable_id, self.node, self.warm_origin)
1765    }
1766}
1767
1768#[derive(Debug, Clone, PartialEq, Eq)]
1769pub struct RecycledNodeInsertion {
1770    pub id: NodeId,
1771    pub stable_id_reused: bool,
1772    pub fallback_error: Option<NodeError>,
1773}
1774
1775impl RecycledNodeInsertion {
1776    fn reused(stable_id: NodeId) -> Self {
1777        Self {
1778            id: stable_id,
1779            stable_id_reused: true,
1780            fallback_error: None,
1781        }
1782    }
1783
1784    fn fresh(id: NodeId, fallback_error: Option<NodeError>) -> Self {
1785        Self {
1786            id,
1787            stable_id_reused: false,
1788            fallback_error,
1789        }
1790    }
1791}
1792
1793pub trait Applier: Any {
1794    fn create(&mut self, node: Box<dyn Node>) -> NodeId;
1795    fn get_mut(&mut self, id: NodeId) -> Result<&mut dyn Node, NodeError>;
1796    fn remove(&mut self, id: NodeId) -> Result<(), NodeError>;
1797
1798    /// Records that `parent_id`'s child list changed structurally this frame
1799    /// (insert, remove, move, or reparent). Incremental scene consumers drain
1800    /// the recorded parents and re-patch those subtrees so removed nodes are
1801    /// evicted from a persistent render graph even when the frame's scene
1802    /// update is otherwise scoped to unrelated dirty nodes.
1803    fn record_structural_change(&mut self, _parent_id: NodeId) {}
1804
1805    /// Returns the current generation for a node index.
1806    /// Generation is incremented when an index is reused from the freelist,
1807    /// preventing stale slot entries from matching recycled nodes.
1808    fn node_generation(&self, id: NodeId) -> u32;
1809
1810    /// Inserts a node with a pre-assigned ID.
1811    ///
1812    /// This is used for virtual nodes whose IDs are allocated separately
1813    /// (e.g., via allocate_virtual_node_id()). Unlike `create()` which assigns
1814    /// a new ID, this method uses the provided ID.
1815    ///
1816    /// Returns Ok(()) if successful, or an error if the ID is already in use.
1817    fn insert_with_id(&mut self, id: NodeId, node: Box<dyn Node>) -> Result<(), NodeError>;
1818
1819    /// Reinserts a recycled node at its retained stable ID, or creates a fresh ID if that
1820    /// retained ID is no longer available.
1821    fn insert_recycled_node_or_create(
1822        &mut self,
1823        stable_id: NodeId,
1824        node: Box<dyn Node>,
1825    ) -> RecycledNodeInsertion {
1826        let id = self.create(node);
1827        RecycledNodeInsertion::fresh(id, Some(NodeError::AlreadyExists { id: stable_id }))
1828    }
1829
1830    fn as_any(&self) -> &dyn Any
1831    where
1832        Self: Sized,
1833    {
1834        self
1835    }
1836
1837    fn as_any_mut(&mut self) -> &mut dyn Any
1838    where
1839        Self: Sized,
1840    {
1841        self
1842    }
1843
1844    /// Trim trailing tombstones/unused capacity after structural changes.
1845    fn compact(&mut self) {}
1846
1847    /// Returns a previously recycled node shell and its stable ID for the requested concrete type.
1848    fn take_recycled_node(&mut self, _key: TypeId) -> Option<RecycledNode> {
1849        None
1850    }
1851
1852    /// Marks whether a reinserted recycled node originated from the warm recycle path.
1853    fn set_recycled_node_origin(&mut self, _id: NodeId, _warm_origin: bool) {}
1854
1855    /// Seeds a warm recyclable shell for future reuse without requiring a prior removal.
1856    fn seed_recycled_node_shell(
1857        &mut self,
1858        _key: TypeId,
1859        _recycle_pool_limit: Option<usize>,
1860        _shell: Box<dyn Node>,
1861    ) {
1862    }
1863
1864    /// Records that the current apply pass had to allocate a fresh recyclable shell for this type.
1865    fn record_fresh_recyclable_creation(&mut self, _key: TypeId) {}
1866
1867    /// Drops any recyclable shells that should not survive beyond the current apply pass.
1868    fn clear_recycled_nodes(&mut self) {}
1869}
1870
1871type TypedNodeUpdate = fn(&mut dyn Node, NodeId) -> Result<(), NodeError>;
1872type CommandCallback = Box<dyn FnOnce(&mut dyn Applier) -> Result<(), NodeError> + 'static>;
1873
1874#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1875pub(crate) struct DirtyBubble {
1876    layout: bool,
1877    measure: bool,
1878    semantics: bool,
1879}
1880
1881impl DirtyBubble {
1882    pub(crate) const LAYOUT_AND_MEASURE: Self = Self {
1883        layout: true,
1884        measure: true,
1885        semantics: false,
1886    };
1887
1888    pub(crate) const SEMANTICS: Self = Self {
1889        layout: false,
1890        measure: false,
1891        semantics: true,
1892    };
1893
1894    fn apply(self, applier: &mut dyn Applier, node_id: NodeId) {
1895        if self.layout {
1896            bubble_layout_dirty(applier, node_id);
1897        }
1898        if self.measure {
1899            bubble_measure_dirty(applier, node_id);
1900        }
1901        if self.semantics {
1902            bubble_semantics_dirty(applier, node_id);
1903        }
1904    }
1905}
1906
1907pub(crate) enum Command {
1908    BubbleDirty {
1909        node_id: NodeId,
1910        bubble: DirtyBubble,
1911    },
1912    UpdateTypedNode {
1913        id: NodeId,
1914        updater: TypedNodeUpdate,
1915    },
1916    RemoveNode {
1917        id: NodeId,
1918    },
1919    MountNode {
1920        id: NodeId,
1921    },
1922    AttachChild {
1923        parent_id: NodeId,
1924        child_id: NodeId,
1925        insert_index: Option<usize>,
1926        bubble: DirtyBubble,
1927    },
1928    InsertChild {
1929        parent_id: NodeId,
1930        child_id: NodeId,
1931        appended_index: usize,
1932        insert_index: usize,
1933        bubble: DirtyBubble,
1934    },
1935    MoveChild {
1936        parent_id: NodeId,
1937        from_index: usize,
1938        to_index: usize,
1939        bubble: DirtyBubble,
1940    },
1941    RemoveChild {
1942        parent_id: NodeId,
1943        child_id: NodeId,
1944    },
1945    DetachChild {
1946        parent_id: NodeId,
1947        child_id: NodeId,
1948    },
1949    SyncChildren {
1950        parent_id: NodeId,
1951        expected_children: ChildList,
1952    },
1953    Callback(CommandCallback),
1954}
1955
1956#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1957struct DeferredChildCleanup {
1958    child_id: NodeId,
1959    generation: u32,
1960    removed_from_parent: bool,
1961}
1962
1963#[derive(Default)]
1964struct DeferredChildCleanupQueue {
1965    pending: Vec<DeferredChildCleanup>,
1966    preserved: Vec<(NodeId, u32)>,
1967}
1968
1969impl DeferredChildCleanupQueue {
1970    fn push(&mut self, child_id: NodeId, generation: u32, removed_from_parent: bool) {
1971        if self
1972            .preserved
1973            .iter()
1974            .any(|&(preserved_id, preserved_generation)| {
1975                preserved_id == child_id && preserved_generation == generation
1976            })
1977        {
1978            return;
1979        }
1980        self.pending.push(DeferredChildCleanup {
1981            child_id,
1982            generation,
1983            removed_from_parent,
1984        });
1985    }
1986
1987    fn preserve(&mut self, child_id: NodeId, generation: u32) {
1988        if !self
1989            .preserved
1990            .iter()
1991            .any(|&(preserved_id, preserved_generation)| {
1992                preserved_id == child_id && preserved_generation == generation
1993            })
1994        {
1995            self.preserved.push((child_id, generation));
1996        }
1997        self.pending
1998            .retain(|cleanup| cleanup.child_id != child_id || cleanup.generation != generation);
1999    }
2000
2001    fn flush(self, applier: &mut dyn Applier) -> Result<(), NodeError> {
2002        for cleanup in self.pending {
2003            cleanup_detached_child(applier, cleanup)?;
2004        }
2005        Ok(())
2006    }
2007}
2008
2009impl Command {
2010    pub(crate) fn update_node<N: Node + 'static>(id: NodeId) -> Self {
2011        Self::UpdateTypedNode {
2012            id,
2013            updater: update_typed_node::<N>,
2014        }
2015    }
2016
2017    pub(crate) fn callback(
2018        callback: impl FnOnce(&mut dyn Applier) -> Result<(), NodeError> + 'static,
2019    ) -> Self {
2020        Self::Callback(Box::new(callback))
2021    }
2022
2023    pub(crate) fn apply(self, applier: &mut dyn Applier) -> Result<(), NodeError> {
2024        let mut deferred_cleanup = DeferredChildCleanupQueue::default();
2025        self.apply_with_cleanup(applier, &mut deferred_cleanup)?;
2026        deferred_cleanup.flush(applier)
2027    }
2028
2029    fn apply_with_cleanup(
2030        self,
2031        applier: &mut dyn Applier,
2032        deferred_cleanup: &mut DeferredChildCleanupQueue,
2033    ) -> Result<(), NodeError> {
2034        match self {
2035            Self::BubbleDirty { node_id, bubble } => {
2036                bubble.apply(applier, node_id);
2037                Ok(())
2038            }
2039            Self::UpdateTypedNode { id, updater } => {
2040                let node = match applier.get_mut(id) {
2041                    Ok(node) => node,
2042                    Err(NodeError::Missing { .. }) => return Ok(()),
2043                    Err(err) => return Err(err),
2044                };
2045                updater(node, id)
2046            }
2047            Self::RemoveNode { id } => {
2048                if let Ok(node) = applier.get_mut(id) {
2049                    node.unmount();
2050                }
2051                match applier.remove(id) {
2052                    Ok(()) | Err(NodeError::Missing { .. }) => Ok(()),
2053                    Err(err) => Err(err),
2054                }
2055            }
2056            Self::MountNode { id } => {
2057                let node = match applier.get_mut(id) {
2058                    Ok(node) => node,
2059                    Err(NodeError::Missing { .. }) => return Ok(()),
2060                    Err(err) => return Err(err),
2061                };
2062                node.set_node_id(id);
2063                node.mount();
2064                Ok(())
2065            }
2066            Self::AttachChild {
2067                parent_id,
2068                child_id,
2069                insert_index,
2070                bubble,
2071            } => {
2072                attach_child_at(applier, parent_id, child_id, insert_index, bubble);
2073                Ok(())
2074            }
2075            Self::InsertChild {
2076                parent_id,
2077                child_id,
2078                appended_index,
2079                insert_index,
2080                bubble,
2081            } => {
2082                insert_child_with_reparenting(applier, parent_id, child_id);
2083                bubble.apply(applier, parent_id);
2084                if insert_index != appended_index
2085                    && let Ok(parent_node) = applier.get_mut(parent_id)
2086                {
2087                    parent_node.move_child(appended_index, insert_index);
2088                }
2089                Ok(())
2090            }
2091            Self::MoveChild {
2092                parent_id,
2093                from_index,
2094                to_index,
2095                bubble,
2096            } => {
2097                if let Ok(parent_node) = applier.get_mut(parent_id) {
2098                    parent_node.move_child(from_index, to_index);
2099                }
2100                bubble.apply(applier, parent_id);
2101                note_structural_move(parent_id, from_index, to_index);
2102                applier.record_structural_change(parent_id);
2103                Ok(())
2104            }
2105            Self::RemoveChild {
2106                parent_id,
2107                child_id,
2108            } => apply_remove_child(applier, parent_id, child_id, deferred_cleanup),
2109            Self::DetachChild {
2110                parent_id,
2111                child_id,
2112            } => {
2113                let generation = applier.node_generation(child_id);
2114                detach_child_from_parent(applier, parent_id, child_id)?;
2115                deferred_cleanup.preserve(child_id, generation);
2116                Ok(())
2117            }
2118            Self::SyncChildren {
2119                parent_id,
2120                expected_children,
2121            } => sync_children(applier, parent_id, &expected_children, deferred_cleanup),
2122            Self::Callback(callback) => callback(applier),
2123        }
2124    }
2125}
2126
2127const COMMAND_CHUNK_CAPACITY: usize = 1024;
2128const COMMAND_FLUSH_THRESHOLD: usize = COMMAND_CHUNK_CAPACITY * 4;
2129type ChildList = SmallVec<[NodeId; 4]>;
2130const SMALL_CHILD_SYNC_LINEAR_THRESHOLD: usize = 8;
2131
2132#[derive(Copy, Clone)]
2133enum CommandTag {
2134    BubbleDirty,
2135    UpdateTypedNode,
2136    RemoveNode,
2137    MountNode,
2138    AttachChild,
2139    InsertChild,
2140    MoveChild,
2141    RemoveChild,
2142    DetachChild,
2143    SyncChildren,
2144    Callback,
2145}
2146
2147impl CommandTag {
2148    fn label(self) -> &'static str {
2149        match self {
2150            Self::BubbleDirty => "BubbleDirty",
2151            Self::UpdateTypedNode => "UpdateTypedNode",
2152            Self::RemoveNode => "RemoveNode",
2153            Self::MountNode => "MountNode",
2154            Self::AttachChild => "AttachChild",
2155            Self::InsertChild => "InsertChild",
2156            Self::MoveChild => "MoveChild",
2157            Self::RemoveChild => "RemoveChild",
2158            Self::DetachChild => "DetachChild",
2159            Self::SyncChildren => "SyncChildren",
2160            Self::Callback => "Callback",
2161        }
2162    }
2163}
2164
2165#[derive(Copy, Clone)]
2166struct BubbleDirtyCommand {
2167    node_id: NodeId,
2168    bubble: DirtyBubble,
2169}
2170
2171#[derive(Copy, Clone)]
2172struct UpdateTypedNodeCommand {
2173    id: NodeId,
2174    updater: TypedNodeUpdate,
2175}
2176
2177#[derive(Copy, Clone)]
2178struct AttachChildCommand {
2179    parent_id: NodeId,
2180    child_id: NodeId,
2181    insert_index: Option<usize>,
2182    bubble: DirtyBubble,
2183}
2184
2185#[derive(Copy, Clone)]
2186struct InsertChildCommand {
2187    parent_id: NodeId,
2188    child_id: NodeId,
2189    appended_index: usize,
2190    insert_index: usize,
2191    bubble: DirtyBubble,
2192}
2193
2194#[derive(Copy, Clone)]
2195struct MoveChildCommand {
2196    parent_id: NodeId,
2197    from_index: usize,
2198    to_index: usize,
2199    bubble: DirtyBubble,
2200}
2201
2202#[derive(Copy, Clone)]
2203struct RemoveChildCommand {
2204    parent_id: NodeId,
2205    child_id: NodeId,
2206}
2207
2208#[derive(Copy, Clone)]
2209struct DetachChildCommand {
2210    parent_id: NodeId,
2211    child_id: NodeId,
2212}
2213
2214struct SyncChildrenCommand {
2215    parent_id: NodeId,
2216    child_start: usize,
2217    child_len: usize,
2218}
2219
2220#[derive(Default)]
2221struct CommandQueue {
2222    chunks: Vec<Vec<CommandTag>>,
2223    len: usize,
2224    bubble_dirty: Vec<BubbleDirtyCommand>,
2225    update_typed_nodes: Vec<UpdateTypedNodeCommand>,
2226    remove_nodes: Vec<NodeId>,
2227    mount_nodes: Vec<NodeId>,
2228    attach_children: Vec<AttachChildCommand>,
2229    insert_children: Vec<InsertChildCommand>,
2230    move_children: Vec<MoveChildCommand>,
2231    remove_children: Vec<RemoveChildCommand>,
2232    detach_children: Vec<DetachChildCommand>,
2233    sync_children: Vec<SyncChildrenCommand>,
2234    sync_child_ids: Vec<NodeId>,
2235    callbacks: Vec<CommandCallback>,
2236}
2237
2238impl CommandQueue {
2239    fn push_tag(&mut self, tag: CommandTag) {
2240        let needs_chunk = self
2241            .chunks
2242            .last()
2243            .is_none_or(|chunk| chunk.len() == chunk.capacity());
2244        if needs_chunk {
2245            self.chunks.push(Vec::with_capacity(COMMAND_CHUNK_CAPACITY));
2246        }
2247        if let Some(chunk) = self.chunks.last_mut() {
2248            chunk.push(tag);
2249            self.len += 1;
2250        }
2251    }
2252
2253    fn push(&mut self, command: Command) {
2254        match command {
2255            Command::BubbleDirty { node_id, bubble } => {
2256                self.bubble_dirty
2257                    .push(BubbleDirtyCommand { node_id, bubble });
2258                self.push_tag(CommandTag::BubbleDirty);
2259            }
2260            Command::UpdateTypedNode { id, updater } => {
2261                self.update_typed_nodes
2262                    .push(UpdateTypedNodeCommand { id, updater });
2263                self.push_tag(CommandTag::UpdateTypedNode);
2264            }
2265            Command::RemoveNode { id } => {
2266                self.remove_nodes.push(id);
2267                self.push_tag(CommandTag::RemoveNode);
2268            }
2269            Command::MountNode { id } => {
2270                self.mount_nodes.push(id);
2271                self.push_tag(CommandTag::MountNode);
2272            }
2273            Command::AttachChild {
2274                parent_id,
2275                child_id,
2276                insert_index,
2277                bubble,
2278            } => {
2279                self.attach_children.push(AttachChildCommand {
2280                    parent_id,
2281                    child_id,
2282                    insert_index,
2283                    bubble,
2284                });
2285                self.push_tag(CommandTag::AttachChild);
2286            }
2287            Command::InsertChild {
2288                parent_id,
2289                child_id,
2290                appended_index,
2291                insert_index,
2292                bubble,
2293            } => {
2294                self.insert_children.push(InsertChildCommand {
2295                    parent_id,
2296                    child_id,
2297                    appended_index,
2298                    insert_index,
2299                    bubble,
2300                });
2301                self.push_tag(CommandTag::InsertChild);
2302            }
2303            Command::MoveChild {
2304                parent_id,
2305                from_index,
2306                to_index,
2307                bubble,
2308            } => {
2309                self.move_children.push(MoveChildCommand {
2310                    parent_id,
2311                    from_index,
2312                    to_index,
2313                    bubble,
2314                });
2315                self.push_tag(CommandTag::MoveChild);
2316            }
2317            Command::RemoveChild {
2318                parent_id,
2319                child_id,
2320            } => {
2321                self.remove_children.push(RemoveChildCommand {
2322                    parent_id,
2323                    child_id,
2324                });
2325                self.push_tag(CommandTag::RemoveChild);
2326            }
2327            Command::DetachChild {
2328                parent_id,
2329                child_id,
2330            } => {
2331                self.detach_children.push(DetachChildCommand {
2332                    parent_id,
2333                    child_id,
2334                });
2335                self.push_tag(CommandTag::DetachChild);
2336            }
2337            Command::SyncChildren {
2338                parent_id,
2339                expected_children,
2340            } => {
2341                let child_start = self.sync_child_ids.len();
2342                let child_len = expected_children.len();
2343                self.sync_child_ids.extend(expected_children);
2344                self.sync_children.push(SyncChildrenCommand {
2345                    parent_id,
2346                    child_start,
2347                    child_len,
2348                });
2349                self.push_tag(CommandTag::SyncChildren);
2350            }
2351            Command::Callback(callback) => {
2352                self.callbacks.push(callback);
2353                self.push_tag(CommandTag::Callback);
2354            }
2355        }
2356    }
2357
2358    fn len(&self) -> usize {
2359        self.len
2360    }
2361
2362    fn capacity(&self) -> usize {
2363        self.chunks.iter().map(Vec::capacity).sum()
2364    }
2365
2366    fn payload_len_bytes(&self) -> usize {
2367        self.bubble_dirty
2368            .len()
2369            .saturating_mul(std::mem::size_of::<BubbleDirtyCommand>())
2370            .saturating_add(
2371                self.update_typed_nodes
2372                    .len()
2373                    .saturating_mul(std::mem::size_of::<UpdateTypedNodeCommand>()),
2374            )
2375            .saturating_add(
2376                self.remove_nodes
2377                    .len()
2378                    .saturating_mul(std::mem::size_of::<NodeId>()),
2379            )
2380            .saturating_add(
2381                self.mount_nodes
2382                    .len()
2383                    .saturating_mul(std::mem::size_of::<NodeId>()),
2384            )
2385            .saturating_add(
2386                self.attach_children
2387                    .len()
2388                    .saturating_mul(std::mem::size_of::<AttachChildCommand>()),
2389            )
2390            .saturating_add(
2391                self.insert_children
2392                    .len()
2393                    .saturating_mul(std::mem::size_of::<InsertChildCommand>()),
2394            )
2395            .saturating_add(
2396                self.move_children
2397                    .len()
2398                    .saturating_mul(std::mem::size_of::<MoveChildCommand>()),
2399            )
2400            .saturating_add(
2401                self.remove_children
2402                    .len()
2403                    .saturating_mul(std::mem::size_of::<RemoveChildCommand>()),
2404            )
2405            .saturating_add(
2406                self.detach_children
2407                    .len()
2408                    .saturating_mul(std::mem::size_of::<DetachChildCommand>()),
2409            )
2410            .saturating_add(
2411                self.sync_children
2412                    .len()
2413                    .saturating_mul(std::mem::size_of::<SyncChildrenCommand>()),
2414            )
2415            .saturating_add(
2416                self.sync_child_ids
2417                    .len()
2418                    .saturating_mul(std::mem::size_of::<NodeId>()),
2419            )
2420            .saturating_add(
2421                self.callbacks
2422                    .len()
2423                    .saturating_mul(std::mem::size_of::<CommandCallback>()),
2424            )
2425    }
2426
2427    fn payload_capacity_bytes(&self) -> usize {
2428        self.bubble_dirty
2429            .capacity()
2430            .saturating_mul(std::mem::size_of::<BubbleDirtyCommand>())
2431            .saturating_add(
2432                self.update_typed_nodes
2433                    .capacity()
2434                    .saturating_mul(std::mem::size_of::<UpdateTypedNodeCommand>()),
2435            )
2436            .saturating_add(
2437                self.remove_nodes
2438                    .capacity()
2439                    .saturating_mul(std::mem::size_of::<NodeId>()),
2440            )
2441            .saturating_add(
2442                self.mount_nodes
2443                    .capacity()
2444                    .saturating_mul(std::mem::size_of::<NodeId>()),
2445            )
2446            .saturating_add(
2447                self.attach_children
2448                    .capacity()
2449                    .saturating_mul(std::mem::size_of::<AttachChildCommand>()),
2450            )
2451            .saturating_add(
2452                self.insert_children
2453                    .capacity()
2454                    .saturating_mul(std::mem::size_of::<InsertChildCommand>()),
2455            )
2456            .saturating_add(
2457                self.move_children
2458                    .capacity()
2459                    .saturating_mul(std::mem::size_of::<MoveChildCommand>()),
2460            )
2461            .saturating_add(
2462                self.remove_children
2463                    .capacity()
2464                    .saturating_mul(std::mem::size_of::<RemoveChildCommand>()),
2465            )
2466            .saturating_add(
2467                self.detach_children
2468                    .capacity()
2469                    .saturating_mul(std::mem::size_of::<DetachChildCommand>()),
2470            )
2471            .saturating_add(
2472                self.sync_children
2473                    .capacity()
2474                    .saturating_mul(std::mem::size_of::<SyncChildrenCommand>()),
2475            )
2476            .saturating_add(
2477                self.sync_child_ids
2478                    .capacity()
2479                    .saturating_mul(std::mem::size_of::<NodeId>()),
2480            )
2481            .saturating_add(
2482                self.callbacks
2483                    .capacity()
2484                    .saturating_mul(std::mem::size_of::<CommandCallback>()),
2485            )
2486    }
2487
2488    fn apply(self, applier: &mut dyn Applier) -> Result<(), NodeError> {
2489        let mut bubble_dirty = self.bubble_dirty.into_iter();
2490        let mut update_typed_nodes = self.update_typed_nodes.into_iter();
2491        let mut remove_nodes = self.remove_nodes.into_iter();
2492        let mut mount_nodes = self.mount_nodes.into_iter();
2493        let mut attach_children = self.attach_children.into_iter();
2494        let mut insert_children = self.insert_children.into_iter();
2495        let mut move_children = self.move_children.into_iter();
2496        let mut remove_children = self.remove_children.into_iter();
2497        let mut detach_children = self.detach_children.into_iter();
2498        let mut sync_children_commands = self.sync_children.into_iter();
2499        let sync_child_ids = self.sync_child_ids;
2500        let mut callbacks = self.callbacks.into_iter();
2501        let mut deferred_cleanup = DeferredChildCleanupQueue::default();
2502
2503        for chunk in self.chunks {
2504            for tag in chunk {
2505                match tag {
2506                    CommandTag::BubbleDirty => {
2507                        let BubbleDirtyCommand { node_id, bubble } =
2508                            next_command_payload(&mut bubble_dirty, tag)?;
2509                        Command::BubbleDirty { node_id, bubble }
2510                            .apply_with_cleanup(applier, &mut deferred_cleanup)?;
2511                    }
2512                    CommandTag::UpdateTypedNode => {
2513                        let UpdateTypedNodeCommand { id, updater } =
2514                            next_command_payload(&mut update_typed_nodes, tag)?;
2515                        Command::UpdateTypedNode { id, updater }
2516                            .apply_with_cleanup(applier, &mut deferred_cleanup)?;
2517                    }
2518                    CommandTag::RemoveNode => {
2519                        let id = next_command_payload(&mut remove_nodes, tag)?;
2520                        Command::RemoveNode { id }
2521                            .apply_with_cleanup(applier, &mut deferred_cleanup)?;
2522                    }
2523                    CommandTag::MountNode => {
2524                        let id = next_command_payload(&mut mount_nodes, tag)?;
2525                        Command::MountNode { id }
2526                            .apply_with_cleanup(applier, &mut deferred_cleanup)?;
2527                    }
2528                    CommandTag::AttachChild => {
2529                        let AttachChildCommand {
2530                            parent_id,
2531                            child_id,
2532                            insert_index,
2533                            bubble,
2534                        } = next_command_payload(&mut attach_children, tag)?;
2535                        Command::AttachChild {
2536                            parent_id,
2537                            child_id,
2538                            insert_index,
2539                            bubble,
2540                        }
2541                        .apply_with_cleanup(applier, &mut deferred_cleanup)?;
2542                    }
2543                    CommandTag::InsertChild => {
2544                        let InsertChildCommand {
2545                            parent_id,
2546                            child_id,
2547                            appended_index,
2548                            insert_index,
2549                            bubble,
2550                        } = next_command_payload(&mut insert_children, tag)?;
2551                        Command::InsertChild {
2552                            parent_id,
2553                            child_id,
2554                            appended_index,
2555                            insert_index,
2556                            bubble,
2557                        }
2558                        .apply_with_cleanup(applier, &mut deferred_cleanup)?;
2559                    }
2560                    CommandTag::MoveChild => {
2561                        let MoveChildCommand {
2562                            parent_id,
2563                            from_index,
2564                            to_index,
2565                            bubble,
2566                        } = next_command_payload(&mut move_children, tag)?;
2567                        Command::MoveChild {
2568                            parent_id,
2569                            from_index,
2570                            to_index,
2571                            bubble,
2572                        }
2573                        .apply_with_cleanup(applier, &mut deferred_cleanup)?;
2574                    }
2575                    CommandTag::RemoveChild => {
2576                        let RemoveChildCommand {
2577                            parent_id,
2578                            child_id,
2579                        } = next_command_payload(&mut remove_children, tag)?;
2580                        Command::RemoveChild {
2581                            parent_id,
2582                            child_id,
2583                        }
2584                        .apply_with_cleanup(applier, &mut deferred_cleanup)?;
2585                    }
2586                    CommandTag::DetachChild => {
2587                        let DetachChildCommand {
2588                            parent_id,
2589                            child_id,
2590                        } = next_command_payload(&mut detach_children, tag)?;
2591                        Command::DetachChild {
2592                            parent_id,
2593                            child_id,
2594                        }
2595                        .apply_with_cleanup(applier, &mut deferred_cleanup)?;
2596                    }
2597                    CommandTag::SyncChildren => {
2598                        let SyncChildrenCommand {
2599                            parent_id,
2600                            child_start,
2601                            child_len,
2602                        } = next_command_payload(&mut sync_children_commands, tag)?;
2603                        let child_end = child_start
2604                            .checked_add(child_len)
2605                            .ok_or_else(|| command_payload_error(tag))?;
2606                        let expected_children = sync_child_ids
2607                            .get(child_start..child_end)
2608                            .ok_or_else(|| command_payload_error(tag))?;
2609                        sync_children(
2610                            applier,
2611                            parent_id,
2612                            expected_children,
2613                            &mut deferred_cleanup,
2614                        )?;
2615                    }
2616                    CommandTag::Callback => {
2617                        let callback = next_command_payload(&mut callbacks, tag)?;
2618                        Command::Callback(callback)
2619                            .apply_with_cleanup(applier, &mut deferred_cleanup)?;
2620                    }
2621                }
2622            }
2623        }
2624
2625        debug_assert!(bubble_dirty.next().is_none());
2626        debug_assert!(update_typed_nodes.next().is_none());
2627        debug_assert!(remove_nodes.next().is_none());
2628        debug_assert!(mount_nodes.next().is_none());
2629        debug_assert!(attach_children.next().is_none());
2630        debug_assert!(insert_children.next().is_none());
2631        debug_assert!(move_children.next().is_none());
2632        debug_assert!(remove_children.next().is_none());
2633        debug_assert!(detach_children.next().is_none());
2634        debug_assert!(sync_children_commands.next().is_none());
2635        debug_assert!(callbacks.next().is_none());
2636        deferred_cleanup.flush(applier)
2637    }
2638}
2639
2640fn command_payload_error(tag: CommandTag) -> NodeError {
2641    NodeError::MalformedCommandPayload { tag: tag.label() }
2642}
2643
2644fn next_command_payload<T>(
2645    payloads: &mut impl Iterator<Item = T>,
2646    tag: CommandTag,
2647) -> Result<T, NodeError> {
2648    payloads.next().ok_or_else(|| command_payload_error(tag))
2649}
2650
2651fn update_typed_node<N: Node + 'static>(node: &mut dyn Node, id: NodeId) -> Result<(), NodeError> {
2652    let typed = node
2653        .as_any_mut()
2654        .downcast_mut::<N>()
2655        .ok_or_else(|| NodeError::TypeMismatch {
2656            id,
2657            expected: std::any::type_name::<N>(),
2658        })?;
2659    typed.update();
2660    Ok(())
2661}
2662
2663fn attach_child_at(
2664    applier: &mut dyn Applier,
2665    parent_id: NodeId,
2666    child_id: NodeId,
2667    insert_index: Option<usize>,
2668    bubble: DirtyBubble,
2669) {
2670    if insert_child_with_reparenting(applier, parent_id, child_id) {
2671        if let Some(target) = insert_index {
2672            move_appended_child_to(applier, parent_id, target);
2673        }
2674        bubble.apply(applier, parent_id);
2675    } else if let Ok(child) = applier.get_mut(child_id) {
2676        let dirty_bubble = DirtyBubble {
2677            layout: child.needs_layout(),
2678            measure: child.needs_measure(),
2679            semantics: false,
2680        };
2681        dirty_bubble.apply(applier, parent_id);
2682    }
2683}
2684
2685fn move_appended_child_to(applier: &mut dyn Applier, parent_id: NodeId, target: usize) {
2686    let Ok(parent_node) = applier.get_mut(parent_id) else {
2687        return;
2688    };
2689    let mut owned: SmallVec<[NodeId; 8]> = SmallVec::new();
2690    parent_node.collect_owned_children_into(&mut owned);
2691    let appended_index = owned.len().saturating_sub(1);
2692    if target < appended_index {
2693        parent_node.move_child(appended_index, target);
2694        note_structural_move(parent_id, appended_index, target);
2695    }
2696}
2697
2698fn insert_child_with_reparenting(
2699    applier: &mut dyn Applier,
2700    parent_id: NodeId,
2701    child_id: NodeId,
2702) -> bool {
2703    if parent_id == child_id {
2704        debug_assert_ne!(
2705            parent_id, child_id,
2706            "a node cannot be attached as its own child"
2707        );
2708        return false;
2709    }
2710
2711    let old_parent = applier
2712        .get_mut(child_id)
2713        .ok()
2714        .and_then(|node| node.parent());
2715    if let Some(old_parent_id) = old_parent
2716        && old_parent_id != parent_id
2717    {
2718        let removed = applier
2719            .get_mut(old_parent_id)
2720            .is_ok_and(|old_parent_node| old_parent_node.remove_child(child_id));
2721        if let Ok(child_node) = applier.get_mut(child_id) {
2722            child_node.on_removed_from_parent();
2723        }
2724        if removed {
2725            bubble_layout_dirty(applier, old_parent_id);
2726            bubble_measure_dirty(applier, old_parent_id);
2727            note_structural("reparent-detach", old_parent_id, child_id);
2728            applier.record_structural_change(old_parent_id);
2729        }
2730    }
2731
2732    let inserted = applier
2733        .get_mut(parent_id)
2734        .is_ok_and(|parent_node| parent_node.insert_child(child_id));
2735    if inserted {
2736        note_structural("attach", parent_id, child_id);
2737        applier.record_structural_change(parent_id);
2738    }
2739    if let Ok(child_node) = applier.get_mut(child_id) {
2740        child_node.on_attached_to_parent(parent_id);
2741    }
2742    inserted
2743}
2744
2745fn apply_remove_child(
2746    applier: &mut dyn Applier,
2747    parent_id: NodeId,
2748    child_id: NodeId,
2749    deferred_cleanup: &mut DeferredChildCleanupQueue,
2750) -> Result<(), NodeError> {
2751    detach_child_from_parent(applier, parent_id, child_id)?;
2752
2753    let generation = applier.node_generation(child_id);
2754    let removed_from_parent = if let Ok(node) = applier.get_mut(child_id) {
2755        node.parent().is_none()
2756    } else {
2757        return Ok(());
2758    };
2759    deferred_cleanup.push(child_id, generation, removed_from_parent);
2760    Ok(())
2761}
2762
2763fn detach_child_from_parent(
2764    applier: &mut dyn Applier,
2765    parent_id: NodeId,
2766    child_id: NodeId,
2767) -> Result<(), NodeError> {
2768    let removed = applier
2769        .get_mut(parent_id)
2770        .is_ok_and(|parent_node| parent_node.remove_child(child_id));
2771    if removed {
2772        bubble_layout_dirty(applier, parent_id);
2773        bubble_measure_dirty(applier, parent_id);
2774        note_structural("detach", parent_id, child_id);
2775        applier.record_structural_change(parent_id);
2776    }
2777
2778    if let Ok(node) = applier.get_mut(child_id) {
2779        match node.parent() {
2780            Some(existing_parent_id) if existing_parent_id == parent_id => {
2781                node.on_removed_from_parent();
2782            }
2783            None => {}
2784            Some(_) => return Ok(()),
2785        }
2786    } else {
2787        return Ok(());
2788    }
2789
2790    Ok(())
2791}
2792
2793fn cleanup_detached_child(
2794    applier: &mut dyn Applier,
2795    cleanup: DeferredChildCleanup,
2796) -> Result<(), NodeError> {
2797    if applier.node_generation(cleanup.child_id) != cleanup.generation {
2798        return Ok(());
2799    }
2800
2801    let parent_id = match applier.get_mut(cleanup.child_id) {
2802        Ok(node) => node.parent(),
2803        Err(NodeError::Missing { .. }) => return Ok(()),
2804        Err(err) => return Err(err),
2805    };
2806    if parent_id.is_some() {
2807        return Ok(());
2808    }
2809
2810    if let Ok(node) = applier.get_mut(cleanup.child_id) {
2811        if !cleanup.removed_from_parent {
2812            node.on_removed_from_parent();
2813        }
2814        node.unmount();
2815    }
2816    match applier.remove(cleanup.child_id) {
2817        Ok(()) | Err(NodeError::Missing { .. }) => Ok(()),
2818        Err(err) => Err(err),
2819    }
2820}
2821
2822fn remove_child_and_cleanup_now(
2823    applier: &mut dyn Applier,
2824    parent_id: NodeId,
2825    child_id: NodeId,
2826) -> Result<(), NodeError> {
2827    let mut deferred_cleanup = DeferredChildCleanupQueue::default();
2828    apply_remove_child(applier, parent_id, child_id, &mut deferred_cleanup)?;
2829    deferred_cleanup.flush(applier)
2830}
2831
2832fn collect_current_children(applier: &mut dyn Applier, parent_id: NodeId) -> ChildList {
2833    let mut scratch = SmallVec::<[NodeId; 8]>::new();
2834    if let Ok(node) = applier.get_mut(parent_id) {
2835        node.collect_children_into(&mut scratch);
2836    }
2837    let mut current = ChildList::new();
2838    current.extend(scratch);
2839    current
2840}
2841
2842fn sync_children(
2843    applier: &mut dyn Applier,
2844    parent_id: NodeId,
2845    expected_children: &[NodeId],
2846    deferred_cleanup: &mut DeferredChildCleanupQueue,
2847) -> Result<(), NodeError> {
2848    let mut current = collect_current_children(applier, parent_id);
2849    let children_changed = current.as_slice() != expected_children;
2850
2851    if children_changed {
2852        if current.len().max(expected_children.len()) <= SMALL_CHILD_SYNC_LINEAR_THRESHOLD {
2853            sync_children_small(
2854                applier,
2855                parent_id,
2856                &mut current,
2857                expected_children,
2858                deferred_cleanup,
2859            )?;
2860        } else {
2861            let mut target_positions: HashMap<NodeId, usize> = HashMap::default();
2862            target_positions.reserve(expected_children.len());
2863            for (index, &child) in expected_children.iter().enumerate() {
2864                target_positions.insert(child, index);
2865            }
2866
2867            for index in (0..current.len()).rev() {
2868                let child = current[index];
2869                if !target_positions.contains_key(&child) {
2870                    current.remove(index);
2871                    apply_remove_child(applier, parent_id, child, deferred_cleanup)?;
2872                }
2873            }
2874
2875            let mut current_positions = build_child_positions(&current);
2876            for (target_index, &child) in expected_children.iter().enumerate() {
2877                if let Some(current_index) = current_positions.get(&child).copied() {
2878                    if current_index != target_index {
2879                        let from_index = current_index;
2880                        let to_index = move_child_in_diff_state(
2881                            &mut current,
2882                            &mut current_positions,
2883                            from_index,
2884                            target_index,
2885                        );
2886                        Command::MoveChild {
2887                            parent_id,
2888                            from_index,
2889                            to_index,
2890                            bubble: DirtyBubble::LAYOUT_AND_MEASURE,
2891                        }
2892                        .apply(applier)?;
2893                    }
2894                } else {
2895                    let insert_index = target_index.min(current.len());
2896                    let appended_index = current.len();
2897                    insert_child_into_diff_state(
2898                        &mut current,
2899                        &mut current_positions,
2900                        insert_index,
2901                        child,
2902                    );
2903                    Command::InsertChild {
2904                        parent_id,
2905                        child_id: child,
2906                        appended_index,
2907                        insert_index,
2908                        bubble: DirtyBubble::LAYOUT_AND_MEASURE,
2909                    }
2910                    .apply(applier)?;
2911                }
2912            }
2913        }
2914    }
2915
2916    reconcile_children(applier, parent_id, expected_children, !children_changed)
2917}
2918
2919fn sync_children_small(
2920    applier: &mut dyn Applier,
2921    parent_id: NodeId,
2922    current: &mut ChildList,
2923    expected_children: &[NodeId],
2924    deferred_cleanup: &mut DeferredChildCleanupQueue,
2925) -> Result<(), NodeError> {
2926    for index in (0..current.len()).rev() {
2927        let child = current[index];
2928        if !expected_children.contains(&child) {
2929            current.remove(index);
2930            apply_remove_child(applier, parent_id, child, deferred_cleanup)?;
2931        }
2932    }
2933
2934    for (target_index, &child) in expected_children.iter().enumerate() {
2935        if let Some(current_index) = current
2936            .iter()
2937            .position(|&current_child| current_child == child)
2938        {
2939            if current_index != target_index {
2940                let child = current.remove(current_index);
2941                let to_index = target_index.min(current.len());
2942                current.insert(to_index, child);
2943                Command::MoveChild {
2944                    parent_id,
2945                    from_index: current_index,
2946                    to_index,
2947                    bubble: DirtyBubble::LAYOUT_AND_MEASURE,
2948                }
2949                .apply(applier)?;
2950            }
2951        } else {
2952            let insert_index = target_index.min(current.len());
2953            let appended_index = current.len();
2954            current.insert(insert_index, child);
2955            Command::InsertChild {
2956                parent_id,
2957                child_id: child,
2958                appended_index,
2959                insert_index,
2960                bubble: DirtyBubble::LAYOUT_AND_MEASURE,
2961            }
2962            .apply(applier)?;
2963        }
2964    }
2965
2966    Ok(())
2967}
2968
2969fn reconcile_children(
2970    applier: &mut dyn Applier,
2971    parent_id: NodeId,
2972    expected_children: &[NodeId],
2973    needs_dirty_check: bool,
2974) -> Result<(), NodeError> {
2975    let mut repaired = false;
2976    for &child_id in expected_children {
2977        let needs_attach = if let Ok(node) = applier.get_mut(child_id) {
2978            node.parent() != Some(parent_id)
2979        } else {
2980            false
2981        };
2982
2983        if needs_attach {
2984            insert_child_with_reparenting(applier, parent_id, child_id);
2985            repaired = true;
2986        }
2987    }
2988
2989    let is_dirty = if needs_dirty_check {
2990        if let Ok(node) = applier.get_mut(parent_id) {
2991            node.needs_layout()
2992        } else {
2993            false
2994        }
2995    } else {
2996        false
2997    };
2998
2999    if repaired {
3000        bubble_layout_dirty(applier, parent_id);
3001        bubble_measure_dirty(applier, parent_id);
3002    } else if is_dirty {
3003        bubble_layout_dirty(applier, parent_id);
3004    }
3005
3006    Ok(())
3007}
3008
3009#[derive(Default)]
3010pub struct MemoryApplier {
3011    nodes: Vec<Option<Box<dyn Node>>>,
3012    physical_stable_ids: Vec<u32>,
3013    physical_warm_recycled_origins: Vec<bool>,
3014    stable_to_physical: HashMap<NodeId, usize>,
3015    stable_generations: HashMap<NodeId, u32>,
3016    free_ids: BinaryHeap<Reverse<usize>>,
3017    high_id_nodes: HashMap<NodeId, Box<dyn Node>>,
3018    high_id_warm_recycled_origins: HashMap<NodeId, bool>,
3019    high_id_generations: HashMap<NodeId, u32>,
3020    next_stable_id: NodeId,
3021    layout_runtime: Option<RuntimeHandle>,
3022    slots: SlotTable,
3023    recycled_nodes: HashMap<TypeId, Vec<RecycledNode>>,
3024    returning_recycled_nodes: HashMap<TypeId, Vec<RecycledNode>>,
3025    cold_recycled_nodes: HashMap<TypeId, Vec<RecycledNode>>,
3026    recycled_node_limits: HashMap<TypeId, usize>,
3027    warm_recycled_node_targets: HashMap<TypeId, usize>,
3028    fresh_recyclable_creations: HashMap<TypeId, usize>,
3029    recycled_node_prototypes: HashMap<TypeId, Box<dyn Node>>,
3030    structural_change_parents: Vec<NodeId>,
3031    virtual_node_ids: HashSet<NodeId>,
3032}
3033
3034struct RemovalFrame {
3035    node_id: NodeId,
3036    children: SmallVec<[NodeId; 8]>,
3037    next_child: usize,
3038}
3039
3040#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
3041pub struct MemoryApplierDebugStats {
3042    pub next_stable_id: NodeId,
3043    pub nodes_len: usize,
3044    pub nodes_cap: usize,
3045    pub physical_stable_ids_len: usize,
3046    pub physical_stable_ids_cap: usize,
3047    pub stable_to_physical_len: usize,
3048    pub stable_to_physical_cap: usize,
3049    pub stable_generations_len: usize,
3050    pub stable_generations_cap: usize,
3051    pub free_ids_len: usize,
3052    pub free_ids_cap: usize,
3053    pub high_id_nodes_len: usize,
3054    pub high_id_nodes_cap: usize,
3055    pub high_id_generations_len: usize,
3056    pub high_id_generations_cap: usize,
3057    pub recycled_type_count: usize,
3058    pub recycled_type_cap: usize,
3059    pub recycled_node_count: usize,
3060    pub recycled_node_capacity: usize,
3061    pub warm_recycled_node_id_count: usize,
3062    pub warm_recycled_node_id_capacity: usize,
3063}
3064
3065impl MemoryApplier {
3066    const EAGER_COMPACT_NODE_LEN: usize = 1_024;
3067    const HIGH_ID_THRESHOLD: NodeId = 1_000_000_000;
3068    const INVALID_STABLE_ID: u32 = u32::MAX;
3069    const INITIAL_DENSE_NODE_CAP: usize = 32;
3070    const LARGE_DENSE_NODE_GROWTH_THRESHOLD: usize = 32 * 1024;
3071    const LARGE_DENSE_NODE_GROWTH_DIVISOR: usize = 4;
3072
3073    fn pack_stable_id(stable_id: NodeId) -> u32 {
3074        u32::try_from(stable_id).expect("stable id overflow")
3075    }
3076
3077    fn unpack_stable_id(stable_id: u32) -> NodeId {
3078        stable_id as NodeId
3079    }
3080
3081    fn next_dense_node_target_len(old_len: usize) -> usize {
3082        if old_len < Self::INITIAL_DENSE_NODE_CAP {
3083            return Self::INITIAL_DENSE_NODE_CAP;
3084        }
3085        if old_len < Self::LARGE_DENSE_NODE_GROWTH_THRESHOLD {
3086            return old_len.saturating_mul(2);
3087        }
3088
3089        let incremental_growth =
3090            (old_len / Self::LARGE_DENSE_NODE_GROWTH_DIVISOR).max(Self::INITIAL_DENSE_NODE_CAP);
3091        old_len.saturating_add(incremental_growth)
3092    }
3093
3094    fn ensure_dense_node_storage_capacity(&mut self) {
3095        let len = self
3096            .nodes
3097            .len()
3098            .max(self.physical_stable_ids.len())
3099            .max(self.physical_warm_recycled_origins.len());
3100        if len < self.nodes.capacity()
3101            && len < self.physical_stable_ids.capacity()
3102            && len < self.physical_warm_recycled_origins.capacity()
3103        {
3104            return;
3105        }
3106
3107        let target = Self::next_dense_node_target_len(len);
3108        if self.nodes.capacity() < target {
3109            self.nodes
3110                .reserve_exact(target.saturating_sub(self.nodes.len()));
3111        }
3112        if self.physical_stable_ids.capacity() < target {
3113            self.physical_stable_ids
3114                .reserve_exact(target.saturating_sub(self.physical_stable_ids.len()));
3115        }
3116        if self.physical_warm_recycled_origins.capacity() < target {
3117            self.physical_warm_recycled_origins
3118                .reserve_exact(target.saturating_sub(self.physical_warm_recycled_origins.len()));
3119        }
3120    }
3121
3122    fn ensure_stable_index_capacity(&mut self) {
3123        let len = self
3124            .stable_to_physical
3125            .len()
3126            .max(self.stable_generations.len());
3127        if len < self.stable_to_physical.capacity() && len < self.stable_generations.capacity() {
3128            return;
3129        }
3130
3131        let target = Self::next_dense_node_target_len(len);
3132        let additional = target.saturating_sub(len);
3133        if self.stable_to_physical.capacity() < target {
3134            self.stable_to_physical.reserve(additional);
3135        }
3136        if self.stable_generations.capacity() < target {
3137            self.stable_generations.reserve(additional);
3138        }
3139    }
3140
3141    pub fn new() -> Self {
3142        Self {
3143            nodes: Vec::new(),
3144            physical_stable_ids: Vec::new(),
3145            physical_warm_recycled_origins: Vec::new(),
3146            stable_to_physical: HashMap::default(),
3147            stable_generations: HashMap::default(),
3148            free_ids: BinaryHeap::new(),
3149            high_id_nodes: HashMap::default(),
3150            high_id_warm_recycled_origins: HashMap::default(),
3151            high_id_generations: HashMap::default(),
3152            next_stable_id: 0,
3153            layout_runtime: None,
3154            slots: SlotTable::default(),
3155            recycled_nodes: HashMap::default(),
3156            returning_recycled_nodes: HashMap::default(),
3157            cold_recycled_nodes: HashMap::default(),
3158            recycled_node_limits: HashMap::default(),
3159            warm_recycled_node_targets: HashMap::default(),
3160            fresh_recyclable_creations: HashMap::default(),
3161            recycled_node_prototypes: HashMap::default(),
3162            structural_change_parents: Vec::new(),
3163            virtual_node_ids: HashSet::default(),
3164        }
3165    }
3166
3167    pub fn slots(&mut self) -> &mut SlotTable {
3168        &mut self.slots
3169    }
3170
3171    /// Drains the parents recorded via [`Applier::record_structural_change`],
3172    /// keeping only nodes still attached to `root` (a parent that was itself
3173    /// removed is covered by its own surviving ancestor's record). A virtual
3174    /// parent — a subcompose slot wrapper the render graph never contains —
3175    /// is reported as its nearest non-virtual ancestor: that is the node
3176    /// whose graph child set the change altered, and an id the graph cannot
3177    /// resolve would force the scoped scene update to give up and rebuild.
3178    /// Resolves a scene-scope candidate the way structural records are
3179    /// resolved: to its nearest non-virtual ancestor, and only while still
3180    /// attached to `root`. A node detached after recording must not reach the
3181    /// scoped scene update — an id the graph cannot resolve forces it to give
3182    /// up and rebuild the whole scene.
3183    pub fn scene_node_attached_to(&mut self, node_id: NodeId, root: NodeId) -> Option<NodeId> {
3184        let resolved = self.first_non_virtual_ancestor(node_id)?;
3185        self.is_attached_to(resolved, root).then_some(resolved)
3186    }
3187
3188    pub fn take_structural_change_parents_attached_to(&mut self, root: NodeId) -> Vec<NodeId> {
3189        let recorded = std::mem::take(&mut self.structural_change_parents);
3190        let mut attached = Vec::with_capacity(recorded.len());
3191        for parent_id in recorded {
3192            let Some(parent_id) = self.first_non_virtual_ancestor(parent_id) else {
3193                continue;
3194            };
3195            if self.is_attached_to(parent_id, root) && !attached.contains(&parent_id) {
3196                attached.push(parent_id);
3197            }
3198        }
3199        attached
3200    }
3201
3202    fn first_non_virtual_ancestor(&mut self, node_id: NodeId) -> Option<NodeId> {
3203        let mut current = node_id;
3204        for _ in 0..100_000 {
3205            if !self.virtual_node_ids.contains(&current) {
3206                return Some(current);
3207            }
3208            match self.get_mut(current) {
3209                Ok(node) => current = node.parent()?,
3210                Err(_) => return None,
3211            }
3212        }
3213        None
3214    }
3215
3216    fn is_attached_to(&mut self, node_id: NodeId, root: NodeId) -> bool {
3217        let mut current = node_id;
3218        for _ in 0..100_000 {
3219            if current == root {
3220                return true;
3221            }
3222            match self.get_mut(current) {
3223                Ok(node) => match node.parent() {
3224                    Some(parent) => current = parent,
3225                    None => return false,
3226                },
3227                Err(_) => return false,
3228            }
3229        }
3230        false
3231    }
3232
3233    pub fn with_node<N: Node + 'static, R>(
3234        &mut self,
3235        id: NodeId,
3236        f: impl FnOnce(&mut N) -> R,
3237    ) -> Result<R, NodeError> {
3238        let physical_id = self
3239            .resolve_node_index(id)
3240            .ok_or(NodeError::Missing { id })?;
3241        let slot = self
3242            .nodes
3243            .get_mut(physical_id)
3244            .ok_or(NodeError::Missing { id })?
3245            .as_deref_mut()
3246            .ok_or(NodeError::Missing { id })?;
3247        let typed =
3248            slot.as_any_mut()
3249                .downcast_mut::<N>()
3250                .ok_or_else(|| NodeError::TypeMismatch {
3251                    id,
3252                    expected: std::any::type_name::<N>(),
3253                })?;
3254        Ok(f(typed))
3255    }
3256
3257    pub fn len(&self) -> usize {
3258        self.nodes.iter().filter(|n| n.is_some()).count()
3259    }
3260
3261    pub fn capacity(&self) -> usize {
3262        self.nodes.len()
3263    }
3264
3265    pub fn tombstone_count(&self) -> usize {
3266        self.nodes.iter().filter(|n| n.is_none()).count()
3267    }
3268
3269    pub fn freelist_len(&self) -> usize {
3270        self.free_ids.len()
3271    }
3272
3273    pub fn debug_recycled_node_count(&self) -> usize {
3274        self.total_recycled_node_count()
3275    }
3276
3277    pub fn debug_recycled_node_count_for<N: Node + 'static>(&self) -> usize {
3278        let key = TypeId::of::<N>();
3279        self.recycled_nodes.get(&key).map_or(0, Vec::len)
3280            + self.returning_recycled_nodes.get(&key).map_or(0, Vec::len)
3281            + self.cold_recycled_nodes.get(&key).map_or(0, Vec::len)
3282    }
3283
3284    pub fn debug_stats(&self) -> MemoryApplierDebugStats {
3285        let mut recycled_keys: HashSet<TypeId> = HashSet::default();
3286        recycled_keys.extend(self.recycled_nodes.keys().copied());
3287        recycled_keys.extend(self.returning_recycled_nodes.keys().copied());
3288        recycled_keys.extend(self.cold_recycled_nodes.keys().copied());
3289
3290        MemoryApplierDebugStats {
3291            next_stable_id: self.next_stable_id,
3292            nodes_len: self.len(),
3293            nodes_cap: self.nodes.len(),
3294            physical_stable_ids_len: self.physical_stable_ids.len(),
3295            physical_stable_ids_cap: self.physical_stable_ids.capacity(),
3296            stable_to_physical_len: self.stable_to_physical.len(),
3297            stable_to_physical_cap: self.stable_to_physical.capacity(),
3298            stable_generations_len: self.stable_generations.len(),
3299            stable_generations_cap: self.stable_generations.capacity(),
3300            free_ids_len: self.free_ids.len(),
3301            free_ids_cap: self.free_ids.capacity(),
3302            high_id_nodes_len: self.high_id_nodes.len(),
3303            high_id_nodes_cap: self.high_id_nodes.capacity(),
3304            high_id_generations_len: self.high_id_generations.len(),
3305            high_id_generations_cap: self.high_id_generations.capacity(),
3306            recycled_type_count: recycled_keys.len(),
3307            recycled_type_cap: self.recycled_nodes.capacity()
3308                + self.returning_recycled_nodes.capacity()
3309                + self.cold_recycled_nodes.capacity(),
3310            recycled_node_count: self.total_recycled_node_count(),
3311            recycled_node_capacity: self.total_recycled_node_capacity(),
3312            warm_recycled_node_id_count: self.total_warm_recycled_node_id_count(),
3313            warm_recycled_node_id_capacity: self.total_warm_recycled_node_id_capacity(),
3314        }
3315    }
3316
3317    pub fn is_empty(&self) -> bool {
3318        self.len() == 0
3319    }
3320
3321    pub fn debug_live_node_heap_bytes(&self) -> usize {
3322        let dense_nodes = self
3323            .nodes
3324            .iter()
3325            .flatten()
3326            .map(|node| std::mem::size_of_val(&**node) + node.debug_heap_bytes())
3327            .sum::<usize>();
3328        let high_id_nodes = self
3329            .high_id_nodes
3330            .values()
3331            .map(|node| std::mem::size_of_val(&**node) + node.debug_heap_bytes())
3332            .sum::<usize>();
3333        dense_nodes + high_id_nodes
3334    }
3335
3336    pub fn debug_recycled_node_heap_bytes(&self) -> usize {
3337        let pool_bytes = |pools: &HashMap<TypeId, Vec<RecycledNode>>| {
3338            pools
3339                .values()
3340                .flat_map(|nodes| nodes.iter())
3341                .map(|node| std::mem::size_of_val(&*node.node) + node.node.debug_heap_bytes())
3342                .sum::<usize>()
3343        };
3344
3345        pool_bytes(&self.recycled_nodes)
3346            + pool_bytes(&self.returning_recycled_nodes)
3347            + pool_bytes(&self.cold_recycled_nodes)
3348    }
3349
3350    pub fn set_runtime_handle(&mut self, handle: RuntimeHandle) {
3351        self.layout_runtime = Some(handle);
3352    }
3353
3354    pub fn clear_runtime_handle(&mut self) {
3355        self.layout_runtime = None;
3356    }
3357
3358    pub fn runtime_handle(&self) -> Option<RuntimeHandle> {
3359        self.layout_runtime.clone()
3360    }
3361
3362    fn pool_node_count(pools: &HashMap<TypeId, Vec<RecycledNode>>) -> usize {
3363        pools.values().map(Vec::len).sum()
3364    }
3365
3366    fn pool_node_capacity(pools: &HashMap<TypeId, Vec<RecycledNode>>) -> usize {
3367        pools.values().map(Vec::capacity).sum()
3368    }
3369
3370    fn total_recycled_node_count(&self) -> usize {
3371        Self::pool_node_count(&self.recycled_nodes)
3372            + Self::pool_node_count(&self.returning_recycled_nodes)
3373            + Self::pool_node_count(&self.cold_recycled_nodes)
3374    }
3375
3376    fn total_recycled_node_capacity(&self) -> usize {
3377        Self::pool_node_capacity(&self.recycled_nodes)
3378            + Self::pool_node_capacity(&self.returning_recycled_nodes)
3379            + Self::pool_node_capacity(&self.cold_recycled_nodes)
3380    }
3381
3382    fn total_warm_recycled_node_id_count(&self) -> usize {
3383        self.live_warm_recycled_origin_count()
3384            + Self::pool_node_count(&self.recycled_nodes)
3385            + Self::pool_node_count(&self.returning_recycled_nodes)
3386    }
3387
3388    fn total_warm_recycled_node_id_capacity(&self) -> usize {
3389        self.live_warm_recycled_origin_capacity()
3390            + Self::pool_node_capacity(&self.recycled_nodes)
3391            + Self::pool_node_capacity(&self.returning_recycled_nodes)
3392    }
3393
3394    fn remember_recycle_pool_limit(&mut self, key: TypeId, recycle_pool_limit: Option<usize>) {
3395        if let Some(limit) = recycle_pool_limit {
3396            self.recycled_node_limits.insert(key, limit);
3397        } else {
3398            self.recycled_node_limits.remove(&key);
3399        }
3400    }
3401
3402    fn recycle_pool_limit_for(&self, key: TypeId) -> Option<usize> {
3403        self.recycled_node_limits.get(&key).copied()
3404    }
3405
3406    fn warm_recycled_pool_len(&self, key: TypeId) -> usize {
3407        self.recycled_nodes.get(&key).map_or(0, Vec::len)
3408    }
3409
3410    fn warm_recycled_node_target(&self, key: TypeId) -> usize {
3411        self.warm_recycled_node_targets
3412            .get(&key)
3413            .copied()
3414            .unwrap_or(0)
3415    }
3416
3417    fn warm_recycled_node_target_limit(&self, key: TypeId) -> usize {
3418        let Some(limit) = self.recycle_pool_limit_for(key) else {
3419            return usize::MAX;
3420        };
3421        if limit <= 8 { limit } else { limit / 4 }
3422    }
3423
3424    fn update_warm_recycled_node_target(&mut self, key: TypeId, observed_demand: usize) -> usize {
3425        let target_limit = self.warm_recycled_node_target_limit(key);
3426        let existing = self.warm_recycled_node_target(key).min(target_limit);
3427        if observed_demand == 0 {
3428            return existing;
3429        }
3430
3431        let target = match self.recycle_pool_limit_for(key) {
3432            Some(limit) if limit > 8 => target_limit,
3433            Some(_) => observed_demand.min(target_limit),
3434            None => observed_demand,
3435        };
3436        self.warm_recycled_node_targets.insert(key, target);
3437        target
3438    }
3439
3440    fn remember_recycled_node_prototype(&mut self, key: TypeId, shell: &dyn Node) {
3441        if self.recycled_node_prototypes.contains_key(&key) {
3442            return;
3443        }
3444        if let Some(prototype) = shell.rehouse_for_recycle() {
3445            self.recycled_node_prototypes.insert(key, prototype);
3446        }
3447    }
3448
3449    fn live_warm_recycled_origin_count(&self) -> usize {
3450        self.physical_warm_recycled_origins
3451            .iter()
3452            .zip(self.nodes.iter())
3453            .filter(|(warm_origin, node)| **warm_origin && node.is_some())
3454            .count()
3455            + self
3456                .high_id_warm_recycled_origins
3457                .values()
3458                .filter(|warm_origin| **warm_origin)
3459                .count()
3460    }
3461
3462    fn live_warm_recycled_origin_capacity(&self) -> usize {
3463        self.physical_warm_recycled_origins.capacity()
3464            + self.high_id_warm_recycled_origins.capacity()
3465    }
3466
3467    fn push_recycled_node(
3468        &mut self,
3469        key: TypeId,
3470        recycle_pool_limit: Option<usize>,
3471        recycled: RecycledNode,
3472    ) {
3473        self.remember_recycle_pool_limit(key, recycle_pool_limit);
3474        self.remember_recycled_node_prototype(key, recycled.node.as_ref());
3475
3476        let warm_origin = recycled.warm_origin();
3477        let pool = if warm_origin {
3478            self.returning_recycled_nodes.entry(key).or_default()
3479        } else {
3480            self.cold_recycled_nodes.entry(key).or_default()
3481        };
3482        pool.push(recycled);
3483        if let Some(limit) = recycle_pool_limit
3484            && pool.len() > limit
3485        {
3486            let excess = pool.len() - limit;
3487            let dropped: Vec<_> = pool.drain(0..excess).collect();
3488            drop(dropped);
3489        }
3490    }
3491
3492    fn push_warm_recycled_node(
3493        &mut self,
3494        key: TypeId,
3495        recycle_pool_limit: Option<usize>,
3496        mut recycled: RecycledNode,
3497    ) {
3498        self.remember_recycle_pool_limit(key, recycle_pool_limit);
3499
3500        recycled.set_warm_origin(true);
3501        let mut dropped = Vec::new();
3502        let mut remove_pool_entry = false;
3503        {
3504            let pool = self.recycled_nodes.entry(key).or_default();
3505            pool.push(recycled);
3506            if let Some(limit) = recycle_pool_limit
3507                && pool.len() > limit
3508            {
3509                let excess = pool.len() - limit;
3510                dropped = pool.drain(0..excess).collect();
3511                remove_pool_entry = pool.is_empty();
3512            }
3513        }
3514        if remove_pool_entry {
3515            self.recycled_nodes.remove(&key);
3516        }
3517        drop(dropped);
3518    }
3519
3520    fn seed_recycled_node_shell_impl(
3521        &mut self,
3522        key: TypeId,
3523        recycle_pool_limit: Option<usize>,
3524        shell: Box<dyn Node>,
3525    ) {
3526        let limit = recycle_pool_limit.unwrap_or(usize::MAX);
3527        if self.warm_recycled_pool_len(key) >= limit {
3528            return;
3529        }
3530
3531        self.remember_recycled_node_prototype(key, shell.as_ref());
3532        let stable_id = self.next_stable_id;
3533        self.next_stable_id = self.next_stable_id.saturating_add(1);
3534        self.push_warm_recycled_node(
3535            key,
3536            recycle_pool_limit,
3537            RecycledNode::from_shell(stable_id, shell, true),
3538        );
3539    }
3540
3541    fn take_recycled_node_from_pool(
3542        pools: &mut HashMap<TypeId, Vec<RecycledNode>>,
3543        key: TypeId,
3544    ) -> Option<RecycledNode> {
3545        let pool = pools.get_mut(&key)?;
3546        let node = pool.pop();
3547        if pool.is_empty() {
3548            pools.remove(&key);
3549        }
3550        node
3551    }
3552
3553    fn compact_idle_warm_pool(&mut self, key: TypeId) {
3554        let Some(pool) = self.recycled_nodes.get_mut(&key) else {
3555            return;
3556        };
3557        if pool.capacity() <= pool.len().saturating_mul(4).max(64) {
3558            return;
3559        }
3560
3561        let retained = pool.len();
3562        let mut compacted = Vec::with_capacity(retained);
3563        compacted.append(pool);
3564        let remove_pool_entry = compacted.is_empty();
3565        *pool = compacted;
3566        let _ = pool;
3567
3568        if remove_pool_entry {
3569            self.recycled_nodes.remove(&key);
3570        }
3571    }
3572
3573    fn trim_idle_warm_pool_to_target(&mut self, key: TypeId, target: usize) {
3574        let pool_len = self.warm_recycled_pool_len(key);
3575        if pool_len <= target {
3576            return;
3577        }
3578
3579        let Some(pool) = self.recycled_nodes.get_mut(&key) else {
3580            return;
3581        };
3582        let removable = (pool_len - target).min(pool.len());
3583        let dropped: Vec<_> = pool.drain(0..removable).collect();
3584        let remove_pool_entry = pool.is_empty();
3585        let _ = pool;
3586
3587        if remove_pool_entry {
3588            self.recycled_nodes.remove(&key);
3589        }
3590        drop(dropped);
3591    }
3592
3593    fn replenish_warm_pool_to_target(&mut self, key: TypeId, target: usize) {
3594        let missing = target.saturating_sub(self.warm_recycled_pool_len(key));
3595        if missing == 0 {
3596            return;
3597        }
3598
3599        let recycle_pool_limit = self.recycle_pool_limit_for(key);
3600        let mut shells = Vec::with_capacity(missing);
3601        if let Some(prototype) = self.recycled_node_prototypes.get(&key) {
3602            for _ in 0..missing {
3603                let Some(shell) = prototype.rehouse_for_recycle() else {
3604                    break;
3605                };
3606                shells.push(shell);
3607            }
3608        }
3609
3610        for shell in shells {
3611            self.seed_recycled_node_shell_impl(key, recycle_pool_limit, shell);
3612        }
3613    }
3614
3615    fn prune_stable_generations(&mut self) {
3616        let retained_len = self.stable_to_physical.len() + self.total_recycled_node_count();
3617        if retained_len == self.stable_generations.len() {
3618            return;
3619        }
3620
3621        let mut retained = HashMap::default();
3622        retained.reserve(retained_len);
3623        for stable_id in self.stable_to_physical.keys().copied() {
3624            if let Some(generation) = self.stable_generations.get(&stable_id).copied() {
3625                retained.insert(stable_id, generation);
3626            }
3627        }
3628        for stable_id in self
3629            .recycled_nodes
3630            .values()
3631            .flat_map(|nodes| nodes.iter().map(RecycledNode::stable_id))
3632        {
3633            if let Some(generation) = self.stable_generations.get(&stable_id).copied() {
3634                retained.insert(stable_id, generation);
3635            }
3636        }
3637        for stable_id in self
3638            .returning_recycled_nodes
3639            .values()
3640            .flat_map(|nodes| nodes.iter().map(RecycledNode::stable_id))
3641        {
3642            if let Some(generation) = self.stable_generations.get(&stable_id).copied() {
3643                retained.insert(stable_id, generation);
3644            }
3645        }
3646        for stable_id in self
3647            .cold_recycled_nodes
3648            .values()
3649            .flat_map(|nodes| nodes.iter().map(RecycledNode::stable_id))
3650        {
3651            if let Some(generation) = self.stable_generations.get(&stable_id).copied() {
3652                retained.insert(stable_id, generation);
3653            }
3654        }
3655        self.stable_generations = retained;
3656    }
3657
3658    pub fn dump_tree(&self, root: Option<NodeId>) -> String {
3659        let mut output = String::new();
3660        if let Some(root_id) = root {
3661            self.dump_node(&mut output, root_id, 0);
3662        } else {
3663            output.push_str("(no root)\n");
3664        }
3665        output
3666    }
3667
3668    fn dump_node(&self, output: &mut String, id: NodeId, depth: usize) {
3669        let indent = "  ".repeat(depth);
3670        if let Some(physical_id) = self.resolve_node_index(id) {
3671            if let Some(node) = self.nodes.get(physical_id).and_then(Option::as_ref) {
3672                let type_name = std::any::type_name_of_val(&**node);
3673                output.push_str(&format!("{indent}[{id}] {type_name}\n"));
3674
3675                let children = node.children();
3676                for child_id in children {
3677                    self.dump_node(output, child_id, depth + 1);
3678                }
3679            } else {
3680                output.push_str(&format!(
3681                    "{indent}[{id}] (missing physical node {physical_id})\n"
3682                ));
3683            }
3684        } else {
3685            output.push_str(&format!("{indent}[{id}] (missing)\n"));
3686        }
3687    }
3688
3689    fn resolve_node_index(&self, id: NodeId) -> Option<usize> {
3690        self.stable_to_physical.get(&id).copied()
3691    }
3692
3693    fn contains_node_id(&self, id: NodeId) -> bool {
3694        self.resolve_node_index(id).is_some() || self.high_id_nodes.contains_key(&id)
3695    }
3696
3697    fn insert_high_id_node(&mut self, stable_id: NodeId, node: Box<dyn Node>, warm_origin: bool) {
3698        self.high_id_nodes.insert(stable_id, node);
3699        self.high_id_warm_recycled_origins
3700            .insert(stable_id, warm_origin);
3701        self.high_id_generations.entry(stable_id).or_insert(0);
3702    }
3703
3704    fn insert_available_with_id(&mut self, stable_id: NodeId, node: Box<dyn Node>) {
3705        if stable_id >= Self::HIGH_ID_THRESHOLD {
3706            self.insert_high_id_node(stable_id, node, false);
3707            return;
3708        }
3709
3710        let physical_id = if let Some(Reverse(free_physical_id)) = self.free_ids.pop() {
3711            self.nodes[free_physical_id] = Some(node);
3712            self.physical_stable_ids[free_physical_id] = Self::pack_stable_id(stable_id);
3713            self.physical_warm_recycled_origins[free_physical_id] = false;
3714            free_physical_id
3715        } else {
3716            self.ensure_dense_node_storage_capacity();
3717            let physical_id = self.nodes.len();
3718            self.nodes.push(Some(node));
3719            self.physical_stable_ids
3720                .push(Self::pack_stable_id(stable_id));
3721            self.physical_warm_recycled_origins.push(false);
3722            physical_id
3723        };
3724
3725        self.next_stable_id = self.next_stable_id.max(stable_id.saturating_add(1));
3726        self.ensure_stable_index_capacity();
3727        self.stable_generations.entry(stable_id).or_insert(0);
3728        self.physical_stable_ids[physical_id] = Self::pack_stable_id(stable_id);
3729        self.stable_to_physical.insert(stable_id, physical_id);
3730    }
3731
3732    fn get_ref(&self, id: NodeId) -> Result<&dyn Node, NodeError> {
3733        if let Some(physical_id) = self.resolve_node_index(id) {
3734            let slot = self
3735                .nodes
3736                .get(physical_id)
3737                .ok_or(NodeError::Missing { id })?
3738                .as_deref()
3739                .ok_or(NodeError::Missing { id })?;
3740            return Ok(slot);
3741        }
3742
3743        self.high_id_nodes
3744            .get(&id)
3745            .map(AsRef::as_ref)
3746            .ok_or(NodeError::Missing { id })
3747    }
3748
3749    fn node_parent(&self, id: NodeId) -> Result<Option<NodeId>, NodeError> {
3750        Ok(self.get_ref(id)?.parent())
3751    }
3752
3753    fn collect_owned_children(
3754        &self,
3755        node_id: NodeId,
3756        out: &mut SmallVec<[NodeId; 8]>,
3757    ) -> Result<(), NodeError> {
3758        self.get_ref(node_id)?.collect_owned_children_into(out);
3759        out.retain(|child_id| {
3760            self.node_parent(*child_id)
3761                .is_ok_and(|parent| parent == Some(node_id))
3762        });
3763        Ok(())
3764    }
3765
3766    fn remove_node_storage(&mut self, node_id: NodeId) -> Result<(), NodeError> {
3767        self.virtual_node_ids.remove(&node_id);
3768        if self.high_id_nodes.contains_key(&node_id) {
3769            if let Some(mut node) = self.high_id_nodes.remove(&node_id)
3770                && let Some(key) = node.recycle_key()
3771            {
3772                let recycle_pool_limit = node.recycle_pool_limit();
3773                let warm_origin = self
3774                    .high_id_warm_recycled_origins
3775                    .remove(&node_id)
3776                    .unwrap_or(false);
3777                node.prepare_for_recycle();
3778                self.push_recycled_node(
3779                    key,
3780                    recycle_pool_limit,
3781                    RecycledNode::new(node_id, node, warm_origin),
3782                );
3783            }
3784            let generation = self.high_id_generations.entry(node_id).or_insert(0);
3785            *generation = generation.wrapping_add(1);
3786            return Ok(());
3787        }
3788
3789        let physical_id = self
3790            .resolve_node_index(node_id)
3791            .ok_or(NodeError::Missing { id: node_id })?;
3792        if let Some(mut node) = self.nodes[physical_id].take()
3793            && let Some(key) = node.recycle_key()
3794        {
3795            let recycle_pool_limit = node.recycle_pool_limit();
3796            let warm_origin = self
3797                .physical_warm_recycled_origins
3798                .get_mut(physical_id)
3799                .is_some_and(std::mem::take);
3800            node.prepare_for_recycle();
3801            self.push_recycled_node(
3802                key,
3803                recycle_pool_limit,
3804                RecycledNode::new(node_id, node, warm_origin),
3805            );
3806        }
3807        self.physical_stable_ids[physical_id] = Self::INVALID_STABLE_ID;
3808        self.stable_to_physical.remove(&node_id);
3809        if let Some(generation) = self.stable_generations.get_mut(&node_id) {
3810            *generation = generation.wrapping_add(1);
3811        } else {
3812            self.stable_generations.insert(node_id, 1);
3813        }
3814        self.free_ids.push(Reverse(physical_id));
3815        Ok(())
3816    }
3817
3818    fn remove_subtree_postorder(&mut self, id: NodeId) -> Result<usize, NodeError> {
3819        self.get_ref(id)?;
3820
3821        let mut root_children = SmallVec::<[NodeId; 8]>::new();
3822        self.collect_owned_children(id, &mut root_children)?;
3823
3824        let mut stack = Vec::new();
3825        stack.push(RemovalFrame {
3826            node_id: id,
3827            children: root_children,
3828            next_child: 0,
3829        });
3830        let mut max_depth = stack.len();
3831
3832        while let Some(frame) = stack.last_mut() {
3833            if frame.next_child < frame.children.len() {
3834                let child_id = frame.children[frame.next_child];
3835                frame.next_child += 1;
3836
3837                if let Ok(child) = self.get_mut(child_id) {
3838                    child.on_removed_from_parent();
3839                    child.unmount();
3840                }
3841
3842                let mut child_children = SmallVec::<[NodeId; 8]>::new();
3843                self.collect_owned_children(child_id, &mut child_children)?;
3844                stack.push(RemovalFrame {
3845                    node_id: child_id,
3846                    children: child_children,
3847                    next_child: 0,
3848                });
3849                max_depth = max_depth.max(stack.len());
3850                continue;
3851            }
3852
3853            let node_id = frame.node_id;
3854            stack.pop();
3855            self.remove_node_storage(node_id)?;
3856        }
3857
3858        Ok(max_depth)
3859    }
3860
3861    #[cfg(test)]
3862    fn debug_remove_max_traversal_depth(&mut self, id: NodeId) -> Result<usize, NodeError> {
3863        self.remove_subtree_postorder(id)
3864    }
3865}
3866
3867impl Applier for MemoryApplier {
3868    fn record_structural_change(&mut self, parent_id: NodeId) {
3869        if self.structural_change_parents.last() != Some(&parent_id) {
3870            self.structural_change_parents.push(parent_id);
3871        }
3872    }
3873
3874    fn create(&mut self, node: Box<dyn Node>) -> NodeId {
3875        let stable_id = self.next_stable_id;
3876        self.next_stable_id = self.next_stable_id.saturating_add(1);
3877        if stable_id >= Self::HIGH_ID_THRESHOLD {
3878            self.insert_high_id_node(stable_id, node, false);
3879            return stable_id;
3880        }
3881
3882        self.ensure_stable_index_capacity();
3883        self.stable_generations.insert(stable_id, 0);
3884
3885        let physical_id = if let Some(Reverse(id)) = self.free_ids.pop() {
3886            debug_assert!(self.nodes[id].is_none(), "freelist entry {id} is not None");
3887            self.nodes[id] = Some(node);
3888            self.physical_stable_ids[id] = Self::pack_stable_id(stable_id);
3889            self.physical_warm_recycled_origins[id] = false;
3890            id
3891        } else {
3892            self.ensure_dense_node_storage_capacity();
3893            let id = self.nodes.len();
3894            self.nodes.push(Some(node));
3895            self.physical_stable_ids
3896                .push(Self::pack_stable_id(stable_id));
3897            self.physical_warm_recycled_origins.push(false);
3898            id
3899        };
3900        self.stable_to_physical.insert(stable_id, physical_id);
3901        stable_id
3902    }
3903
3904    fn node_generation(&self, id: NodeId) -> u32 {
3905        self.high_id_generations
3906            .get(&id)
3907            .copied()
3908            .or_else(|| self.stable_generations.get(&id).copied())
3909            .unwrap_or(0)
3910    }
3911
3912    fn get_mut(&mut self, id: NodeId) -> Result<&mut dyn Node, NodeError> {
3913        if let Some(physical_id) = self.resolve_node_index(id) {
3914            let slot = self.nodes[physical_id]
3915                .as_deref_mut()
3916                .ok_or(NodeError::Missing { id })?;
3917            return Ok(slot);
3918        }
3919        self.high_id_nodes
3920            .get_mut(&id)
3921            .map(std::convert::AsMut::as_mut)
3922            .ok_or(NodeError::Missing { id })
3923    }
3924
3925    fn remove(&mut self, id: NodeId) -> Result<(), NodeError> {
3926        self.remove_subtree_postorder(id).map(|_| ())
3927    }
3928
3929    fn insert_with_id(&mut self, id: NodeId, node: Box<dyn Node>) -> Result<(), NodeError> {
3930        if self.contains_node_id(id) {
3931            return Err(NodeError::AlreadyExists { id });
3932        }
3933        self.insert_available_with_id(id, node);
3934        self.virtual_node_ids.insert(id);
3935        Ok(())
3936    }
3937
3938    fn insert_recycled_node_or_create(
3939        &mut self,
3940        stable_id: NodeId,
3941        node: Box<dyn Node>,
3942    ) -> RecycledNodeInsertion {
3943        if self.contains_node_id(stable_id) {
3944            let id = self.create(node);
3945            return RecycledNodeInsertion::fresh(
3946                id,
3947                Some(NodeError::AlreadyExists { id: stable_id }),
3948            );
3949        }
3950
3951        self.insert_available_with_id(stable_id, node);
3952        RecycledNodeInsertion::reused(stable_id)
3953    }
3954
3955    fn compact(&mut self) {
3956        let live_count = self.nodes.iter().filter(|slot| slot.is_some()).count();
3957        let tombstone_count = self.nodes.len().saturating_sub(live_count);
3958        if tombstone_count == 0 {
3959            return;
3960        }
3961        if self.nodes.len() > Self::EAGER_COMPACT_NODE_LEN && tombstone_count < live_count {
3962            return;
3963        }
3964        let rehouse_live_nodes = tombstone_count >= live_count;
3965        let mut packed_nodes = Vec::with_capacity(live_count);
3966        let mut packed_physical_stable_ids = Vec::with_capacity(live_count);
3967        let mut packed_warm_recycled_origins = Vec::with_capacity(live_count);
3968        let mut stable_to_physical = HashMap::default();
3969        stable_to_physical.reserve(live_count);
3970
3971        for physical_id in 0..self.nodes.len() {
3972            let Some(mut node) = self.nodes[physical_id].take() else {
3973                continue;
3974            };
3975            if rehouse_live_nodes && let Some(rehoused) = node.rehouse_for_live_compaction() {
3976                node = rehoused;
3977            }
3978            let stable_id = std::mem::replace(
3979                &mut self.physical_stable_ids[physical_id],
3980                Self::INVALID_STABLE_ID,
3981            );
3982            debug_assert_ne!(
3983                stable_id,
3984                Self::INVALID_STABLE_ID,
3985                "live physical slot must have a stable id",
3986            );
3987            let stable_id = Self::unpack_stable_id(stable_id);
3988            packed_nodes.push(Some(node));
3989            packed_physical_stable_ids.push(Self::pack_stable_id(stable_id));
3990            packed_warm_recycled_origins.push(self.physical_warm_recycled_origins[physical_id]);
3991            stable_to_physical.insert(stable_id, packed_nodes.len() - 1);
3992        }
3993
3994        self.nodes = packed_nodes;
3995        self.physical_stable_ids = packed_physical_stable_ids;
3996        self.physical_warm_recycled_origins = packed_warm_recycled_origins;
3997        self.free_ids = BinaryHeap::new();
3998        self.stable_to_physical = stable_to_physical;
3999        self.prune_stable_generations();
4000    }
4001
4002    fn take_recycled_node(&mut self, key: TypeId) -> Option<RecycledNode> {
4003        Self::take_recycled_node_from_pool(&mut self.returning_recycled_nodes, key)
4004            .or_else(|| Self::take_recycled_node_from_pool(&mut self.recycled_nodes, key))
4005    }
4006
4007    fn set_recycled_node_origin(&mut self, id: NodeId, warm_origin: bool) {
4008        if let Some(physical_id) = self.resolve_node_index(id) {
4009            self.physical_warm_recycled_origins[physical_id] = warm_origin;
4010        } else if self.high_id_nodes.contains_key(&id) {
4011            self.high_id_warm_recycled_origins.insert(id, warm_origin);
4012        }
4013    }
4014
4015    fn seed_recycled_node_shell(
4016        &mut self,
4017        key: TypeId,
4018        recycle_pool_limit: Option<usize>,
4019        shell: Box<dyn Node>,
4020    ) {
4021        self.seed_recycled_node_shell_impl(key, recycle_pool_limit, shell);
4022    }
4023
4024    fn record_fresh_recyclable_creation(&mut self, key: TypeId) {
4025        *self.fresh_recyclable_creations.entry(key).or_insert(0) += 1;
4026    }
4027
4028    fn clear_recycled_nodes(&mut self) {
4029        let returning = std::mem::take(&mut self.returning_recycled_nodes);
4030        for (key, mut nodes) in returning {
4031            let pool = self.recycled_nodes.entry(key).or_default();
4032            pool.append(&mut nodes);
4033        }
4034
4035        let fresh_recyclable_creations = std::mem::take(&mut self.fresh_recyclable_creations);
4036        let cold = std::mem::take(&mut self.cold_recycled_nodes);
4037        for (key, mut nodes) in cold {
4038            let needed = fresh_recyclable_creations.get(&key).copied().unwrap_or(0);
4039            if needed > 0 {
4040                let remaining_limit = self
4041                    .recycle_pool_limit_for(key)
4042                    .unwrap_or(usize::MAX)
4043                    .saturating_sub(self.warm_recycled_pool_len(key));
4044                let promote = nodes.len().min(needed).min(remaining_limit);
4045                let split_at = nodes.len().saturating_sub(promote);
4046                let promoted = nodes.split_off(split_at);
4047                for mut recycled in promoted {
4048                    recycled.set_warm_origin(true);
4049                    self.recycled_nodes.entry(key).or_default().push(recycled);
4050                }
4051            }
4052        }
4053
4054        let mut keys: HashSet<TypeId> = HashSet::default();
4055        keys.extend(self.recycled_nodes.keys().copied());
4056        keys.extend(self.recycled_node_limits.keys().copied());
4057        keys.extend(self.warm_recycled_node_targets.keys().copied());
4058        keys.extend(self.recycled_node_prototypes.keys().copied());
4059        for key in keys {
4060            let observed_demand = fresh_recyclable_creations.get(&key).copied().unwrap_or(0);
4061            let target = self.update_warm_recycled_node_target(key, observed_demand);
4062            self.replenish_warm_pool_to_target(key, target);
4063            self.trim_idle_warm_pool_to_target(key, target);
4064            self.compact_idle_warm_pool(key);
4065        }
4066        self.prune_stable_generations();
4067        self.compact();
4068    }
4069}
4070
4071pub trait ApplierHost {
4072    fn borrow_dyn(&self) -> RefMut<'_, dyn Applier>;
4073    /// Compact internal storage after commands have been applied.
4074    fn compact(&self) {}
4075}
4076
4077pub struct ConcreteApplierHost<A: Applier + 'static> {
4078    inner: RefCell<A>,
4079}
4080
4081impl<A: Applier + 'static> ConcreteApplierHost<A> {
4082    pub fn new(applier: A) -> Self {
4083        Self {
4084            inner: RefCell::new(applier),
4085        }
4086    }
4087
4088    pub fn borrow_typed(&self) -> RefMut<'_, A> {
4089        self.inner.borrow_mut()
4090    }
4091
4092    pub fn try_borrow_typed(&self) -> Result<RefMut<'_, A>, std::cell::BorrowMutError> {
4093        self.inner.try_borrow_mut()
4094    }
4095
4096    pub fn into_inner(self) -> A {
4097        self.inner.into_inner()
4098    }
4099}
4100
4101impl<A: Applier + 'static> ApplierHost for ConcreteApplierHost<A> {
4102    fn borrow_dyn(&self) -> RefMut<'_, dyn Applier> {
4103        RefMut::map(self.inner.borrow_mut(), |applier| {
4104            applier as &mut dyn Applier
4105        })
4106    }
4107
4108    fn compact(&self) {
4109        self.inner.borrow_mut().compact();
4110    }
4111}
4112
4113pub struct ApplierGuard<'a, A: Applier + 'static> {
4114    inner: RefMut<'a, A>,
4115}
4116
4117impl<'a, A: Applier + 'static> ApplierGuard<'a, A> {
4118    fn new(inner: RefMut<'a, A>) -> Self {
4119        Self { inner }
4120    }
4121}
4122
4123impl<A: Applier + 'static> Deref for ApplierGuard<'_, A> {
4124    type Target = A;
4125
4126    fn deref(&self) -> &Self::Target {
4127        &self.inner
4128    }
4129}
4130
4131impl<A: Applier + 'static> DerefMut for ApplierGuard<'_, A> {
4132    fn deref_mut(&mut self) -> &mut Self::Target {
4133        &mut self.inner
4134    }
4135}
4136
4137pub struct SlotsHost {
4138    storage_key: Cell<usize>,
4139    inner: RefCell<SlotsHostInner>,
4140}
4141
4142#[derive(Debug, Default)]
4143pub(crate) struct SlotPassOutcome {
4144    pub(crate) compacted: bool,
4145    pub(crate) compact_anchor_registry_storage: bool,
4146    pub(crate) compact_payload_storage: bool,
4147}
4148
4149#[derive(Default)]
4150pub(crate) struct FinishedSlotPass {
4151    pub(crate) outcome: SlotPassOutcome,
4152    pub(crate) detached_root_children: Vec<slot::DetachedSubtree>,
4153}
4154
4155struct ActivePassState {
4156    state: slot::SlotWriteSessionState,
4157}
4158
4159struct SlotsHostInner {
4160    table: SlotTable,
4161    nested_hosts: Vec<std::rc::Weak<SlotsHost>>,
4162    lifecycle: slot::SlotLifecycleCoordinator,
4163    runtime_state: Option<Rc<crate::composer::ComposerRuntimeState>>,
4164    active_pass: Option<ActivePassState>,
4165}
4166
4167impl Drop for SlotsHost {
4168    fn drop(&mut self) {
4169        let storage_key = self.storage_key.get();
4170        let inner = self.inner.get_mut();
4171        if let Some(state) = inner.runtime_state.clone() {
4172            if let Err(err) = state.dispose_retained_subtrees_for_host(
4173                storage_key,
4174                &mut inner.table,
4175                &mut inner.lifecycle,
4176            ) {
4177                log::error!(
4178                    "retained subtree disposal failed while dropping SlotsHost {storage_key}: {err}"
4179                );
4180                state.abandon_retained_subtrees_for_host(
4181                    storage_key,
4182                    &mut inner.table,
4183                    &mut inner.lifecycle,
4184                );
4185            } else {
4186                state.clear_host_storage_key(storage_key);
4187            }
4188        }
4189        inner.lifecycle.dispose_slot_table(&mut inner.table);
4190    }
4191}
4192
4193impl SlotsHost {
4194    pub fn storage_key(&self) -> usize {
4195        self.storage_key.get()
4196    }
4197
4198    pub fn new(storage: SlotTable) -> Self {
4199        let storage_key = storage.storage_id();
4200        Self {
4201            storage_key: Cell::new(storage_key),
4202            inner: RefCell::new(SlotsHostInner {
4203                table: storage,
4204                nested_hosts: Vec::new(),
4205                lifecycle: slot::SlotLifecycleCoordinator::default(),
4206                runtime_state: None,
4207                active_pass: None,
4208            }),
4209        }
4210    }
4211
4212    pub fn note_nested_host(&self, nested: &Rc<SlotsHost>) {
4213        let Ok(mut inner) = self.inner.try_borrow_mut() else {
4214            return;
4215        };
4216        inner.nested_hosts.retain(|held| held.upgrade().is_some());
4217        if inner
4218            .nested_hosts
4219            .iter()
4220            .any(|held| held.upgrade().is_some_and(|host| Rc::ptr_eq(&host, nested)))
4221        {
4222            return;
4223        }
4224        inner.nested_hosts.push(Rc::downgrade(nested));
4225    }
4226
4227    pub(crate) fn forget_effects(&self) -> bool {
4228        let (forgotten, nested, runtime_state) = {
4229            let Ok(mut inner) = self.inner.try_borrow_mut() else {
4230                return false;
4231            };
4232            if inner.active_pass.is_some() {
4233                return false;
4234            }
4235            let drops = inner.table.take_effect_drops();
4236            inner.nested_hosts.retain(|held| held.upgrade().is_some());
4237            let nested: Vec<Rc<SlotsHost>> = inner
4238                .nested_hosts
4239                .iter()
4240                .filter_map(std::rc::Weak::upgrade)
4241                .collect();
4242            (drops, nested, inner.runtime_state.clone())
4243        };
4244        let mut any = !forgotten.is_empty();
4245        drop(forgotten);
4246        for host in nested {
4247            any |= host.forget_effects();
4248        }
4249        if any && let Some(runtime_state) = runtime_state {
4250            runtime_state.force_recompose_host_scopes(self.storage_key());
4251        }
4252        any
4253    }
4254
4255    pub(crate) fn bind_runtime_state(&self, state: &Rc<crate::composer::ComposerRuntimeState>) {
4256        let mut inner = self.inner.borrow_mut();
4257        inner.runtime_state = Some(Rc::clone(state));
4258    }
4259
4260    pub(crate) fn rebind_orphaned_runtime_state(
4261        &self,
4262        state: &Rc<crate::composer::ComposerRuntimeState>,
4263    ) -> bool {
4264        let inner = self.inner.borrow();
4265        if inner.active_pass.is_some() {
4266            log::error!("cannot rebind SlotsHost during an active pass");
4267            return false;
4268        }
4269        let Some(bound_state) = inner.runtime_state.as_ref() else {
4270            drop(inner);
4271            self.bind_runtime_state(state);
4272            return true;
4273        };
4274        if Rc::ptr_eq(bound_state, state) {
4275            return true;
4276        }
4277        if bound_state.has_live_applier_host() {
4278            return false;
4279        }
4280        drop(inner);
4281
4282        let mut inner = self.inner.borrow_mut();
4283        let Some(bound_state) = inner.runtime_state.as_ref() else {
4284            inner.runtime_state = Some(Rc::clone(state));
4285            return true;
4286        };
4287        if Rc::ptr_eq(bound_state, state) {
4288            return true;
4289        }
4290        if bound_state.has_live_applier_host() {
4291            return false;
4292        }
4293
4294        let previous_state = Rc::clone(bound_state);
4295        let mut lifecycle = std::mem::take(&mut inner.lifecycle);
4296        lifecycle.flush_pending_drops();
4297        let host_key = self.storage_key();
4298        if previous_state
4299            .dispose_retained_subtrees_for_host(host_key, &mut inner.table, &mut lifecycle)
4300            .is_err()
4301        {
4302            inner.lifecycle = lifecycle;
4303            return false;
4304        }
4305        previous_state.clear_host(self);
4306        lifecycle.flush_pending_drops();
4307        inner.runtime_state = Some(Rc::clone(state));
4308        inner.lifecycle = lifecycle;
4309        true
4310    }
4311
4312    pub(crate) fn runtime_state(&self) -> Option<Rc<crate::composer::ComposerRuntimeState>> {
4313        self.inner.borrow().runtime_state.clone()
4314    }
4315
4316    pub(crate) fn borrow(&self) -> Ref<'_, SlotTable> {
4317        Ref::map(self.inner.borrow(), |inner| &inner.table)
4318    }
4319
4320    pub(crate) fn borrow_mut(&self) -> RefMut<'_, SlotTable> {
4321        RefMut::map(self.inner.borrow_mut(), |inner| &mut inner.table)
4322    }
4323
4324    pub fn into_table(self: Rc<Self>) -> Result<SlotTable, NodeError> {
4325        if Rc::strong_count(&self) != 1 {
4326            return Err(NodeError::SlotHostUnavailable {
4327                operation: "SlotsHost::into_table",
4328                reason: "other host references are alive",
4329            });
4330        }
4331        self.take_table_for_transfer()
4332    }
4333
4334    fn take_table_for_transfer(&self) -> Result<SlotTable, NodeError> {
4335        let inner = self.inner.borrow();
4336        if inner.active_pass.is_some() {
4337            return Err(NodeError::SlotHostUnavailable {
4338                operation: "SlotsHost::into_table",
4339                reason: "slot pass is active",
4340            });
4341        }
4342        drop(inner);
4343        let mut inner = self.inner.borrow_mut();
4344        let mut lifecycle = std::mem::take(&mut inner.lifecycle);
4345        lifecycle.flush_pending_drops();
4346        if let Some(state) = inner.runtime_state.clone() {
4347            let host_key = self.storage_key();
4348            state.dispose_retained_subtrees_for_host(host_key, &mut inner.table, &mut lifecycle)?;
4349            state.clear_host(self);
4350            lifecycle.flush_pending_drops();
4351        }
4352        let taken = std::mem::take(&mut inner.table);
4353        self.storage_key.set(inner.table.storage_id());
4354        inner.runtime_state = None;
4355        inner.lifecycle = lifecycle;
4356        Ok(taken)
4357    }
4358
4359    pub fn reset(&self) -> Result<(), NodeError> {
4360        let inner = self.inner.borrow();
4361        if inner.active_pass.is_some() {
4362            return Err(NodeError::SlotHostUnavailable {
4363                operation: "SlotsHost::reset",
4364                reason: "slot pass is active",
4365            });
4366        }
4367        let runtime_state = inner.runtime_state.clone();
4368        drop(inner);
4369        let mut inner = self.inner.borrow_mut();
4370        let mut lifecycle = std::mem::take(&mut inner.lifecycle);
4371        if let Some(state) = runtime_state {
4372            let host_key = self.storage_key();
4373            state.dispose_retained_subtrees_for_host(host_key, &mut inner.table, &mut lifecycle)?;
4374            state.clear_host(self);
4375        }
4376        lifecycle.dispose_slot_table(&mut inner.table);
4377        inner.table = SlotTable::default();
4378        self.storage_key.set(inner.table.storage_id());
4379        inner.runtime_state = None;
4380        inner.lifecycle = slot::SlotLifecycleCoordinator::default();
4381        Ok(())
4382    }
4383
4384    pub(crate) fn abandon_after_apply_failure(&self) {
4385        let inner = self.inner.borrow();
4386        if inner.active_pass.is_some() {
4387            log::error!("cannot abandon SlotsHost during an active pass");
4388            return;
4389        }
4390        let runtime_state = inner.runtime_state.clone();
4391        drop(inner);
4392        let mut inner = self.inner.borrow_mut();
4393        let mut lifecycle = std::mem::take(&mut inner.lifecycle);
4394        if let Some(state) = runtime_state {
4395            let host_key = self.storage_key();
4396            state.abandon_retained_subtrees_for_host(host_key, &mut inner.table, &mut lifecycle);
4397        }
4398        lifecycle.dispose_slot_table(&mut inner.table);
4399        inner.table = SlotTable::default();
4400        self.storage_key.set(inner.table.storage_id());
4401        inner.runtime_state = None;
4402        inner.lifecycle = slot::SlotLifecycleCoordinator::default();
4403    }
4404
4405    pub(crate) fn debug_stats(&self) -> SlotTableDebugStats {
4406        let inner = self.inner.borrow();
4407        let local = inner.table.debug_stats();
4408        let lifecycle = inner.lifecycle.debug_stats();
4409        let retention = inner
4410            .runtime_state
4411            .clone()
4412            .map(|state| state.slot_retention_debug_stats(self))
4413            .unwrap_or_default();
4414        SlotTableDebugStats::from_parts(local, lifecycle, retention)
4415    }
4416
4417    pub(crate) fn debug_snapshot(&self) -> slot::SlotDebugSnapshot {
4418        let inner = self.inner.borrow();
4419        let mut snapshot = inner.table.debug_snapshot();
4420        if let Some(state) = inner.runtime_state.clone() {
4421            state.fill_slot_debug_snapshot(self, &mut snapshot);
4422        }
4423        snapshot
4424    }
4425
4426    pub(crate) fn begin_pass(&self, mode: slot::SlotPassMode) {
4427        let mut inner = self.inner.borrow_mut();
4428        if inner.active_pass.is_some() {
4429            log::error!("slot pass already active for host");
4430            return;
4431        }
4432        let mut state = slot::SlotWriteSessionState::default();
4433        state.reset_for_pass(mode);
4434        inner.active_pass = Some(ActivePassState { state });
4435    }
4436
4437    pub(crate) fn has_active_pass(&self) -> bool {
4438        self.inner.borrow().active_pass.is_some()
4439    }
4440
4441    pub(crate) fn try_push_branch_fold(&self, key: Key) -> Option<usize> {
4442        let mut inner = self.inner.try_borrow_mut().ok()?;
4443        let pass = inner.active_pass.as_mut()?;
4444        Some(pass.state.push_branch_fold(key))
4445    }
4446
4447    pub(crate) fn try_close_branch_fold(&self, token: usize) -> bool {
4448        let Ok(mut inner) = self.inner.try_borrow_mut() else {
4449            return false;
4450        };
4451        let Some(pass) = inner.active_pass.as_mut() else {
4452            return false;
4453        };
4454        pass.state.close_branch_fold(token);
4455        true
4456    }
4457
4458    pub(crate) fn abandon_active_pass(&self) {
4459        self.inner.borrow_mut().active_pass = None;
4460    }
4461
4462    pub(crate) fn with_write_session<R>(
4463        &self,
4464        f: impl FnOnce(&mut slot::SlotWriteSession<'_>) -> R,
4465    ) -> R {
4466        let mut inner = self.inner.borrow_mut();
4467        let SlotsHostInner {
4468            table,
4469            lifecycle,
4470            active_pass,
4471            ..
4472        } = &mut *inner;
4473        let active_pass = active_pass
4474            .as_mut()
4475            .expect("slot write session requires an active pass");
4476        let mut session = table.write_session(lifecycle, &mut active_pass.state);
4477        f(&mut session)
4478    }
4479
4480    pub(crate) fn with_table_and_lifecycle_mut<R>(
4481        &self,
4482        f: impl FnOnce(&mut SlotTable, &mut slot::SlotLifecycleCoordinator) -> R,
4483    ) -> R {
4484        let mut inner = self.inner.borrow_mut();
4485        let SlotsHostInner {
4486            table, lifecycle, ..
4487        } = &mut *inner;
4488        f(table, lifecycle)
4489    }
4490
4491    pub(crate) fn finish_pass(
4492        &self,
4493        applier: &mut dyn Applier,
4494    ) -> Result<FinishedSlotPass, NodeError> {
4495        let mut inner = self.inner.borrow_mut();
4496        let SlotsHostInner {
4497            table,
4498            lifecycle,
4499            active_pass: active_pass_slot,
4500            ..
4501        } = &mut *inner;
4502        let Some(mut active_pass) = active_pass_slot.take() else {
4503            return Ok(FinishedSlotPass::default());
4504        };
4505
4506        active_pass.state.flush_payload_location_refreshes(table);
4507
4508        #[cfg(debug_assertions)]
4509        if let Err(err) = active_pass.state.validate(table) {
4510            log::error!("slot writer invariant violation before finalize_pass: {err:?}");
4511            return Err(NodeError::SlotHostUnavailable {
4512                operation: "SlotsHost::finish_pass",
4513                reason: "slot writer invariant violation",
4514            });
4515        }
4516
4517        let detached_root_children = {
4518            let mut session = table.write_session(lifecycle, &mut active_pass.state);
4519            session.finalize_pass(applier)?
4520        };
4521
4522        Ok(FinishedSlotPass {
4523            outcome: SlotPassOutcome {
4524                compacted: active_pass.state.request_compaction,
4525                compact_anchor_registry_storage: active_pass
4526                    .state
4527                    .request_anchor_storage_compaction,
4528                compact_payload_storage: active_pass.state.request_payload_storage_compaction,
4529            },
4530            detached_root_children,
4531        })
4532    }
4533
4534    pub(crate) fn flush_pending_drops(&self) {
4535        self.inner.borrow_mut().lifecycle.flush_pending_drops();
4536    }
4537
4538    pub(crate) fn complete_pass_cleanup(&self, outcome: &SlotPassOutcome) {
4539        let mut inner = self.inner.borrow_mut();
4540        let SlotsHostInner {
4541            table,
4542            lifecycle,
4543            runtime_state,
4544            ..
4545        } = &mut *inner;
4546        lifecycle.flush_pending_drops();
4547        if outcome.compacted {
4548            table.compact_storage();
4549            lifecycle.compact_storage();
4550        }
4551        if let Some(state) = runtime_state.clone() {
4552            state.compact_table_identity_storage_for_host(
4553                self,
4554                table,
4555                outcome.compact_anchor_registry_storage,
4556                outcome.compact_payload_storage,
4557            );
4558        } else {
4559            if outcome.compact_anchor_registry_storage {
4560                table.compact_anchor_registry_storage(None);
4561            }
4562            if outcome.compact_payload_storage {
4563                table.compact_payload_anchor_registry_storage(None);
4564            }
4565        }
4566        table.assert_fast_integrity("slot pass cleanup");
4567        #[cfg(any(test, debug_assertions))]
4568        {
4569            table.debug_verify();
4570            if let Some(state) = runtime_state.clone() {
4571                state.debug_verify_host(self, table);
4572            }
4573        }
4574    }
4575}
4576
4577fn build_child_positions(children: &[NodeId]) -> HashMap<NodeId, usize> {
4578    let mut positions = HashMap::default();
4579    positions.reserve(children.len());
4580    for (index, &child) in children.iter().enumerate() {
4581        positions.insert(child, index);
4582    }
4583    positions
4584}
4585
4586fn refresh_child_positions(
4587    current: &[NodeId],
4588    positions: &mut HashMap<NodeId, usize>,
4589    start: usize,
4590    end: usize,
4591) {
4592    if current.is_empty() || start >= current.len() {
4593        return;
4594    }
4595    let end = end.min(current.len() - 1);
4596    for (offset, &child) in current[start..=end].iter().enumerate() {
4597        positions.insert(child, start + offset);
4598    }
4599}
4600
4601fn insert_child_into_diff_state(
4602    current: &mut ChildList,
4603    positions: &mut HashMap<NodeId, usize>,
4604    index: usize,
4605    child: NodeId,
4606) {
4607    let index = index.min(current.len());
4608    current.insert(index, child);
4609    refresh_child_positions(current, positions, index, current.len() - 1);
4610}
4611
4612fn move_child_in_diff_state(
4613    current: &mut ChildList,
4614    positions: &mut HashMap<NodeId, usize>,
4615    from_index: usize,
4616    target_index: usize,
4617) -> usize {
4618    let child = current.remove(from_index);
4619    let to_index = target_index.min(current.len());
4620    current.insert(to_index, child);
4621    refresh_child_positions(
4622        current,
4623        positions,
4624        from_index.min(to_index),
4625        from_index.max(to_index),
4626    );
4627    to_index
4628}
4629
4630pub(crate) use state::MutableStateInner;
4631pub use state::{
4632    MutableState, OwnedMutableState, SnapshotStateList, SnapshotStateMap, State,
4633    StateSubscriptionHold,
4634};
4635
4636fn hash_key<K: Hash>(key: &K) -> Key {
4637    let mut hasher = hash::default::new();
4638    key.hash(&mut hasher);
4639    hasher.finish()
4640}
4641
4642pub(crate) fn explicit_group_key_seed<K: Hash>(
4643    key: &K,
4644    caller: &'static std::panic::Location<'static>,
4645) -> slot::GroupKeySeed {
4646    let source_key = location_key(caller.file(), caller.line(), caller.column());
4647    let explicit_key = hash_key(key);
4648    slot::GroupKeySeed::keyed(source_key, explicit_key)
4649}
4650
4651#[cfg(test)]
4652#[path = "tests/mod.rs"]
4653mod tests;
4654
4655#[cfg(test)]
4656#[path = "tests/recursive_decrease_increase_test.rs"]
4657mod recursive_decrease_increase_test;
4658
4659pub mod collections;
4660pub mod hash;
4661
4662/// Where a test writes real files. Behind `test-helpers` so only a test build
4663/// of the workspace carries it.
4664#[cfg(any(test, feature = "test-helpers"))]
4665pub mod test_scratch;
4666#[cfg(any(test, feature = "test-helpers"))]
4667pub use test_scratch::test_scratch_dir;
4668
4669pub(crate) fn note_structural(reason: &str, parent_id: NodeId, child_id: NodeId) {
4670    if env_flag!("CRANPOSE_STRUCTURAL_DIAG") {
4671        eprintln!("[structural] {reason} parent={parent_id} child={child_id}");
4672    }
4673}
4674
4675pub(crate) fn note_structural_move(parent_id: NodeId, from_index: usize, to_index: usize) {
4676    if env_flag!("CRANPOSE_STRUCTURAL_DIAG") {
4677        eprintln!("[structural] move parent={parent_id} from={from_index} to={to_index}");
4678    }
4679}