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(|c| c.get())
205}
206
207/// Returns true if currently in an applied snapshot context.
208pub fn in_applied_snapshot() -> bool {
209    IN_APPLIED_SNAPSHOT.with(|c| c.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 state_for_effect = state.clone();
1302                let mut effect_opt = Some(effect);
1303                composer.register_side_effect(move || {
1304                    if let Some(effect) = effect_opt.take() {
1305                        let result = effect(DisposableEffectScope);
1306                        state_for_effect.update(|state| state.set_cleanup(result.into_cleanup()));
1307                    }
1308                });
1309            }
1310        });
1311    });
1312}
1313
1314/// Runs `effect` when this call site first enters composition, and again
1315/// whenever `keys` no longer equals the value it ran with last time; the
1316/// previous run's [`DisposableEffectScope::on_dispose`] cleanup, if any,
1317/// runs first, and also when the call site leaves composition entirely.
1318///
1319/// `keys` may be a tuple to depend on more than one value, matching Jetpack
1320/// Compose's `DisposableEffect(vararg keys)`.
1321#[allow(non_snake_case)]
1322#[track_caller]
1323pub fn DisposableEffect<K, F>(keys: K, effect: F)
1324where
1325    K: PartialEq + 'static,
1326    F: FnOnce(DisposableEffectScope) -> DisposableEffectResult + 'static,
1327{
1328    __disposable_effect_impl(crate::caller_location_key(), keys, effect);
1329}
1330
1331#[macro_export]
1332macro_rules! clone_captures {
1333    ($($alias:ident $(= $value:expr)?),+ $(,)?; $body:expr) => {{
1334        $(let $alias = $crate::clone_captures!(@clone $alias $(= $value)?);)+
1335        $body
1336    }};
1337    (@clone $alias:ident = $value:expr) => {
1338        ($value).clone()
1339    };
1340    (@clone $alias:ident) => {
1341        $alias.clone()
1342    };
1343}
1344
1345pub fn with_node_mut<N: Node + 'static, R>(
1346    id: NodeId,
1347    f: impl FnOnce(&mut N) -> R,
1348) -> Result<R, NodeError> {
1349    with_current_composer(|composer| composer.with_node_mut(id, f))
1350}
1351
1352pub fn push_parent(id: NodeId) {
1353    with_current_composer(|composer| composer.push_parent(id));
1354}
1355
1356pub fn pop_parent() {
1357    with_current_composer(|composer| composer.pop_parent());
1358}
1359
1360pub trait Node: Any {
1361    fn mount(&mut self) {}
1362    fn update(&mut self) {}
1363    fn unmount(&mut self) {}
1364    /// Adds `child` to this node's child list, returning whether the list
1365    /// actually changed. A node that already holds the child returns `false`:
1366    /// callers record a structural change from this answer, and a structural
1367    /// change re-lowers the whole subtree, so claiming one for a no-op costs a
1368    /// full rebuild per call.
1369    fn insert_child(&mut self, _child: NodeId) -> bool {
1370        false
1371    }
1372    /// Removes `child` from this node's child list, returning whether the list
1373    /// actually changed. Only this node can answer that: a caller inspecting
1374    /// the child's parent pointer gets it wrong when the child was reparented
1375    /// while still listed here.
1376    fn remove_child(&mut self, _child: NodeId) -> bool {
1377        false
1378    }
1379    fn move_child(&mut self, _from: usize, _to: usize) {}
1380    fn update_children(&mut self, _children: &[NodeId]) {}
1381    fn children(&self) -> Vec<NodeId> {
1382        Vec::new()
1383    }
1384    /// Copies child IDs into the provided scratch buffer without allocating a
1385    /// fresh container for every traversal.
1386    fn collect_children_into(&self, out: &mut SmallVec<[NodeId; 8]>) {
1387        out.clear();
1388        out.extend(self.children());
1389    }
1390    fn collect_owned_children_into(&self, out: &mut SmallVec<[NodeId; 8]>) {
1391        self.collect_children_into(out);
1392    }
1393    /// Called after the node is created to record its own ID.
1394    /// Useful for nodes that need to store their ID for later operations.
1395    fn set_node_id(&mut self, _id: NodeId) {}
1396    /// Called when this node is attached to a parent.
1397    /// Nodes with parent tracking should set their parent reference here.
1398    fn on_attached_to_parent(&mut self, _parent: NodeId) {}
1399    /// Called when this node is removed from its parent.
1400    /// Nodes with parent tracking should clear their parent reference here.
1401    fn on_removed_from_parent(&mut self) {}
1402    /// Get this node's parent ID (for nodes that track parents).
1403    /// Returns None if node has no parent or doesn't track parents.
1404    fn parent(&self) -> Option<NodeId> {
1405        None
1406    }
1407    /// Mark this node as needing layout (for nodes with dirty flags).
1408    /// Called during bubbling to propagate dirtiness up the tree.
1409    fn mark_needs_layout(&self) {}
1410    /// Check if this node needs layout (for nodes with dirty flags).
1411    fn needs_layout(&self) -> bool {
1412        false
1413    }
1414    /// Mark this node as needing measure (size may have changed).
1415    /// Called during bubbling when children are added/removed.
1416    fn mark_needs_measure(&self) {}
1417    /// Check if this node needs measure (for nodes with dirty flags).
1418    fn needs_measure(&self) -> bool {
1419        false
1420    }
1421    /// Mark this node as needing semantics recomputation.
1422    fn mark_needs_semantics(&self) {}
1423    /// Check if this node needs semantics recomputation.
1424    fn needs_semantics(&self) -> bool {
1425        false
1426    }
1427    /// Set parent reference for dirty flag bubbling ONLY.
1428    /// This is a minimal version of on_attached_to_parent that doesn't trigger
1429    /// registry updates or other side effects. Used during measurement when we
1430    /// need to establish parent connections for bubble_measure_dirty without
1431    /// causing the full attachment lifecycle.
1432    ///
1433    /// Default implementation uses the normal parent-attachment hook.
1434    fn set_parent_for_bubbling(&mut self, parent: NodeId) {
1435        self.on_attached_to_parent(parent);
1436    }
1437
1438    /// Returns a recycle pool key when this node supports shell reuse.
1439    fn recycle_key(&self) -> Option<TypeId> {
1440        None
1441    }
1442
1443    /// Bounds how many recyclable shells of this node type should be retained.
1444    fn recycle_pool_limit(&self) -> Option<usize> {
1445        None
1446    }
1447
1448    /// Clears live attachments before the node shell enters a recycle pool.
1449    fn prepare_for_recycle(&mut self) {}
1450
1451    /// Optionally provides a compact replacement box for this recycled shell.
1452    ///
1453    /// Returning `Some` lets nodes move pooled survivors onto fresh compact
1454    /// storage so the recycle pool does not pin large spike-era allocations.
1455    fn rehouse_for_recycle(&self) -> Option<Box<dyn Node>> {
1456        None
1457    }
1458
1459    /// Optionally moves a live node onto a fresh box during applier compaction.
1460    ///
1461    /// This is used after large-majority teardowns where a small surviving live
1462    /// tree can otherwise pin allocator pages from a much larger spike-era node
1463    /// population. Implementations must preserve the node's live state.
1464    fn rehouse_for_live_compaction(&mut self) -> Option<Box<dyn Node>> {
1465        None
1466    }
1467
1468    /// Returns the node-owned heap retained beyond the node's own box allocation.
1469    fn debug_heap_bytes(&self) -> usize {
1470        0
1471    }
1472}
1473
1474/// Unified API for bubbling layout dirty flags from a node to the root (Applier context).
1475///
1476/// This is the canonical function for dirty bubbling during the apply phase (structural changes).
1477/// Call this after mutations like insert/remove/move that happen during apply.
1478///
1479/// # Behavior
1480/// 1. Marks the starting node as needing layout
1481/// 2. Walks up the parent chain, marking each ancestor
1482/// 3. Stops when it reaches a node that's already dirty (O(1) optimization)
1483/// 4. Stops at the root (node with no parent)
1484///
1485/// # Performance
1486/// This function is O(height) in the worst case, but typically O(1) due to early exit
1487/// when encountering an already-dirty ancestor.
1488///
1489/// # Usage
1490/// - Call from composer mutations (insert/remove/move) during apply phase
1491/// - Call from applier-level operations that modify the tree structure
1492pub fn bubble_layout_dirty(applier: &mut dyn Applier, node_id: NodeId) {
1493    bubble_layout_dirty_applier(applier, node_id);
1494}
1495
1496/// Unified API for bubbling measure dirty flags from a node to the root (Applier context).
1497///
1498/// Call this when a node's size may have changed (children added/removed, modifier changed).
1499/// This ensures that measure_layout will increment the cache epoch and re-measure the subtree.
1500///
1501/// # Behavior
1502/// 1. Marks the starting node as needing measure
1503/// 2. Walks up the parent chain, marking each ancestor
1504/// 3. Stops when it reaches a node that's already dirty (O(1) optimization)
1505/// 4. Stops at the root (node with no parent)
1506pub fn bubble_measure_dirty(applier: &mut dyn Applier, node_id: NodeId) {
1507    bubble_measure_dirty_applier(applier, node_id);
1508}
1509
1510/// Unified API for bubbling semantics dirty flags from a node to the root (Applier context).
1511///
1512/// This mirrors [`bubble_layout_dirty`] but toggles semantics-specific dirty
1513/// flags instead of layout ones, allowing semantics updates to propagate during
1514/// the apply phase without forcing layout work.
1515pub fn bubble_semantics_dirty(applier: &mut dyn Applier, node_id: NodeId) {
1516    bubble_semantics_dirty_applier(applier, node_id);
1517}
1518
1519/// Schedules semantics bubbling for a node using the active composer if present.
1520///
1521/// This defers the work to the apply phase where we can safely mutate the
1522/// applier tree without re-entrantly borrowing the composer during composition.
1523pub fn queue_semantics_invalidation(node_id: NodeId) {
1524    let _ = composer_context::try_with_composer(|composer| {
1525        composer.enqueue_semantics_invalidation(node_id);
1526    });
1527}
1528
1529/// Unified API for bubbling layout dirty flags from a node to the root (Composer context).
1530///
1531/// This is the canonical function for dirty bubbling during composition (property changes).
1532/// Call this after property changes that happen during composition via with_node_mut.
1533///
1534/// # Behavior
1535/// 1. Marks the starting node as needing layout
1536/// 2. Walks up the parent chain, marking each ancestor
1537/// 3. Stops when it reaches a node that's already dirty (O(1) optimization)
1538/// 4. Stops at the root (node with no parent)
1539///
1540/// # Performance
1541/// This function is O(height) in the worst case, but typically O(1) due to early exit
1542/// when encountering an already-dirty ancestor.
1543///
1544/// # Type Requirements
1545/// The node type N must implement Node (which includes mark_needs_layout, parent, etc.).
1546/// Typically this will be LayoutNode or similar layout-aware node types.
1547///
1548/// # Usage
1549/// - Call from property setters during composition (e.g., set_modifier, set_measure_policy)
1550/// - Call from widget composition when layout-affecting state changes
1551pub fn bubble_layout_dirty_in_composer<N: Node + 'static>(node_id: NodeId) {
1552    bubble_layout_dirty_composer::<N>(node_id);
1553}
1554
1555/// Unified API for bubbling measure dirty flags from a node to the root during composition.
1556///
1557/// This queues a dirty-bubble command on the active composer so measure invalidation
1558/// runs during the apply phase, avoiding re-entrant applier borrows while widgets are
1559/// mutating nodes via `with_node_mut`.
1560pub fn bubble_measure_dirty_in_composer(node_id: NodeId) {
1561    with_current_composer(|composer| {
1562        composer.commands_mut().push(Command::BubbleDirty {
1563            node_id,
1564            bubble: DirtyBubble {
1565                layout: false,
1566                measure: true,
1567                semantics: false,
1568            },
1569        });
1570    });
1571}
1572
1573/// Unified API for bubbling semantics dirty flags from a node to the root (Composer context).
1574///
1575/// This mirrors [`bubble_layout_dirty_in_composer`] but routes through the semantics
1576/// dirty flag instead of the layout one. Modifier nodes can request semantics
1577/// invalidations without triggering measure/layout work, and the runtime can
1578/// query the root to determine whether the semantics tree needs rebuilding.
1579pub fn bubble_semantics_dirty_in_composer<N: Node + 'static>(node_id: NodeId) {
1580    bubble_semantics_dirty_composer::<N>(node_id);
1581}
1582
1583fn bubble_layout_dirty_applier(applier: &mut dyn Applier, mut node_id: NodeId) {
1584    if let Ok(node) = applier.get_mut(node_id) {
1585        node.mark_needs_layout();
1586    }
1587
1588    loop {
1589        let parent_id = match applier.get_mut(node_id) {
1590            Ok(node) => node.parent(),
1591            Err(_) => None,
1592        };
1593
1594        match parent_id {
1595            Some(pid) => {
1596                if let Ok(parent) = applier.get_mut(pid) {
1597                    let parent_already_dirty = parent.needs_layout();
1598                    if !parent_already_dirty {
1599                        parent.mark_needs_layout();
1600                    }
1601                    node_id = pid;
1602                } else {
1603                    break;
1604                }
1605            }
1606            None => break,
1607        }
1608    }
1609}
1610
1611fn bubble_measure_dirty_applier(applier: &mut dyn Applier, mut node_id: NodeId) {
1612    if let Ok(node) = applier.get_mut(node_id) {
1613        node.mark_needs_measure();
1614    }
1615
1616    loop {
1617        let parent_id = match applier.get_mut(node_id) {
1618            Ok(node) => node.parent(),
1619            Err(_) => None,
1620        };
1621
1622        match parent_id {
1623            Some(pid) => {
1624                if let Ok(parent) = applier.get_mut(pid) {
1625                    if !parent.needs_measure() {
1626                        parent.mark_needs_measure();
1627                    }
1628                    node_id = pid;
1629                } else {
1630                    break;
1631                }
1632            }
1633            None => {
1634                break;
1635            }
1636        }
1637    }
1638}
1639
1640fn bubble_semantics_dirty_applier(applier: &mut dyn Applier, mut node_id: NodeId) {
1641    if let Ok(node) = applier.get_mut(node_id) {
1642        node.mark_needs_semantics();
1643    }
1644
1645    loop {
1646        let parent_id = match applier.get_mut(node_id) {
1647            Ok(node) => node.parent(),
1648            Err(_) => None,
1649        };
1650
1651        match parent_id {
1652            Some(pid) => {
1653                if let Ok(parent) = applier.get_mut(pid) {
1654                    if !parent.needs_semantics() {
1655                        parent.mark_needs_semantics();
1656                    }
1657                    node_id = pid;
1658                } else {
1659                    break;
1660                }
1661            }
1662            None => break,
1663        }
1664    }
1665}
1666
1667fn bubble_layout_dirty_composer<N: Node + 'static>(mut node_id: NodeId) {
1668    let _ = with_node_mut(node_id, |node: &mut N| {
1669        node.mark_needs_layout();
1670    });
1671
1672    while let Ok(Some(pid)) = with_node_mut(node_id, |node: &mut N| node.parent()) {
1673        let parent_id = pid;
1674
1675        let advanced = with_node_mut(parent_id, |node: &mut N| {
1676            if !node.needs_layout() {
1677                node.mark_needs_layout();
1678            }
1679            true
1680        })
1681        .unwrap_or(false);
1682
1683        if advanced {
1684            node_id = parent_id;
1685        } else {
1686            break;
1687        }
1688    }
1689}
1690
1691fn bubble_semantics_dirty_composer<N: Node + 'static>(mut node_id: NodeId) {
1692    let _ = with_node_mut(node_id, |node: &mut N| {
1693        node.mark_needs_semantics();
1694    });
1695
1696    while let Ok(Some(pid)) = with_node_mut(node_id, |node: &mut N| node.parent()) {
1697        let parent_id = pid;
1698
1699        let advanced = with_node_mut(parent_id, |node: &mut N| {
1700            if !node.needs_semantics() {
1701                node.mark_needs_semantics();
1702            }
1703            true
1704        })
1705        .unwrap_or(false);
1706
1707        if advanced {
1708            node_id = parent_id;
1709        } else {
1710            break;
1711        }
1712    }
1713}
1714
1715impl dyn Node {
1716    pub fn as_any_mut(&mut self) -> &mut dyn Any {
1717        self
1718    }
1719}
1720
1721pub struct RecycledNode {
1722    stable_id: NodeId,
1723    node: Box<dyn Node>,
1724    warm_origin: bool,
1725}
1726
1727impl RecycledNode {
1728    fn new(stable_id: NodeId, node: Box<dyn Node>, warm_origin: bool) -> Self {
1729        let node = node.rehouse_for_recycle().unwrap_or(node);
1730        Self {
1731            stable_id,
1732            node,
1733            warm_origin,
1734        }
1735    }
1736
1737    fn from_shell(stable_id: NodeId, node: Box<dyn Node>, warm_origin: bool) -> Self {
1738        Self {
1739            stable_id,
1740            node,
1741            warm_origin,
1742        }
1743    }
1744
1745    pub fn stable_id(&self) -> NodeId {
1746        self.stable_id
1747    }
1748
1749    fn warm_origin(&self) -> bool {
1750        self.warm_origin
1751    }
1752
1753    fn set_warm_origin(&mut self, warm_origin: bool) {
1754        self.warm_origin = warm_origin;
1755    }
1756
1757    pub fn node_mut(&mut self) -> &mut dyn Node {
1758        self.node.as_mut()
1759    }
1760
1761    pub fn into_parts(self) -> (NodeId, Box<dyn Node>, bool) {
1762        (self.stable_id, self.node, self.warm_origin)
1763    }
1764}
1765
1766#[derive(Debug, Clone, PartialEq, Eq)]
1767pub struct RecycledNodeInsertion {
1768    pub id: NodeId,
1769    pub stable_id_reused: bool,
1770    pub fallback_error: Option<NodeError>,
1771}
1772
1773impl RecycledNodeInsertion {
1774    fn reused(stable_id: NodeId) -> Self {
1775        Self {
1776            id: stable_id,
1777            stable_id_reused: true,
1778            fallback_error: None,
1779        }
1780    }
1781
1782    fn fresh(id: NodeId, fallback_error: Option<NodeError>) -> Self {
1783        Self {
1784            id,
1785            stable_id_reused: false,
1786            fallback_error,
1787        }
1788    }
1789}
1790
1791pub trait Applier: Any {
1792    fn create(&mut self, node: Box<dyn Node>) -> NodeId;
1793    fn get_mut(&mut self, id: NodeId) -> Result<&mut dyn Node, NodeError>;
1794    fn remove(&mut self, id: NodeId) -> Result<(), NodeError>;
1795
1796    /// Records that `parent_id`'s child list changed structurally this frame
1797    /// (insert, remove, move, or reparent). Incremental scene consumers drain
1798    /// the recorded parents and re-patch those subtrees so removed nodes are
1799    /// evicted from a persistent render graph even when the frame's scene
1800    /// update is otherwise scoped to unrelated dirty nodes.
1801    fn record_structural_change(&mut self, _parent_id: NodeId) {}
1802
1803    /// Returns the current generation for a node index.
1804    /// Generation is incremented when an index is reused from the freelist,
1805    /// preventing stale slot entries from matching recycled nodes.
1806    fn node_generation(&self, id: NodeId) -> u32;
1807
1808    /// Inserts a node with a pre-assigned ID.
1809    ///
1810    /// This is used for virtual nodes whose IDs are allocated separately
1811    /// (e.g., via allocate_virtual_node_id()). Unlike `create()` which assigns
1812    /// a new ID, this method uses the provided ID.
1813    ///
1814    /// Returns Ok(()) if successful, or an error if the ID is already in use.
1815    fn insert_with_id(&mut self, id: NodeId, node: Box<dyn Node>) -> Result<(), NodeError>;
1816
1817    /// Reinserts a recycled node at its retained stable ID, or creates a fresh ID if that
1818    /// retained ID is no longer available.
1819    fn insert_recycled_node_or_create(
1820        &mut self,
1821        stable_id: NodeId,
1822        node: Box<dyn Node>,
1823    ) -> RecycledNodeInsertion {
1824        let id = self.create(node);
1825        RecycledNodeInsertion::fresh(id, Some(NodeError::AlreadyExists { id: stable_id }))
1826    }
1827
1828    fn as_any(&self) -> &dyn Any
1829    where
1830        Self: Sized,
1831    {
1832        self
1833    }
1834
1835    fn as_any_mut(&mut self) -> &mut dyn Any
1836    where
1837        Self: Sized,
1838    {
1839        self
1840    }
1841
1842    /// Trim trailing tombstones/unused capacity after structural changes.
1843    fn compact(&mut self) {}
1844
1845    /// Returns a previously recycled node shell and its stable ID for the requested concrete type.
1846    fn take_recycled_node(&mut self, _key: TypeId) -> Option<RecycledNode> {
1847        None
1848    }
1849
1850    /// Marks whether a reinserted recycled node originated from the warm recycle path.
1851    fn set_recycled_node_origin(&mut self, _id: NodeId, _warm_origin: bool) {}
1852
1853    /// Seeds a warm recyclable shell for future reuse without requiring a prior removal.
1854    fn seed_recycled_node_shell(
1855        &mut self,
1856        _key: TypeId,
1857        _recycle_pool_limit: Option<usize>,
1858        _shell: Box<dyn Node>,
1859    ) {
1860    }
1861
1862    /// Records that the current apply pass had to allocate a fresh recyclable shell for this type.
1863    fn record_fresh_recyclable_creation(&mut self, _key: TypeId) {}
1864
1865    /// Drops any recyclable shells that should not survive beyond the current apply pass.
1866    fn clear_recycled_nodes(&mut self) {}
1867}
1868
1869type TypedNodeUpdate = fn(&mut dyn Node, NodeId) -> Result<(), NodeError>;
1870type CommandCallback = Box<dyn FnOnce(&mut dyn Applier) -> Result<(), NodeError> + 'static>;
1871
1872#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1873pub(crate) struct DirtyBubble {
1874    layout: bool,
1875    measure: bool,
1876    semantics: bool,
1877}
1878
1879impl DirtyBubble {
1880    pub(crate) const LAYOUT_AND_MEASURE: Self = Self {
1881        layout: true,
1882        measure: true,
1883        semantics: false,
1884    };
1885
1886    pub(crate) const SEMANTICS: Self = Self {
1887        layout: false,
1888        measure: false,
1889        semantics: true,
1890    };
1891
1892    fn apply(self, applier: &mut dyn Applier, node_id: NodeId) {
1893        if self.layout {
1894            bubble_layout_dirty(applier, node_id);
1895        }
1896        if self.measure {
1897            bubble_measure_dirty(applier, node_id);
1898        }
1899        if self.semantics {
1900            bubble_semantics_dirty(applier, node_id);
1901        }
1902    }
1903}
1904
1905pub(crate) enum Command {
1906    BubbleDirty {
1907        node_id: NodeId,
1908        bubble: DirtyBubble,
1909    },
1910    UpdateTypedNode {
1911        id: NodeId,
1912        updater: TypedNodeUpdate,
1913    },
1914    RemoveNode {
1915        id: NodeId,
1916    },
1917    MountNode {
1918        id: NodeId,
1919    },
1920    AttachChild {
1921        parent_id: NodeId,
1922        child_id: NodeId,
1923        insert_index: Option<usize>,
1924        bubble: DirtyBubble,
1925    },
1926    InsertChild {
1927        parent_id: NodeId,
1928        child_id: NodeId,
1929        appended_index: usize,
1930        insert_index: usize,
1931        bubble: DirtyBubble,
1932    },
1933    MoveChild {
1934        parent_id: NodeId,
1935        from_index: usize,
1936        to_index: usize,
1937        bubble: DirtyBubble,
1938    },
1939    RemoveChild {
1940        parent_id: NodeId,
1941        child_id: NodeId,
1942    },
1943    DetachChild {
1944        parent_id: NodeId,
1945        child_id: NodeId,
1946    },
1947    SyncChildren {
1948        parent_id: NodeId,
1949        expected_children: ChildList,
1950    },
1951    Callback(CommandCallback),
1952}
1953
1954#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1955struct DeferredChildCleanup {
1956    child_id: NodeId,
1957    generation: u32,
1958    removed_from_parent: bool,
1959}
1960
1961#[derive(Default)]
1962struct DeferredChildCleanupQueue {
1963    pending: Vec<DeferredChildCleanup>,
1964    preserved: Vec<(NodeId, u32)>,
1965}
1966
1967impl DeferredChildCleanupQueue {
1968    fn push(&mut self, child_id: NodeId, generation: u32, removed_from_parent: bool) {
1969        if self
1970            .preserved
1971            .iter()
1972            .any(|&(preserved_id, preserved_generation)| {
1973                preserved_id == child_id && preserved_generation == generation
1974            })
1975        {
1976            return;
1977        }
1978        self.pending.push(DeferredChildCleanup {
1979            child_id,
1980            generation,
1981            removed_from_parent,
1982        });
1983    }
1984
1985    fn preserve(&mut self, child_id: NodeId, generation: u32) {
1986        if !self
1987            .preserved
1988            .iter()
1989            .any(|&(preserved_id, preserved_generation)| {
1990                preserved_id == child_id && preserved_generation == generation
1991            })
1992        {
1993            self.preserved.push((child_id, generation));
1994        }
1995        self.pending
1996            .retain(|cleanup| cleanup.child_id != child_id || cleanup.generation != generation);
1997    }
1998
1999    fn flush(self, applier: &mut dyn Applier) -> Result<(), NodeError> {
2000        for cleanup in self.pending {
2001            cleanup_detached_child(applier, cleanup)?;
2002        }
2003        Ok(())
2004    }
2005}
2006
2007impl Command {
2008    pub(crate) fn update_node<N: Node + 'static>(id: NodeId) -> Self {
2009        Self::UpdateTypedNode {
2010            id,
2011            updater: update_typed_node::<N>,
2012        }
2013    }
2014
2015    pub(crate) fn callback(
2016        callback: impl FnOnce(&mut dyn Applier) -> Result<(), NodeError> + 'static,
2017    ) -> Self {
2018        Self::Callback(Box::new(callback))
2019    }
2020
2021    pub(crate) fn apply(self, applier: &mut dyn Applier) -> Result<(), NodeError> {
2022        let mut deferred_cleanup = DeferredChildCleanupQueue::default();
2023        self.apply_with_cleanup(applier, &mut deferred_cleanup)?;
2024        deferred_cleanup.flush(applier)
2025    }
2026
2027    fn apply_with_cleanup(
2028        self,
2029        applier: &mut dyn Applier,
2030        deferred_cleanup: &mut DeferredChildCleanupQueue,
2031    ) -> Result<(), NodeError> {
2032        match self {
2033            Self::BubbleDirty { node_id, bubble } => {
2034                bubble.apply(applier, node_id);
2035                Ok(())
2036            }
2037            Self::UpdateTypedNode { id, updater } => {
2038                let node = match applier.get_mut(id) {
2039                    Ok(node) => node,
2040                    Err(NodeError::Missing { .. }) => return Ok(()),
2041                    Err(err) => return Err(err),
2042                };
2043                updater(node, id)
2044            }
2045            Self::RemoveNode { id } => {
2046                if let Ok(node) = applier.get_mut(id) {
2047                    node.unmount();
2048                }
2049                match applier.remove(id) {
2050                    Ok(()) | Err(NodeError::Missing { .. }) => Ok(()),
2051                    Err(err) => Err(err),
2052                }
2053            }
2054            Self::MountNode { id } => {
2055                let node = match applier.get_mut(id) {
2056                    Ok(node) => node,
2057                    Err(NodeError::Missing { .. }) => return Ok(()),
2058                    Err(err) => return Err(err),
2059                };
2060                node.set_node_id(id);
2061                node.mount();
2062                Ok(())
2063            }
2064            Self::AttachChild {
2065                parent_id,
2066                child_id,
2067                insert_index,
2068                bubble,
2069            } => {
2070                attach_child_at(applier, parent_id, child_id, insert_index, bubble);
2071                Ok(())
2072            }
2073            Self::InsertChild {
2074                parent_id,
2075                child_id,
2076                appended_index,
2077                insert_index,
2078                bubble,
2079            } => {
2080                insert_child_with_reparenting(applier, parent_id, child_id);
2081                bubble.apply(applier, parent_id);
2082                if insert_index != appended_index
2083                    && let Ok(parent_node) = applier.get_mut(parent_id)
2084                {
2085                    parent_node.move_child(appended_index, insert_index);
2086                }
2087                Ok(())
2088            }
2089            Self::MoveChild {
2090                parent_id,
2091                from_index,
2092                to_index,
2093                bubble,
2094            } => {
2095                if let Ok(parent_node) = applier.get_mut(parent_id) {
2096                    parent_node.move_child(from_index, to_index);
2097                }
2098                bubble.apply(applier, parent_id);
2099                note_structural_move(parent_id, from_index, to_index);
2100                applier.record_structural_change(parent_id);
2101                Ok(())
2102            }
2103            Self::RemoveChild {
2104                parent_id,
2105                child_id,
2106            } => apply_remove_child(applier, parent_id, child_id, deferred_cleanup),
2107            Self::DetachChild {
2108                parent_id,
2109                child_id,
2110            } => {
2111                let generation = applier.node_generation(child_id);
2112                detach_child_from_parent(applier, parent_id, child_id)?;
2113                deferred_cleanup.preserve(child_id, generation);
2114                Ok(())
2115            }
2116            Self::SyncChildren {
2117                parent_id,
2118                expected_children,
2119            } => sync_children(applier, parent_id, &expected_children, deferred_cleanup),
2120            Self::Callback(callback) => callback(applier),
2121        }
2122    }
2123}
2124
2125const COMMAND_CHUNK_CAPACITY: usize = 1024;
2126const COMMAND_FLUSH_THRESHOLD: usize = COMMAND_CHUNK_CAPACITY * 4;
2127type ChildList = SmallVec<[NodeId; 4]>;
2128const SMALL_CHILD_SYNC_LINEAR_THRESHOLD: usize = 8;
2129
2130#[derive(Copy, Clone)]
2131enum CommandTag {
2132    BubbleDirty,
2133    UpdateTypedNode,
2134    RemoveNode,
2135    MountNode,
2136    AttachChild,
2137    InsertChild,
2138    MoveChild,
2139    RemoveChild,
2140    DetachChild,
2141    SyncChildren,
2142    Callback,
2143}
2144
2145impl CommandTag {
2146    fn label(self) -> &'static str {
2147        match self {
2148            Self::BubbleDirty => "BubbleDirty",
2149            Self::UpdateTypedNode => "UpdateTypedNode",
2150            Self::RemoveNode => "RemoveNode",
2151            Self::MountNode => "MountNode",
2152            Self::AttachChild => "AttachChild",
2153            Self::InsertChild => "InsertChild",
2154            Self::MoveChild => "MoveChild",
2155            Self::RemoveChild => "RemoveChild",
2156            Self::DetachChild => "DetachChild",
2157            Self::SyncChildren => "SyncChildren",
2158            Self::Callback => "Callback",
2159        }
2160    }
2161}
2162
2163#[derive(Copy, Clone)]
2164struct BubbleDirtyCommand {
2165    node_id: NodeId,
2166    bubble: DirtyBubble,
2167}
2168
2169#[derive(Copy, Clone)]
2170struct UpdateTypedNodeCommand {
2171    id: NodeId,
2172    updater: TypedNodeUpdate,
2173}
2174
2175#[derive(Copy, Clone)]
2176struct AttachChildCommand {
2177    parent_id: NodeId,
2178    child_id: NodeId,
2179    insert_index: Option<usize>,
2180    bubble: DirtyBubble,
2181}
2182
2183#[derive(Copy, Clone)]
2184struct InsertChildCommand {
2185    parent_id: NodeId,
2186    child_id: NodeId,
2187    appended_index: usize,
2188    insert_index: usize,
2189    bubble: DirtyBubble,
2190}
2191
2192#[derive(Copy, Clone)]
2193struct MoveChildCommand {
2194    parent_id: NodeId,
2195    from_index: usize,
2196    to_index: usize,
2197    bubble: DirtyBubble,
2198}
2199
2200#[derive(Copy, Clone)]
2201struct RemoveChildCommand {
2202    parent_id: NodeId,
2203    child_id: NodeId,
2204}
2205
2206#[derive(Copy, Clone)]
2207struct DetachChildCommand {
2208    parent_id: NodeId,
2209    child_id: NodeId,
2210}
2211
2212struct SyncChildrenCommand {
2213    parent_id: NodeId,
2214    child_start: usize,
2215    child_len: usize,
2216}
2217
2218#[derive(Default)]
2219struct CommandQueue {
2220    chunks: Vec<Vec<CommandTag>>,
2221    len: usize,
2222    bubble_dirty: Vec<BubbleDirtyCommand>,
2223    update_typed_nodes: Vec<UpdateTypedNodeCommand>,
2224    remove_nodes: Vec<NodeId>,
2225    mount_nodes: Vec<NodeId>,
2226    attach_children: Vec<AttachChildCommand>,
2227    insert_children: Vec<InsertChildCommand>,
2228    move_children: Vec<MoveChildCommand>,
2229    remove_children: Vec<RemoveChildCommand>,
2230    detach_children: Vec<DetachChildCommand>,
2231    sync_children: Vec<SyncChildrenCommand>,
2232    sync_child_ids: Vec<NodeId>,
2233    callbacks: Vec<CommandCallback>,
2234}
2235
2236impl CommandQueue {
2237    fn push_tag(&mut self, tag: CommandTag) {
2238        let needs_chunk = self
2239            .chunks
2240            .last()
2241            .map(|chunk| chunk.len() == chunk.capacity())
2242            .unwrap_or(true);
2243        if needs_chunk {
2244            self.chunks.push(Vec::with_capacity(COMMAND_CHUNK_CAPACITY));
2245        }
2246        if let Some(chunk) = self.chunks.last_mut() {
2247            chunk.push(tag);
2248            self.len += 1;
2249        }
2250    }
2251
2252    fn push(&mut self, command: Command) {
2253        match command {
2254            Command::BubbleDirty { node_id, bubble } => {
2255                self.bubble_dirty
2256                    .push(BubbleDirtyCommand { node_id, bubble });
2257                self.push_tag(CommandTag::BubbleDirty);
2258            }
2259            Command::UpdateTypedNode { id, updater } => {
2260                self.update_typed_nodes
2261                    .push(UpdateTypedNodeCommand { id, updater });
2262                self.push_tag(CommandTag::UpdateTypedNode);
2263            }
2264            Command::RemoveNode { id } => {
2265                self.remove_nodes.push(id);
2266                self.push_tag(CommandTag::RemoveNode);
2267            }
2268            Command::MountNode { id } => {
2269                self.mount_nodes.push(id);
2270                self.push_tag(CommandTag::MountNode);
2271            }
2272            Command::AttachChild {
2273                parent_id,
2274                child_id,
2275                insert_index,
2276                bubble,
2277            } => {
2278                self.attach_children.push(AttachChildCommand {
2279                    parent_id,
2280                    child_id,
2281                    insert_index,
2282                    bubble,
2283                });
2284                self.push_tag(CommandTag::AttachChild);
2285            }
2286            Command::InsertChild {
2287                parent_id,
2288                child_id,
2289                appended_index,
2290                insert_index,
2291                bubble,
2292            } => {
2293                self.insert_children.push(InsertChildCommand {
2294                    parent_id,
2295                    child_id,
2296                    appended_index,
2297                    insert_index,
2298                    bubble,
2299                });
2300                self.push_tag(CommandTag::InsertChild);
2301            }
2302            Command::MoveChild {
2303                parent_id,
2304                from_index,
2305                to_index,
2306                bubble,
2307            } => {
2308                self.move_children.push(MoveChildCommand {
2309                    parent_id,
2310                    from_index,
2311                    to_index,
2312                    bubble,
2313                });
2314                self.push_tag(CommandTag::MoveChild);
2315            }
2316            Command::RemoveChild {
2317                parent_id,
2318                child_id,
2319            } => {
2320                self.remove_children.push(RemoveChildCommand {
2321                    parent_id,
2322                    child_id,
2323                });
2324                self.push_tag(CommandTag::RemoveChild);
2325            }
2326            Command::DetachChild {
2327                parent_id,
2328                child_id,
2329            } => {
2330                self.detach_children.push(DetachChildCommand {
2331                    parent_id,
2332                    child_id,
2333                });
2334                self.push_tag(CommandTag::DetachChild);
2335            }
2336            Command::SyncChildren {
2337                parent_id,
2338                expected_children,
2339            } => {
2340                let child_start = self.sync_child_ids.len();
2341                let child_len = expected_children.len();
2342                self.sync_child_ids.extend(expected_children);
2343                self.sync_children.push(SyncChildrenCommand {
2344                    parent_id,
2345                    child_start,
2346                    child_len,
2347                });
2348                self.push_tag(CommandTag::SyncChildren);
2349            }
2350            Command::Callback(callback) => {
2351                self.callbacks.push(callback);
2352                self.push_tag(CommandTag::Callback);
2353            }
2354        }
2355    }
2356
2357    fn len(&self) -> usize {
2358        self.len
2359    }
2360
2361    fn capacity(&self) -> usize {
2362        self.chunks.iter().map(Vec::capacity).sum()
2363    }
2364
2365    fn payload_len_bytes(&self) -> usize {
2366        self.bubble_dirty
2367            .len()
2368            .saturating_mul(std::mem::size_of::<BubbleDirtyCommand>())
2369            .saturating_add(
2370                self.update_typed_nodes
2371                    .len()
2372                    .saturating_mul(std::mem::size_of::<UpdateTypedNodeCommand>()),
2373            )
2374            .saturating_add(
2375                self.remove_nodes
2376                    .len()
2377                    .saturating_mul(std::mem::size_of::<NodeId>()),
2378            )
2379            .saturating_add(
2380                self.mount_nodes
2381                    .len()
2382                    .saturating_mul(std::mem::size_of::<NodeId>()),
2383            )
2384            .saturating_add(
2385                self.attach_children
2386                    .len()
2387                    .saturating_mul(std::mem::size_of::<AttachChildCommand>()),
2388            )
2389            .saturating_add(
2390                self.insert_children
2391                    .len()
2392                    .saturating_mul(std::mem::size_of::<InsertChildCommand>()),
2393            )
2394            .saturating_add(
2395                self.move_children
2396                    .len()
2397                    .saturating_mul(std::mem::size_of::<MoveChildCommand>()),
2398            )
2399            .saturating_add(
2400                self.remove_children
2401                    .len()
2402                    .saturating_mul(std::mem::size_of::<RemoveChildCommand>()),
2403            )
2404            .saturating_add(
2405                self.detach_children
2406                    .len()
2407                    .saturating_mul(std::mem::size_of::<DetachChildCommand>()),
2408            )
2409            .saturating_add(
2410                self.sync_children
2411                    .len()
2412                    .saturating_mul(std::mem::size_of::<SyncChildrenCommand>()),
2413            )
2414            .saturating_add(
2415                self.sync_child_ids
2416                    .len()
2417                    .saturating_mul(std::mem::size_of::<NodeId>()),
2418            )
2419            .saturating_add(
2420                self.callbacks
2421                    .len()
2422                    .saturating_mul(std::mem::size_of::<CommandCallback>()),
2423            )
2424    }
2425
2426    fn payload_capacity_bytes(&self) -> usize {
2427        self.bubble_dirty
2428            .capacity()
2429            .saturating_mul(std::mem::size_of::<BubbleDirtyCommand>())
2430            .saturating_add(
2431                self.update_typed_nodes
2432                    .capacity()
2433                    .saturating_mul(std::mem::size_of::<UpdateTypedNodeCommand>()),
2434            )
2435            .saturating_add(
2436                self.remove_nodes
2437                    .capacity()
2438                    .saturating_mul(std::mem::size_of::<NodeId>()),
2439            )
2440            .saturating_add(
2441                self.mount_nodes
2442                    .capacity()
2443                    .saturating_mul(std::mem::size_of::<NodeId>()),
2444            )
2445            .saturating_add(
2446                self.attach_children
2447                    .capacity()
2448                    .saturating_mul(std::mem::size_of::<AttachChildCommand>()),
2449            )
2450            .saturating_add(
2451                self.insert_children
2452                    .capacity()
2453                    .saturating_mul(std::mem::size_of::<InsertChildCommand>()),
2454            )
2455            .saturating_add(
2456                self.move_children
2457                    .capacity()
2458                    .saturating_mul(std::mem::size_of::<MoveChildCommand>()),
2459            )
2460            .saturating_add(
2461                self.remove_children
2462                    .capacity()
2463                    .saturating_mul(std::mem::size_of::<RemoveChildCommand>()),
2464            )
2465            .saturating_add(
2466                self.detach_children
2467                    .capacity()
2468                    .saturating_mul(std::mem::size_of::<DetachChildCommand>()),
2469            )
2470            .saturating_add(
2471                self.sync_children
2472                    .capacity()
2473                    .saturating_mul(std::mem::size_of::<SyncChildrenCommand>()),
2474            )
2475            .saturating_add(
2476                self.sync_child_ids
2477                    .capacity()
2478                    .saturating_mul(std::mem::size_of::<NodeId>()),
2479            )
2480            .saturating_add(
2481                self.callbacks
2482                    .capacity()
2483                    .saturating_mul(std::mem::size_of::<CommandCallback>()),
2484            )
2485    }
2486
2487    fn apply(self, applier: &mut dyn Applier) -> Result<(), NodeError> {
2488        let mut bubble_dirty = self.bubble_dirty.into_iter();
2489        let mut update_typed_nodes = self.update_typed_nodes.into_iter();
2490        let mut remove_nodes = self.remove_nodes.into_iter();
2491        let mut mount_nodes = self.mount_nodes.into_iter();
2492        let mut attach_children = self.attach_children.into_iter();
2493        let mut insert_children = self.insert_children.into_iter();
2494        let mut move_children = self.move_children.into_iter();
2495        let mut remove_children = self.remove_children.into_iter();
2496        let mut detach_children = self.detach_children.into_iter();
2497        let mut sync_children_commands = self.sync_children.into_iter();
2498        let sync_child_ids = self.sync_child_ids;
2499        let mut callbacks = self.callbacks.into_iter();
2500        let mut deferred_cleanup = DeferredChildCleanupQueue::default();
2501
2502        for chunk in self.chunks {
2503            for tag in chunk {
2504                match tag {
2505                    CommandTag::BubbleDirty => {
2506                        let BubbleDirtyCommand { node_id, bubble } =
2507                            next_command_payload(&mut bubble_dirty, tag)?;
2508                        Command::BubbleDirty { node_id, bubble }
2509                            .apply_with_cleanup(applier, &mut deferred_cleanup)?;
2510                    }
2511                    CommandTag::UpdateTypedNode => {
2512                        let UpdateTypedNodeCommand { id, updater } =
2513                            next_command_payload(&mut update_typed_nodes, tag)?;
2514                        Command::UpdateTypedNode { id, updater }
2515                            .apply_with_cleanup(applier, &mut deferred_cleanup)?;
2516                    }
2517                    CommandTag::RemoveNode => {
2518                        let id = next_command_payload(&mut remove_nodes, tag)?;
2519                        Command::RemoveNode { id }
2520                            .apply_with_cleanup(applier, &mut deferred_cleanup)?;
2521                    }
2522                    CommandTag::MountNode => {
2523                        let id = next_command_payload(&mut mount_nodes, tag)?;
2524                        Command::MountNode { id }
2525                            .apply_with_cleanup(applier, &mut deferred_cleanup)?;
2526                    }
2527                    CommandTag::AttachChild => {
2528                        let AttachChildCommand {
2529                            parent_id,
2530                            child_id,
2531                            insert_index,
2532                            bubble,
2533                        } = next_command_payload(&mut attach_children, tag)?;
2534                        Command::AttachChild {
2535                            parent_id,
2536                            child_id,
2537                            insert_index,
2538                            bubble,
2539                        }
2540                        .apply_with_cleanup(applier, &mut deferred_cleanup)?;
2541                    }
2542                    CommandTag::InsertChild => {
2543                        let InsertChildCommand {
2544                            parent_id,
2545                            child_id,
2546                            appended_index,
2547                            insert_index,
2548                            bubble,
2549                        } = next_command_payload(&mut insert_children, tag)?;
2550                        Command::InsertChild {
2551                            parent_id,
2552                            child_id,
2553                            appended_index,
2554                            insert_index,
2555                            bubble,
2556                        }
2557                        .apply_with_cleanup(applier, &mut deferred_cleanup)?;
2558                    }
2559                    CommandTag::MoveChild => {
2560                        let MoveChildCommand {
2561                            parent_id,
2562                            from_index,
2563                            to_index,
2564                            bubble,
2565                        } = next_command_payload(&mut move_children, tag)?;
2566                        Command::MoveChild {
2567                            parent_id,
2568                            from_index,
2569                            to_index,
2570                            bubble,
2571                        }
2572                        .apply_with_cleanup(applier, &mut deferred_cleanup)?;
2573                    }
2574                    CommandTag::RemoveChild => {
2575                        let RemoveChildCommand {
2576                            parent_id,
2577                            child_id,
2578                        } = next_command_payload(&mut remove_children, tag)?;
2579                        Command::RemoveChild {
2580                            parent_id,
2581                            child_id,
2582                        }
2583                        .apply_with_cleanup(applier, &mut deferred_cleanup)?;
2584                    }
2585                    CommandTag::DetachChild => {
2586                        let DetachChildCommand {
2587                            parent_id,
2588                            child_id,
2589                        } = next_command_payload(&mut detach_children, tag)?;
2590                        Command::DetachChild {
2591                            parent_id,
2592                            child_id,
2593                        }
2594                        .apply_with_cleanup(applier, &mut deferred_cleanup)?;
2595                    }
2596                    CommandTag::SyncChildren => {
2597                        let SyncChildrenCommand {
2598                            parent_id,
2599                            child_start,
2600                            child_len,
2601                        } = next_command_payload(&mut sync_children_commands, tag)?;
2602                        let child_end = child_start
2603                            .checked_add(child_len)
2604                            .ok_or_else(|| command_payload_error(tag))?;
2605                        let expected_children = sync_child_ids
2606                            .get(child_start..child_end)
2607                            .ok_or_else(|| command_payload_error(tag))?;
2608                        sync_children(
2609                            applier,
2610                            parent_id,
2611                            expected_children,
2612                            &mut deferred_cleanup,
2613                        )?;
2614                    }
2615                    CommandTag::Callback => {
2616                        let callback = next_command_payload(&mut callbacks, tag)?;
2617                        Command::Callback(callback)
2618                            .apply_with_cleanup(applier, &mut deferred_cleanup)?;
2619                    }
2620                }
2621            }
2622        }
2623
2624        debug_assert!(bubble_dirty.next().is_none());
2625        debug_assert!(update_typed_nodes.next().is_none());
2626        debug_assert!(remove_nodes.next().is_none());
2627        debug_assert!(mount_nodes.next().is_none());
2628        debug_assert!(attach_children.next().is_none());
2629        debug_assert!(insert_children.next().is_none());
2630        debug_assert!(move_children.next().is_none());
2631        debug_assert!(remove_children.next().is_none());
2632        debug_assert!(detach_children.next().is_none());
2633        debug_assert!(sync_children_commands.next().is_none());
2634        debug_assert!(callbacks.next().is_none());
2635        deferred_cleanup.flush(applier)
2636    }
2637}
2638
2639fn command_payload_error(tag: CommandTag) -> NodeError {
2640    NodeError::MalformedCommandPayload { tag: tag.label() }
2641}
2642
2643fn next_command_payload<T>(
2644    payloads: &mut impl Iterator<Item = T>,
2645    tag: CommandTag,
2646) -> Result<T, NodeError> {
2647    payloads.next().ok_or_else(|| command_payload_error(tag))
2648}
2649
2650fn update_typed_node<N: Node + 'static>(node: &mut dyn Node, id: NodeId) -> Result<(), NodeError> {
2651    let typed = node
2652        .as_any_mut()
2653        .downcast_mut::<N>()
2654        .ok_or(NodeError::TypeMismatch {
2655            id,
2656            expected: std::any::type_name::<N>(),
2657        })?;
2658    typed.update();
2659    Ok(())
2660}
2661
2662fn attach_child_at(
2663    applier: &mut dyn Applier,
2664    parent_id: NodeId,
2665    child_id: NodeId,
2666    insert_index: Option<usize>,
2667    bubble: DirtyBubble,
2668) {
2669    if insert_child_with_reparenting(applier, parent_id, child_id) {
2670        if let Some(target) = insert_index {
2671            move_appended_child_to(applier, parent_id, target);
2672        }
2673        bubble.apply(applier, parent_id);
2674    } else if let Ok(child) = applier.get_mut(child_id) {
2675        let dirty_bubble = DirtyBubble {
2676            layout: child.needs_layout(),
2677            measure: child.needs_measure(),
2678            semantics: false,
2679        };
2680        dirty_bubble.apply(applier, parent_id);
2681    }
2682}
2683
2684fn move_appended_child_to(applier: &mut dyn Applier, parent_id: NodeId, target: usize) {
2685    let Ok(parent_node) = applier.get_mut(parent_id) else {
2686        return;
2687    };
2688    let mut owned: SmallVec<[NodeId; 8]> = SmallVec::new();
2689    parent_node.collect_owned_children_into(&mut owned);
2690    let appended_index = owned.len().saturating_sub(1);
2691    if target < appended_index {
2692        parent_node.move_child(appended_index, target);
2693        note_structural_move(parent_id, appended_index, target);
2694    }
2695}
2696
2697fn insert_child_with_reparenting(
2698    applier: &mut dyn Applier,
2699    parent_id: NodeId,
2700    child_id: NodeId,
2701) -> bool {
2702    if parent_id == child_id {
2703        debug_assert_ne!(
2704            parent_id, child_id,
2705            "a node cannot be attached as its own child"
2706        );
2707        return false;
2708    }
2709
2710    let old_parent = applier
2711        .get_mut(child_id)
2712        .ok()
2713        .and_then(|node| node.parent());
2714    if let Some(old_parent_id) = old_parent
2715        && old_parent_id != parent_id
2716    {
2717        let removed = applier
2718            .get_mut(old_parent_id)
2719            .is_ok_and(|old_parent_node| old_parent_node.remove_child(child_id));
2720        if let Ok(child_node) = applier.get_mut(child_id) {
2721            child_node.on_removed_from_parent();
2722        }
2723        if removed {
2724            bubble_layout_dirty(applier, old_parent_id);
2725            bubble_measure_dirty(applier, old_parent_id);
2726            note_structural("reparent-detach", old_parent_id, child_id);
2727            applier.record_structural_change(old_parent_id);
2728        }
2729    }
2730
2731    let inserted = applier
2732        .get_mut(parent_id)
2733        .is_ok_and(|parent_node| parent_node.insert_child(child_id));
2734    if inserted {
2735        note_structural("attach", parent_id, child_id);
2736        applier.record_structural_change(parent_id);
2737    }
2738    if let Ok(child_node) = applier.get_mut(child_id) {
2739        child_node.on_attached_to_parent(parent_id);
2740    }
2741    inserted
2742}
2743
2744fn apply_remove_child(
2745    applier: &mut dyn Applier,
2746    parent_id: NodeId,
2747    child_id: NodeId,
2748    deferred_cleanup: &mut DeferredChildCleanupQueue,
2749) -> Result<(), NodeError> {
2750    detach_child_from_parent(applier, parent_id, child_id)?;
2751
2752    let generation = applier.node_generation(child_id);
2753    let removed_from_parent = if let Ok(node) = applier.get_mut(child_id) {
2754        node.parent().is_none()
2755    } else {
2756        return Ok(());
2757    };
2758    deferred_cleanup.push(child_id, generation, removed_from_parent);
2759    Ok(())
2760}
2761
2762fn detach_child_from_parent(
2763    applier: &mut dyn Applier,
2764    parent_id: NodeId,
2765    child_id: NodeId,
2766) -> Result<(), NodeError> {
2767    let removed = applier
2768        .get_mut(parent_id)
2769        .is_ok_and(|parent_node| parent_node.remove_child(child_id));
2770    if removed {
2771        bubble_layout_dirty(applier, parent_id);
2772        bubble_measure_dirty(applier, parent_id);
2773        note_structural("detach", parent_id, child_id);
2774        applier.record_structural_change(parent_id);
2775    }
2776
2777    if let Ok(node) = applier.get_mut(child_id) {
2778        match node.parent() {
2779            Some(existing_parent_id) if existing_parent_id == parent_id => {
2780                node.on_removed_from_parent();
2781            }
2782            None => {}
2783            Some(_) => return Ok(()),
2784        }
2785    } else {
2786        return Ok(());
2787    }
2788
2789    Ok(())
2790}
2791
2792fn cleanup_detached_child(
2793    applier: &mut dyn Applier,
2794    cleanup: DeferredChildCleanup,
2795) -> Result<(), NodeError> {
2796    if applier.node_generation(cleanup.child_id) != cleanup.generation {
2797        return Ok(());
2798    }
2799
2800    let parent_id = match applier.get_mut(cleanup.child_id) {
2801        Ok(node) => node.parent(),
2802        Err(NodeError::Missing { .. }) => return Ok(()),
2803        Err(err) => return Err(err),
2804    };
2805    if parent_id.is_some() {
2806        return Ok(());
2807    }
2808
2809    if let Ok(node) = applier.get_mut(cleanup.child_id) {
2810        if !cleanup.removed_from_parent {
2811            node.on_removed_from_parent();
2812        }
2813        node.unmount();
2814    }
2815    match applier.remove(cleanup.child_id) {
2816        Ok(()) | Err(NodeError::Missing { .. }) => Ok(()),
2817        Err(err) => Err(err),
2818    }
2819}
2820
2821fn remove_child_and_cleanup_now(
2822    applier: &mut dyn Applier,
2823    parent_id: NodeId,
2824    child_id: NodeId,
2825) -> Result<(), NodeError> {
2826    let mut deferred_cleanup = DeferredChildCleanupQueue::default();
2827    apply_remove_child(applier, parent_id, child_id, &mut deferred_cleanup)?;
2828    deferred_cleanup.flush(applier)
2829}
2830
2831fn collect_current_children(applier: &mut dyn Applier, parent_id: NodeId) -> ChildList {
2832    let mut scratch = SmallVec::<[NodeId; 8]>::new();
2833    if let Ok(node) = applier.get_mut(parent_id) {
2834        node.collect_children_into(&mut scratch);
2835    }
2836    let mut current = ChildList::new();
2837    current.extend(scratch);
2838    current
2839}
2840
2841fn sync_children(
2842    applier: &mut dyn Applier,
2843    parent_id: NodeId,
2844    expected_children: &[NodeId],
2845    deferred_cleanup: &mut DeferredChildCleanupQueue,
2846) -> Result<(), NodeError> {
2847    let mut current = collect_current_children(applier, parent_id);
2848    let children_changed = current.as_slice() != expected_children;
2849
2850    if children_changed {
2851        if current.len().max(expected_children.len()) <= SMALL_CHILD_SYNC_LINEAR_THRESHOLD {
2852            sync_children_small(
2853                applier,
2854                parent_id,
2855                &mut current,
2856                expected_children,
2857                deferred_cleanup,
2858            )?;
2859        } else {
2860            let mut target_positions: HashMap<NodeId, usize> = HashMap::default();
2861            target_positions.reserve(expected_children.len());
2862            for (index, &child) in expected_children.iter().enumerate() {
2863                target_positions.insert(child, index);
2864            }
2865
2866            for index in (0..current.len()).rev() {
2867                let child = current[index];
2868                if !target_positions.contains_key(&child) {
2869                    current.remove(index);
2870                    apply_remove_child(applier, parent_id, child, deferred_cleanup)?;
2871                }
2872            }
2873
2874            let mut current_positions = build_child_positions(&current);
2875            for (target_index, &child) in expected_children.iter().enumerate() {
2876                if let Some(current_index) = current_positions.get(&child).copied() {
2877                    if current_index != target_index {
2878                        let from_index = current_index;
2879                        let to_index = move_child_in_diff_state(
2880                            &mut current,
2881                            &mut current_positions,
2882                            from_index,
2883                            target_index,
2884                        );
2885                        Command::MoveChild {
2886                            parent_id,
2887                            from_index,
2888                            to_index,
2889                            bubble: DirtyBubble::LAYOUT_AND_MEASURE,
2890                        }
2891                        .apply(applier)?;
2892                    }
2893                } else {
2894                    let insert_index = target_index.min(current.len());
2895                    let appended_index = current.len();
2896                    insert_child_into_diff_state(
2897                        &mut current,
2898                        &mut current_positions,
2899                        insert_index,
2900                        child,
2901                    );
2902                    Command::InsertChild {
2903                        parent_id,
2904                        child_id: child,
2905                        appended_index,
2906                        insert_index,
2907                        bubble: DirtyBubble::LAYOUT_AND_MEASURE,
2908                    }
2909                    .apply(applier)?;
2910                }
2911            }
2912        }
2913    }
2914
2915    reconcile_children(applier, parent_id, expected_children, !children_changed)
2916}
2917
2918fn sync_children_small(
2919    applier: &mut dyn Applier,
2920    parent_id: NodeId,
2921    current: &mut ChildList,
2922    expected_children: &[NodeId],
2923    deferred_cleanup: &mut DeferredChildCleanupQueue,
2924) -> Result<(), NodeError> {
2925    for index in (0..current.len()).rev() {
2926        let child = current[index];
2927        if !expected_children.contains(&child) {
2928            current.remove(index);
2929            apply_remove_child(applier, parent_id, child, deferred_cleanup)?;
2930        }
2931    }
2932
2933    for (target_index, &child) in expected_children.iter().enumerate() {
2934        if let Some(current_index) = current
2935            .iter()
2936            .position(|&current_child| current_child == child)
2937        {
2938            if current_index != target_index {
2939                let child = current.remove(current_index);
2940                let to_index = target_index.min(current.len());
2941                current.insert(to_index, child);
2942                Command::MoveChild {
2943                    parent_id,
2944                    from_index: current_index,
2945                    to_index,
2946                    bubble: DirtyBubble::LAYOUT_AND_MEASURE,
2947                }
2948                .apply(applier)?;
2949            }
2950        } else {
2951            let insert_index = target_index.min(current.len());
2952            let appended_index = current.len();
2953            current.insert(insert_index, child);
2954            Command::InsertChild {
2955                parent_id,
2956                child_id: child,
2957                appended_index,
2958                insert_index,
2959                bubble: DirtyBubble::LAYOUT_AND_MEASURE,
2960            }
2961            .apply(applier)?;
2962        }
2963    }
2964
2965    Ok(())
2966}
2967
2968fn reconcile_children(
2969    applier: &mut dyn Applier,
2970    parent_id: NodeId,
2971    expected_children: &[NodeId],
2972    needs_dirty_check: bool,
2973) -> Result<(), NodeError> {
2974    let mut repaired = false;
2975    for &child_id in expected_children {
2976        let needs_attach = if let Ok(node) = applier.get_mut(child_id) {
2977            node.parent() != Some(parent_id)
2978        } else {
2979            false
2980        };
2981
2982        if needs_attach {
2983            insert_child_with_reparenting(applier, parent_id, child_id);
2984            repaired = true;
2985        }
2986    }
2987
2988    let is_dirty = if needs_dirty_check {
2989        if let Ok(node) = applier.get_mut(parent_id) {
2990            node.needs_layout()
2991        } else {
2992            false
2993        }
2994    } else {
2995        false
2996    };
2997
2998    if repaired {
2999        bubble_layout_dirty(applier, parent_id);
3000        bubble_measure_dirty(applier, parent_id);
3001    } else if is_dirty {
3002        bubble_layout_dirty(applier, parent_id);
3003    }
3004
3005    Ok(())
3006}
3007
3008#[derive(Default)]
3009pub struct MemoryApplier {
3010    nodes: Vec<Option<Box<dyn Node>>>,
3011    physical_stable_ids: Vec<u32>,
3012    physical_warm_recycled_origins: Vec<bool>,
3013    stable_to_physical: HashMap<NodeId, usize>,
3014    stable_generations: HashMap<NodeId, u32>,
3015    free_ids: BinaryHeap<Reverse<usize>>,
3016    high_id_nodes: HashMap<NodeId, Box<dyn Node>>,
3017    high_id_warm_recycled_origins: HashMap<NodeId, bool>,
3018    high_id_generations: HashMap<NodeId, u32>,
3019    next_stable_id: NodeId,
3020    layout_runtime: Option<RuntimeHandle>,
3021    slots: SlotTable,
3022    recycled_nodes: HashMap<TypeId, Vec<RecycledNode>>,
3023    returning_recycled_nodes: HashMap<TypeId, Vec<RecycledNode>>,
3024    cold_recycled_nodes: HashMap<TypeId, Vec<RecycledNode>>,
3025    recycled_node_limits: HashMap<TypeId, usize>,
3026    warm_recycled_node_targets: HashMap<TypeId, usize>,
3027    fresh_recyclable_creations: HashMap<TypeId, usize>,
3028    recycled_node_prototypes: HashMap<TypeId, Box<dyn Node>>,
3029    structural_change_parents: Vec<NodeId>,
3030    virtual_node_ids: HashSet<NodeId>,
3031}
3032
3033struct RemovalFrame {
3034    node_id: NodeId,
3035    children: SmallVec<[NodeId; 8]>,
3036    next_child: usize,
3037}
3038
3039#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
3040pub struct MemoryApplierDebugStats {
3041    pub next_stable_id: NodeId,
3042    pub nodes_len: usize,
3043    pub nodes_cap: usize,
3044    pub physical_stable_ids_len: usize,
3045    pub physical_stable_ids_cap: usize,
3046    pub stable_to_physical_len: usize,
3047    pub stable_to_physical_cap: usize,
3048    pub stable_generations_len: usize,
3049    pub stable_generations_cap: usize,
3050    pub free_ids_len: usize,
3051    pub free_ids_cap: usize,
3052    pub high_id_nodes_len: usize,
3053    pub high_id_nodes_cap: usize,
3054    pub high_id_generations_len: usize,
3055    pub high_id_generations_cap: usize,
3056    pub recycled_type_count: usize,
3057    pub recycled_type_cap: usize,
3058    pub recycled_node_count: usize,
3059    pub recycled_node_capacity: usize,
3060    pub warm_recycled_node_id_count: usize,
3061    pub warm_recycled_node_id_capacity: usize,
3062}
3063
3064impl MemoryApplier {
3065    const EAGER_COMPACT_NODE_LEN: usize = 1_024;
3066    const HIGH_ID_THRESHOLD: NodeId = 1_000_000_000;
3067    const INVALID_STABLE_ID: u32 = u32::MAX;
3068    const INITIAL_DENSE_NODE_CAP: usize = 32;
3069    const LARGE_DENSE_NODE_GROWTH_THRESHOLD: usize = 32 * 1024;
3070    const LARGE_DENSE_NODE_GROWTH_DIVISOR: usize = 4;
3071
3072    fn pack_stable_id(stable_id: NodeId) -> u32 {
3073        u32::try_from(stable_id).expect("stable id overflow")
3074    }
3075
3076    fn unpack_stable_id(stable_id: u32) -> NodeId {
3077        stable_id as NodeId
3078    }
3079
3080    fn next_dense_node_target_len(old_len: usize) -> usize {
3081        if old_len < Self::INITIAL_DENSE_NODE_CAP {
3082            return Self::INITIAL_DENSE_NODE_CAP;
3083        }
3084        if old_len < Self::LARGE_DENSE_NODE_GROWTH_THRESHOLD {
3085            return old_len.saturating_mul(2);
3086        }
3087
3088        let incremental_growth =
3089            (old_len / Self::LARGE_DENSE_NODE_GROWTH_DIVISOR).max(Self::INITIAL_DENSE_NODE_CAP);
3090        old_len.saturating_add(incremental_growth)
3091    }
3092
3093    fn ensure_dense_node_storage_capacity(&mut self) {
3094        let len = self
3095            .nodes
3096            .len()
3097            .max(self.physical_stable_ids.len())
3098            .max(self.physical_warm_recycled_origins.len());
3099        if len < self.nodes.capacity()
3100            && len < self.physical_stable_ids.capacity()
3101            && len < self.physical_warm_recycled_origins.capacity()
3102        {
3103            return;
3104        }
3105
3106        let target = Self::next_dense_node_target_len(len);
3107        if self.nodes.capacity() < target {
3108            self.nodes
3109                .reserve_exact(target.saturating_sub(self.nodes.len()));
3110        }
3111        if self.physical_stable_ids.capacity() < target {
3112            self.physical_stable_ids
3113                .reserve_exact(target.saturating_sub(self.physical_stable_ids.len()));
3114        }
3115        if self.physical_warm_recycled_origins.capacity() < target {
3116            self.physical_warm_recycled_origins
3117                .reserve_exact(target.saturating_sub(self.physical_warm_recycled_origins.len()));
3118        }
3119    }
3120
3121    fn ensure_stable_index_capacity(&mut self) {
3122        let len = self
3123            .stable_to_physical
3124            .len()
3125            .max(self.stable_generations.len());
3126        if len < self.stable_to_physical.capacity() && len < self.stable_generations.capacity() {
3127            return;
3128        }
3129
3130        let target = Self::next_dense_node_target_len(len);
3131        let additional = target.saturating_sub(len);
3132        if self.stable_to_physical.capacity() < target {
3133            self.stable_to_physical.reserve(additional);
3134        }
3135        if self.stable_generations.capacity() < target {
3136            self.stable_generations.reserve(additional);
3137        }
3138    }
3139
3140    pub fn new() -> Self {
3141        Self {
3142            nodes: Vec::new(),
3143            physical_stable_ids: Vec::new(),
3144            physical_warm_recycled_origins: Vec::new(),
3145            stable_to_physical: HashMap::default(),
3146            stable_generations: HashMap::default(),
3147            free_ids: BinaryHeap::new(),
3148            high_id_nodes: HashMap::default(),
3149            high_id_warm_recycled_origins: HashMap::default(),
3150            high_id_generations: HashMap::default(),
3151            next_stable_id: 0,
3152            layout_runtime: None,
3153            slots: SlotTable::default(),
3154            recycled_nodes: HashMap::default(),
3155            returning_recycled_nodes: HashMap::default(),
3156            cold_recycled_nodes: HashMap::default(),
3157            recycled_node_limits: HashMap::default(),
3158            warm_recycled_node_targets: HashMap::default(),
3159            fresh_recyclable_creations: HashMap::default(),
3160            recycled_node_prototypes: HashMap::default(),
3161            structural_change_parents: Vec::new(),
3162            virtual_node_ids: HashSet::default(),
3163        }
3164    }
3165
3166    pub fn slots(&mut self) -> &mut SlotTable {
3167        &mut self.slots
3168    }
3169
3170    /// Drains the parents recorded via [`Applier::record_structural_change`],
3171    /// keeping only nodes still attached to `root` (a parent that was itself
3172    /// removed is covered by its own surviving ancestor's record). A virtual
3173    /// parent — a subcompose slot wrapper the render graph never contains —
3174    /// is reported as its nearest non-virtual ancestor: that is the node
3175    /// whose graph child set the change altered, and an id the graph cannot
3176    /// resolve would force the scoped scene update to give up and rebuild.
3177    /// Resolves a scene-scope candidate the way structural records are
3178    /// resolved: to its nearest non-virtual ancestor, and only while still
3179    /// attached to `root`. A node detached after recording must not reach the
3180    /// scoped scene update — an id the graph cannot resolve forces it to give
3181    /// up and rebuild the whole scene.
3182    pub fn scene_node_attached_to(&mut self, node_id: NodeId, root: NodeId) -> Option<NodeId> {
3183        let resolved = self.first_non_virtual_ancestor(node_id)?;
3184        self.is_attached_to(resolved, root).then_some(resolved)
3185    }
3186
3187    pub fn take_structural_change_parents_attached_to(&mut self, root: NodeId) -> Vec<NodeId> {
3188        let recorded = std::mem::take(&mut self.structural_change_parents);
3189        let mut attached = Vec::with_capacity(recorded.len());
3190        for parent_id in recorded {
3191            let Some(parent_id) = self.first_non_virtual_ancestor(parent_id) else {
3192                continue;
3193            };
3194            if self.is_attached_to(parent_id, root) && !attached.contains(&parent_id) {
3195                attached.push(parent_id);
3196            }
3197        }
3198        attached
3199    }
3200
3201    fn first_non_virtual_ancestor(&mut self, node_id: NodeId) -> Option<NodeId> {
3202        let mut current = node_id;
3203        for _ in 0..100_000 {
3204            if !self.virtual_node_ids.contains(&current) {
3205                return Some(current);
3206            }
3207            match self.get_mut(current) {
3208                Ok(node) => current = node.parent()?,
3209                Err(_) => return None,
3210            }
3211        }
3212        None
3213    }
3214
3215    fn is_attached_to(&mut self, node_id: NodeId, root: NodeId) -> bool {
3216        let mut current = node_id;
3217        for _ in 0..100_000 {
3218            if current == root {
3219                return true;
3220            }
3221            match self.get_mut(current) {
3222                Ok(node) => match node.parent() {
3223                    Some(parent) => current = parent,
3224                    None => return false,
3225                },
3226                Err(_) => return false,
3227            }
3228        }
3229        false
3230    }
3231
3232    pub fn with_node<N: Node + 'static, R>(
3233        &mut self,
3234        id: NodeId,
3235        f: impl FnOnce(&mut N) -> R,
3236    ) -> Result<R, NodeError> {
3237        let physical_id = self
3238            .resolve_node_index(id)
3239            .ok_or(NodeError::Missing { id })?;
3240        let slot = self
3241            .nodes
3242            .get_mut(physical_id)
3243            .ok_or(NodeError::Missing { id })?
3244            .as_deref_mut()
3245            .ok_or(NodeError::Missing { id })?;
3246        let typed = slot
3247            .as_any_mut()
3248            .downcast_mut::<N>()
3249            .ok_or(NodeError::TypeMismatch {
3250                id,
3251                expected: std::any::type_name::<N>(),
3252            })?;
3253        Ok(f(typed))
3254    }
3255
3256    pub fn len(&self) -> usize {
3257        self.nodes.iter().filter(|n| n.is_some()).count()
3258    }
3259
3260    pub fn capacity(&self) -> usize {
3261        self.nodes.len()
3262    }
3263
3264    pub fn tombstone_count(&self) -> usize {
3265        self.nodes.iter().filter(|n| n.is_none()).count()
3266    }
3267
3268    pub fn freelist_len(&self) -> usize {
3269        self.free_ids.len()
3270    }
3271
3272    pub fn debug_recycled_node_count(&self) -> usize {
3273        self.total_recycled_node_count()
3274    }
3275
3276    pub fn debug_recycled_node_count_for<N: Node + 'static>(&self) -> usize {
3277        let key = TypeId::of::<N>();
3278        self.recycled_nodes.get(&key).map(Vec::len).unwrap_or(0)
3279            + self
3280                .returning_recycled_nodes
3281                .get(&key)
3282                .map(Vec::len)
3283                .unwrap_or(0)
3284            + self
3285                .cold_recycled_nodes
3286                .get(&key)
3287                .map(Vec::len)
3288                .unwrap_or(0)
3289    }
3290
3291    pub fn debug_stats(&self) -> MemoryApplierDebugStats {
3292        let mut recycled_keys: HashSet<TypeId> = HashSet::default();
3293        recycled_keys.extend(self.recycled_nodes.keys().copied());
3294        recycled_keys.extend(self.returning_recycled_nodes.keys().copied());
3295        recycled_keys.extend(self.cold_recycled_nodes.keys().copied());
3296
3297        MemoryApplierDebugStats {
3298            next_stable_id: self.next_stable_id,
3299            nodes_len: self.len(),
3300            nodes_cap: self.nodes.len(),
3301            physical_stable_ids_len: self.physical_stable_ids.len(),
3302            physical_stable_ids_cap: self.physical_stable_ids.capacity(),
3303            stable_to_physical_len: self.stable_to_physical.len(),
3304            stable_to_physical_cap: self.stable_to_physical.capacity(),
3305            stable_generations_len: self.stable_generations.len(),
3306            stable_generations_cap: self.stable_generations.capacity(),
3307            free_ids_len: self.free_ids.len(),
3308            free_ids_cap: self.free_ids.capacity(),
3309            high_id_nodes_len: self.high_id_nodes.len(),
3310            high_id_nodes_cap: self.high_id_nodes.capacity(),
3311            high_id_generations_len: self.high_id_generations.len(),
3312            high_id_generations_cap: self.high_id_generations.capacity(),
3313            recycled_type_count: recycled_keys.len(),
3314            recycled_type_cap: self.recycled_nodes.capacity()
3315                + self.returning_recycled_nodes.capacity()
3316                + self.cold_recycled_nodes.capacity(),
3317            recycled_node_count: self.total_recycled_node_count(),
3318            recycled_node_capacity: self.total_recycled_node_capacity(),
3319            warm_recycled_node_id_count: self.total_warm_recycled_node_id_count(),
3320            warm_recycled_node_id_capacity: self.total_warm_recycled_node_id_capacity(),
3321        }
3322    }
3323
3324    pub fn is_empty(&self) -> bool {
3325        self.len() == 0
3326    }
3327
3328    pub fn debug_live_node_heap_bytes(&self) -> usize {
3329        let dense_nodes = self
3330            .nodes
3331            .iter()
3332            .flatten()
3333            .map(|node| std::mem::size_of_val(&**node) + node.debug_heap_bytes())
3334            .sum::<usize>();
3335        let high_id_nodes = self
3336            .high_id_nodes
3337            .values()
3338            .map(|node| std::mem::size_of_val(&**node) + node.debug_heap_bytes())
3339            .sum::<usize>();
3340        dense_nodes + high_id_nodes
3341    }
3342
3343    pub fn debug_recycled_node_heap_bytes(&self) -> usize {
3344        let pool_bytes = |pools: &HashMap<TypeId, Vec<RecycledNode>>| {
3345            pools
3346                .values()
3347                .flat_map(|nodes| nodes.iter())
3348                .map(|node| std::mem::size_of_val(&*node.node) + node.node.debug_heap_bytes())
3349                .sum::<usize>()
3350        };
3351
3352        pool_bytes(&self.recycled_nodes)
3353            + pool_bytes(&self.returning_recycled_nodes)
3354            + pool_bytes(&self.cold_recycled_nodes)
3355    }
3356
3357    pub fn set_runtime_handle(&mut self, handle: RuntimeHandle) {
3358        self.layout_runtime = Some(handle);
3359    }
3360
3361    pub fn clear_runtime_handle(&mut self) {
3362        self.layout_runtime = None;
3363    }
3364
3365    pub fn runtime_handle(&self) -> Option<RuntimeHandle> {
3366        self.layout_runtime.clone()
3367    }
3368
3369    fn pool_node_count(pools: &HashMap<TypeId, Vec<RecycledNode>>) -> usize {
3370        pools.values().map(Vec::len).sum()
3371    }
3372
3373    fn pool_node_capacity(pools: &HashMap<TypeId, Vec<RecycledNode>>) -> usize {
3374        pools.values().map(Vec::capacity).sum()
3375    }
3376
3377    fn total_recycled_node_count(&self) -> usize {
3378        Self::pool_node_count(&self.recycled_nodes)
3379            + Self::pool_node_count(&self.returning_recycled_nodes)
3380            + Self::pool_node_count(&self.cold_recycled_nodes)
3381    }
3382
3383    fn total_recycled_node_capacity(&self) -> usize {
3384        Self::pool_node_capacity(&self.recycled_nodes)
3385            + Self::pool_node_capacity(&self.returning_recycled_nodes)
3386            + Self::pool_node_capacity(&self.cold_recycled_nodes)
3387    }
3388
3389    fn total_warm_recycled_node_id_count(&self) -> usize {
3390        self.live_warm_recycled_origin_count()
3391            + Self::pool_node_count(&self.recycled_nodes)
3392            + Self::pool_node_count(&self.returning_recycled_nodes)
3393    }
3394
3395    fn total_warm_recycled_node_id_capacity(&self) -> usize {
3396        self.live_warm_recycled_origin_capacity()
3397            + Self::pool_node_capacity(&self.recycled_nodes)
3398            + Self::pool_node_capacity(&self.returning_recycled_nodes)
3399    }
3400
3401    fn remember_recycle_pool_limit(&mut self, key: TypeId, recycle_pool_limit: Option<usize>) {
3402        if let Some(limit) = recycle_pool_limit {
3403            self.recycled_node_limits.insert(key, limit);
3404        } else {
3405            self.recycled_node_limits.remove(&key);
3406        }
3407    }
3408
3409    fn recycle_pool_limit_for(&self, key: TypeId) -> Option<usize> {
3410        self.recycled_node_limits.get(&key).copied()
3411    }
3412
3413    fn warm_recycled_pool_len(&self, key: TypeId) -> usize {
3414        self.recycled_nodes.get(&key).map(Vec::len).unwrap_or(0)
3415    }
3416
3417    fn warm_recycled_node_target(&self, key: TypeId) -> usize {
3418        self.warm_recycled_node_targets
3419            .get(&key)
3420            .copied()
3421            .unwrap_or(0)
3422    }
3423
3424    fn warm_recycled_node_target_limit(&self, key: TypeId) -> usize {
3425        let Some(limit) = self.recycle_pool_limit_for(key) else {
3426            return usize::MAX;
3427        };
3428        if limit <= 8 { limit } else { limit / 4 }
3429    }
3430
3431    fn update_warm_recycled_node_target(&mut self, key: TypeId, observed_demand: usize) -> usize {
3432        let target_limit = self.warm_recycled_node_target_limit(key);
3433        let existing = self.warm_recycled_node_target(key).min(target_limit);
3434        if observed_demand == 0 {
3435            return existing;
3436        }
3437
3438        let target = match self.recycle_pool_limit_for(key) {
3439            Some(limit) if limit > 8 => target_limit,
3440            Some(_) => observed_demand.min(target_limit),
3441            None => observed_demand,
3442        };
3443        self.warm_recycled_node_targets.insert(key, target);
3444        target
3445    }
3446
3447    fn remember_recycled_node_prototype(&mut self, key: TypeId, shell: &dyn Node) {
3448        if self.recycled_node_prototypes.contains_key(&key) {
3449            return;
3450        }
3451        if let Some(prototype) = shell.rehouse_for_recycle() {
3452            self.recycled_node_prototypes.insert(key, prototype);
3453        }
3454    }
3455
3456    fn live_warm_recycled_origin_count(&self) -> usize {
3457        self.physical_warm_recycled_origins
3458            .iter()
3459            .zip(self.nodes.iter())
3460            .filter(|(warm_origin, node)| **warm_origin && node.is_some())
3461            .count()
3462            + self
3463                .high_id_warm_recycled_origins
3464                .values()
3465                .filter(|warm_origin| **warm_origin)
3466                .count()
3467    }
3468
3469    fn live_warm_recycled_origin_capacity(&self) -> usize {
3470        self.physical_warm_recycled_origins.capacity()
3471            + self.high_id_warm_recycled_origins.capacity()
3472    }
3473
3474    fn push_recycled_node(
3475        &mut self,
3476        key: TypeId,
3477        recycle_pool_limit: Option<usize>,
3478        recycled: RecycledNode,
3479    ) {
3480        self.remember_recycle_pool_limit(key, recycle_pool_limit);
3481        self.remember_recycled_node_prototype(key, recycled.node.as_ref());
3482
3483        let warm_origin = recycled.warm_origin();
3484        let pool = if warm_origin {
3485            self.returning_recycled_nodes.entry(key).or_default()
3486        } else {
3487            self.cold_recycled_nodes.entry(key).or_default()
3488        };
3489        pool.push(recycled);
3490        if let Some(limit) = recycle_pool_limit
3491            && pool.len() > limit
3492        {
3493            let excess = pool.len() - limit;
3494            let dropped: Vec<_> = pool.drain(0..excess).collect();
3495            drop(dropped);
3496        }
3497    }
3498
3499    fn push_warm_recycled_node(
3500        &mut self,
3501        key: TypeId,
3502        recycle_pool_limit: Option<usize>,
3503        mut recycled: RecycledNode,
3504    ) {
3505        self.remember_recycle_pool_limit(key, recycle_pool_limit);
3506
3507        recycled.set_warm_origin(true);
3508        let mut dropped = Vec::new();
3509        let mut remove_pool_entry = false;
3510        {
3511            let pool = self.recycled_nodes.entry(key).or_default();
3512            pool.push(recycled);
3513            if let Some(limit) = recycle_pool_limit
3514                && pool.len() > limit
3515            {
3516                let excess = pool.len() - limit;
3517                dropped = pool.drain(0..excess).collect();
3518                remove_pool_entry = pool.is_empty();
3519            }
3520        }
3521        if remove_pool_entry {
3522            self.recycled_nodes.remove(&key);
3523        }
3524        drop(dropped);
3525    }
3526
3527    fn seed_recycled_node_shell_impl(
3528        &mut self,
3529        key: TypeId,
3530        recycle_pool_limit: Option<usize>,
3531        shell: Box<dyn Node>,
3532    ) {
3533        let limit = recycle_pool_limit.unwrap_or(usize::MAX);
3534        if self.warm_recycled_pool_len(key) >= limit {
3535            return;
3536        }
3537
3538        self.remember_recycled_node_prototype(key, shell.as_ref());
3539        let stable_id = self.next_stable_id;
3540        self.next_stable_id = self.next_stable_id.saturating_add(1);
3541        self.push_warm_recycled_node(
3542            key,
3543            recycle_pool_limit,
3544            RecycledNode::from_shell(stable_id, shell, true),
3545        );
3546    }
3547
3548    fn take_recycled_node_from_pool(
3549        pools: &mut HashMap<TypeId, Vec<RecycledNode>>,
3550        key: TypeId,
3551    ) -> Option<RecycledNode> {
3552        let pool = pools.get_mut(&key)?;
3553        let node = pool.pop();
3554        if pool.is_empty() {
3555            pools.remove(&key);
3556        }
3557        node
3558    }
3559
3560    fn compact_idle_warm_pool(&mut self, key: TypeId) {
3561        let Some(pool) = self.recycled_nodes.get_mut(&key) else {
3562            return;
3563        };
3564        if pool.capacity() <= pool.len().saturating_mul(4).max(64) {
3565            return;
3566        }
3567
3568        let retained = pool.len();
3569        let mut compacted = Vec::with_capacity(retained);
3570        compacted.append(pool);
3571        let remove_pool_entry = compacted.is_empty();
3572        *pool = compacted;
3573        let _ = pool;
3574
3575        if remove_pool_entry {
3576            self.recycled_nodes.remove(&key);
3577        }
3578    }
3579
3580    fn trim_idle_warm_pool_to_target(&mut self, key: TypeId, target: usize) {
3581        let pool_len = self.warm_recycled_pool_len(key);
3582        if pool_len <= target {
3583            return;
3584        }
3585
3586        let Some(pool) = self.recycled_nodes.get_mut(&key) else {
3587            return;
3588        };
3589        let removable = (pool_len - target).min(pool.len());
3590        let dropped: Vec<_> = pool.drain(0..removable).collect();
3591        let remove_pool_entry = pool.is_empty();
3592        let _ = pool;
3593
3594        if remove_pool_entry {
3595            self.recycled_nodes.remove(&key);
3596        }
3597        drop(dropped);
3598    }
3599
3600    fn replenish_warm_pool_to_target(&mut self, key: TypeId, target: usize) {
3601        let missing = target.saturating_sub(self.warm_recycled_pool_len(key));
3602        if missing == 0 {
3603            return;
3604        }
3605
3606        let recycle_pool_limit = self.recycle_pool_limit_for(key);
3607        let mut shells = Vec::with_capacity(missing);
3608        if let Some(prototype) = self.recycled_node_prototypes.get(&key) {
3609            for _ in 0..missing {
3610                let Some(shell) = prototype.rehouse_for_recycle() else {
3611                    break;
3612                };
3613                shells.push(shell);
3614            }
3615        }
3616
3617        for shell in shells {
3618            self.seed_recycled_node_shell_impl(key, recycle_pool_limit, shell);
3619        }
3620    }
3621
3622    fn prune_stable_generations(&mut self) {
3623        let retained_len = self.stable_to_physical.len() + self.total_recycled_node_count();
3624        if retained_len == self.stable_generations.len() {
3625            return;
3626        }
3627
3628        let mut retained = HashMap::default();
3629        retained.reserve(retained_len);
3630        for stable_id in self.stable_to_physical.keys().copied() {
3631            if let Some(generation) = self.stable_generations.get(&stable_id).copied() {
3632                retained.insert(stable_id, generation);
3633            }
3634        }
3635        for stable_id in self
3636            .recycled_nodes
3637            .values()
3638            .flat_map(|nodes| nodes.iter().map(RecycledNode::stable_id))
3639        {
3640            if let Some(generation) = self.stable_generations.get(&stable_id).copied() {
3641                retained.insert(stable_id, generation);
3642            }
3643        }
3644        for stable_id in self
3645            .returning_recycled_nodes
3646            .values()
3647            .flat_map(|nodes| nodes.iter().map(RecycledNode::stable_id))
3648        {
3649            if let Some(generation) = self.stable_generations.get(&stable_id).copied() {
3650                retained.insert(stable_id, generation);
3651            }
3652        }
3653        for stable_id in self
3654            .cold_recycled_nodes
3655            .values()
3656            .flat_map(|nodes| nodes.iter().map(RecycledNode::stable_id))
3657        {
3658            if let Some(generation) = self.stable_generations.get(&stable_id).copied() {
3659                retained.insert(stable_id, generation);
3660            }
3661        }
3662        self.stable_generations = retained;
3663    }
3664
3665    pub fn dump_tree(&self, root: Option<NodeId>) -> String {
3666        let mut output = String::new();
3667        if let Some(root_id) = root {
3668            self.dump_node(&mut output, root_id, 0);
3669        } else {
3670            output.push_str("(no root)\n");
3671        }
3672        output
3673    }
3674
3675    fn dump_node(&self, output: &mut String, id: NodeId, depth: usize) {
3676        let indent = "  ".repeat(depth);
3677        if let Some(physical_id) = self.resolve_node_index(id) {
3678            if let Some(node) = self.nodes.get(physical_id).and_then(Option::as_ref) {
3679                let type_name = std::any::type_name_of_val(&**node);
3680                output.push_str(&format!("{}[{}] {}\n", indent, id, type_name));
3681
3682                let children = node.children();
3683                for child_id in children {
3684                    self.dump_node(output, child_id, depth + 1);
3685                }
3686            } else {
3687                output.push_str(&format!(
3688                    "{}[{}] (missing physical node {})\n",
3689                    indent, id, physical_id
3690                ));
3691            }
3692        } else {
3693            output.push_str(&format!("{}[{}] (missing)\n", indent, id));
3694        }
3695    }
3696
3697    fn resolve_node_index(&self, id: NodeId) -> Option<usize> {
3698        self.stable_to_physical.get(&id).copied()
3699    }
3700
3701    fn contains_node_id(&self, id: NodeId) -> bool {
3702        self.resolve_node_index(id).is_some() || self.high_id_nodes.contains_key(&id)
3703    }
3704
3705    fn insert_high_id_node(&mut self, stable_id: NodeId, node: Box<dyn Node>, warm_origin: bool) {
3706        self.high_id_nodes.insert(stable_id, node);
3707        self.high_id_warm_recycled_origins
3708            .insert(stable_id, warm_origin);
3709        self.high_id_generations.entry(stable_id).or_insert(0);
3710    }
3711
3712    fn insert_available_with_id(&mut self, stable_id: NodeId, node: Box<dyn Node>) {
3713        if stable_id >= Self::HIGH_ID_THRESHOLD {
3714            self.insert_high_id_node(stable_id, node, false);
3715            return;
3716        }
3717
3718        let physical_id = if let Some(Reverse(free_physical_id)) = self.free_ids.pop() {
3719            self.nodes[free_physical_id] = Some(node);
3720            self.physical_stable_ids[free_physical_id] = Self::pack_stable_id(stable_id);
3721            self.physical_warm_recycled_origins[free_physical_id] = false;
3722            free_physical_id
3723        } else {
3724            self.ensure_dense_node_storage_capacity();
3725            let physical_id = self.nodes.len();
3726            self.nodes.push(Some(node));
3727            self.physical_stable_ids
3728                .push(Self::pack_stable_id(stable_id));
3729            self.physical_warm_recycled_origins.push(false);
3730            physical_id
3731        };
3732
3733        self.next_stable_id = self.next_stable_id.max(stable_id.saturating_add(1));
3734        self.ensure_stable_index_capacity();
3735        self.stable_generations.entry(stable_id).or_insert(0);
3736        self.physical_stable_ids[physical_id] = Self::pack_stable_id(stable_id);
3737        self.stable_to_physical.insert(stable_id, physical_id);
3738    }
3739
3740    fn get_ref(&self, id: NodeId) -> Result<&dyn Node, NodeError> {
3741        if let Some(physical_id) = self.resolve_node_index(id) {
3742            let slot = self
3743                .nodes
3744                .get(physical_id)
3745                .ok_or(NodeError::Missing { id })?
3746                .as_deref()
3747                .ok_or(NodeError::Missing { id })?;
3748            return Ok(slot);
3749        }
3750
3751        self.high_id_nodes
3752            .get(&id)
3753            .map(|node| node.as_ref())
3754            .ok_or(NodeError::Missing { id })
3755    }
3756
3757    fn node_parent(&self, id: NodeId) -> Result<Option<NodeId>, NodeError> {
3758        Ok(self.get_ref(id)?.parent())
3759    }
3760
3761    fn collect_owned_children(
3762        &self,
3763        node_id: NodeId,
3764        out: &mut SmallVec<[NodeId; 8]>,
3765    ) -> Result<(), NodeError> {
3766        self.get_ref(node_id)?.collect_owned_children_into(out);
3767        out.retain(|child_id| {
3768            self.node_parent(*child_id)
3769                .map(|parent| parent == Some(node_id))
3770                .unwrap_or(false)
3771        });
3772        Ok(())
3773    }
3774
3775    fn remove_node_storage(&mut self, node_id: NodeId) -> Result<(), NodeError> {
3776        self.virtual_node_ids.remove(&node_id);
3777        if self.high_id_nodes.contains_key(&node_id) {
3778            if let Some(mut node) = self.high_id_nodes.remove(&node_id)
3779                && let Some(key) = node.recycle_key()
3780            {
3781                let recycle_pool_limit = node.recycle_pool_limit();
3782                let warm_origin = self
3783                    .high_id_warm_recycled_origins
3784                    .remove(&node_id)
3785                    .unwrap_or(false);
3786                node.prepare_for_recycle();
3787                self.push_recycled_node(
3788                    key,
3789                    recycle_pool_limit,
3790                    RecycledNode::new(node_id, node, warm_origin),
3791                );
3792            }
3793            let generation = self.high_id_generations.entry(node_id).or_insert(0);
3794            *generation = generation.wrapping_add(1);
3795            return Ok(());
3796        }
3797
3798        let physical_id = self
3799            .resolve_node_index(node_id)
3800            .ok_or(NodeError::Missing { id: node_id })?;
3801        if let Some(mut node) = self.nodes[physical_id].take()
3802            && let Some(key) = node.recycle_key()
3803        {
3804            let recycle_pool_limit = node.recycle_pool_limit();
3805            let warm_origin = self
3806                .physical_warm_recycled_origins
3807                .get_mut(physical_id)
3808                .map(std::mem::take)
3809                .unwrap_or(false);
3810            node.prepare_for_recycle();
3811            self.push_recycled_node(
3812                key,
3813                recycle_pool_limit,
3814                RecycledNode::new(node_id, node, warm_origin),
3815            );
3816        }
3817        self.physical_stable_ids[physical_id] = Self::INVALID_STABLE_ID;
3818        self.stable_to_physical.remove(&node_id);
3819        if let Some(generation) = self.stable_generations.get_mut(&node_id) {
3820            *generation = generation.wrapping_add(1);
3821        } else {
3822            self.stable_generations.insert(node_id, 1);
3823        }
3824        self.free_ids.push(Reverse(physical_id));
3825        Ok(())
3826    }
3827
3828    fn remove_subtree_postorder(&mut self, id: NodeId) -> Result<usize, NodeError> {
3829        self.get_ref(id)?;
3830
3831        let mut root_children = SmallVec::<[NodeId; 8]>::new();
3832        self.collect_owned_children(id, &mut root_children)?;
3833
3834        let mut stack = Vec::new();
3835        stack.push(RemovalFrame {
3836            node_id: id,
3837            children: root_children,
3838            next_child: 0,
3839        });
3840        let mut max_depth = stack.len();
3841
3842        while let Some(frame) = stack.last_mut() {
3843            if frame.next_child < frame.children.len() {
3844                let child_id = frame.children[frame.next_child];
3845                frame.next_child += 1;
3846
3847                if let Ok(child) = self.get_mut(child_id) {
3848                    child.on_removed_from_parent();
3849                    child.unmount();
3850                }
3851
3852                let mut child_children = SmallVec::<[NodeId; 8]>::new();
3853                self.collect_owned_children(child_id, &mut child_children)?;
3854                stack.push(RemovalFrame {
3855                    node_id: child_id,
3856                    children: child_children,
3857                    next_child: 0,
3858                });
3859                max_depth = max_depth.max(stack.len());
3860                continue;
3861            }
3862
3863            let node_id = frame.node_id;
3864            stack.pop();
3865            self.remove_node_storage(node_id)?;
3866        }
3867
3868        Ok(max_depth)
3869    }
3870
3871    #[cfg(test)]
3872    fn debug_remove_max_traversal_depth(&mut self, id: NodeId) -> Result<usize, NodeError> {
3873        self.remove_subtree_postorder(id)
3874    }
3875}
3876
3877impl Applier for MemoryApplier {
3878    fn record_structural_change(&mut self, parent_id: NodeId) {
3879        if self.structural_change_parents.last() != Some(&parent_id) {
3880            self.structural_change_parents.push(parent_id);
3881        }
3882    }
3883
3884    fn create(&mut self, node: Box<dyn Node>) -> NodeId {
3885        let stable_id = self.next_stable_id;
3886        self.next_stable_id = self.next_stable_id.saturating_add(1);
3887        if stable_id >= Self::HIGH_ID_THRESHOLD {
3888            self.insert_high_id_node(stable_id, node, false);
3889            return stable_id;
3890        }
3891
3892        self.ensure_stable_index_capacity();
3893        self.stable_generations.insert(stable_id, 0);
3894
3895        let physical_id = if let Some(Reverse(id)) = self.free_ids.pop() {
3896            debug_assert!(self.nodes[id].is_none(), "freelist entry {id} is not None");
3897            self.nodes[id] = Some(node);
3898            self.physical_stable_ids[id] = Self::pack_stable_id(stable_id);
3899            self.physical_warm_recycled_origins[id] = false;
3900            id
3901        } else {
3902            self.ensure_dense_node_storage_capacity();
3903            let id = self.nodes.len();
3904            self.nodes.push(Some(node));
3905            self.physical_stable_ids
3906                .push(Self::pack_stable_id(stable_id));
3907            self.physical_warm_recycled_origins.push(false);
3908            id
3909        };
3910        self.stable_to_physical.insert(stable_id, physical_id);
3911        stable_id
3912    }
3913
3914    fn node_generation(&self, id: NodeId) -> u32 {
3915        self.high_id_generations
3916            .get(&id)
3917            .copied()
3918            .or_else(|| self.stable_generations.get(&id).copied())
3919            .unwrap_or(0)
3920    }
3921
3922    fn get_mut(&mut self, id: NodeId) -> Result<&mut dyn Node, NodeError> {
3923        if let Some(physical_id) = self.resolve_node_index(id) {
3924            let slot = self.nodes[physical_id]
3925                .as_deref_mut()
3926                .ok_or(NodeError::Missing { id })?;
3927            return Ok(slot);
3928        }
3929        self.high_id_nodes
3930            .get_mut(&id)
3931            .map(|n| n.as_mut())
3932            .ok_or(NodeError::Missing { id })
3933    }
3934
3935    fn remove(&mut self, id: NodeId) -> Result<(), NodeError> {
3936        self.remove_subtree_postorder(id).map(|_| ())
3937    }
3938
3939    fn insert_with_id(&mut self, id: NodeId, node: Box<dyn Node>) -> Result<(), NodeError> {
3940        if self.contains_node_id(id) {
3941            return Err(NodeError::AlreadyExists { id });
3942        }
3943        self.insert_available_with_id(id, node);
3944        self.virtual_node_ids.insert(id);
3945        Ok(())
3946    }
3947
3948    fn insert_recycled_node_or_create(
3949        &mut self,
3950        stable_id: NodeId,
3951        node: Box<dyn Node>,
3952    ) -> RecycledNodeInsertion {
3953        if self.contains_node_id(stable_id) {
3954            let id = self.create(node);
3955            return RecycledNodeInsertion::fresh(
3956                id,
3957                Some(NodeError::AlreadyExists { id: stable_id }),
3958            );
3959        }
3960
3961        self.insert_available_with_id(stable_id, node);
3962        RecycledNodeInsertion::reused(stable_id)
3963    }
3964
3965    fn compact(&mut self) {
3966        let live_count = self.nodes.iter().filter(|slot| slot.is_some()).count();
3967        let tombstone_count = self.nodes.len().saturating_sub(live_count);
3968        if tombstone_count == 0 {
3969            return;
3970        }
3971        if self.nodes.len() > Self::EAGER_COMPACT_NODE_LEN && tombstone_count < live_count {
3972            return;
3973        }
3974        let rehouse_live_nodes = tombstone_count >= live_count;
3975        let mut packed_nodes = Vec::with_capacity(live_count);
3976        let mut packed_physical_stable_ids = Vec::with_capacity(live_count);
3977        let mut packed_warm_recycled_origins = Vec::with_capacity(live_count);
3978        let mut stable_to_physical = HashMap::default();
3979        stable_to_physical.reserve(live_count);
3980
3981        for physical_id in 0..self.nodes.len() {
3982            let Some(mut node) = self.nodes[physical_id].take() else {
3983                continue;
3984            };
3985            if rehouse_live_nodes && let Some(rehoused) = node.rehouse_for_live_compaction() {
3986                node = rehoused;
3987            }
3988            let stable_id = std::mem::replace(
3989                &mut self.physical_stable_ids[physical_id],
3990                Self::INVALID_STABLE_ID,
3991            );
3992            debug_assert_ne!(
3993                stable_id,
3994                Self::INVALID_STABLE_ID,
3995                "live physical slot must have a stable id",
3996            );
3997            let stable_id = Self::unpack_stable_id(stable_id);
3998            packed_nodes.push(Some(node));
3999            packed_physical_stable_ids.push(Self::pack_stable_id(stable_id));
4000            packed_warm_recycled_origins.push(self.physical_warm_recycled_origins[physical_id]);
4001            stable_to_physical.insert(stable_id, packed_nodes.len() - 1);
4002        }
4003
4004        self.nodes = packed_nodes;
4005        self.physical_stable_ids = packed_physical_stable_ids;
4006        self.physical_warm_recycled_origins = packed_warm_recycled_origins;
4007        self.free_ids = BinaryHeap::new();
4008        self.stable_to_physical = stable_to_physical;
4009        self.prune_stable_generations();
4010    }
4011
4012    fn take_recycled_node(&mut self, key: TypeId) -> Option<RecycledNode> {
4013        Self::take_recycled_node_from_pool(&mut self.returning_recycled_nodes, key)
4014            .or_else(|| Self::take_recycled_node_from_pool(&mut self.recycled_nodes, key))
4015    }
4016
4017    fn set_recycled_node_origin(&mut self, id: NodeId, warm_origin: bool) {
4018        if let Some(physical_id) = self.resolve_node_index(id) {
4019            self.physical_warm_recycled_origins[physical_id] = warm_origin;
4020        } else if self.high_id_nodes.contains_key(&id) {
4021            self.high_id_warm_recycled_origins.insert(id, warm_origin);
4022        }
4023    }
4024
4025    fn seed_recycled_node_shell(
4026        &mut self,
4027        key: TypeId,
4028        recycle_pool_limit: Option<usize>,
4029        shell: Box<dyn Node>,
4030    ) {
4031        self.seed_recycled_node_shell_impl(key, recycle_pool_limit, shell);
4032    }
4033
4034    fn record_fresh_recyclable_creation(&mut self, key: TypeId) {
4035        *self.fresh_recyclable_creations.entry(key).or_insert(0) += 1;
4036    }
4037
4038    fn clear_recycled_nodes(&mut self) {
4039        let returning = std::mem::take(&mut self.returning_recycled_nodes);
4040        for (key, mut nodes) in returning {
4041            let pool = self.recycled_nodes.entry(key).or_default();
4042            pool.append(&mut nodes);
4043        }
4044
4045        let fresh_recyclable_creations = std::mem::take(&mut self.fresh_recyclable_creations);
4046        let cold = std::mem::take(&mut self.cold_recycled_nodes);
4047        for (key, mut nodes) in cold {
4048            let needed = fresh_recyclable_creations.get(&key).copied().unwrap_or(0);
4049            if needed > 0 {
4050                let remaining_limit = self
4051                    .recycle_pool_limit_for(key)
4052                    .unwrap_or(usize::MAX)
4053                    .saturating_sub(self.warm_recycled_pool_len(key));
4054                let promote = nodes.len().min(needed).min(remaining_limit);
4055                let split_at = nodes.len().saturating_sub(promote);
4056                let promoted = nodes.split_off(split_at);
4057                for mut recycled in promoted {
4058                    recycled.set_warm_origin(true);
4059                    self.recycled_nodes.entry(key).or_default().push(recycled);
4060                }
4061            }
4062        }
4063
4064        let mut keys: HashSet<TypeId> = HashSet::default();
4065        keys.extend(self.recycled_nodes.keys().copied());
4066        keys.extend(self.recycled_node_limits.keys().copied());
4067        keys.extend(self.warm_recycled_node_targets.keys().copied());
4068        keys.extend(self.recycled_node_prototypes.keys().copied());
4069        for key in keys {
4070            let observed_demand = fresh_recyclable_creations.get(&key).copied().unwrap_or(0);
4071            let target = self.update_warm_recycled_node_target(key, observed_demand);
4072            self.replenish_warm_pool_to_target(key, target);
4073            self.trim_idle_warm_pool_to_target(key, target);
4074            self.compact_idle_warm_pool(key);
4075        }
4076        self.prune_stable_generations();
4077        self.compact();
4078    }
4079}
4080
4081pub trait ApplierHost {
4082    fn borrow_dyn(&self) -> RefMut<'_, dyn Applier>;
4083    /// Compact internal storage after commands have been applied.
4084    fn compact(&self) {}
4085}
4086
4087pub struct ConcreteApplierHost<A: Applier + 'static> {
4088    inner: RefCell<A>,
4089}
4090
4091impl<A: Applier + 'static> ConcreteApplierHost<A> {
4092    pub fn new(applier: A) -> Self {
4093        Self {
4094            inner: RefCell::new(applier),
4095        }
4096    }
4097
4098    pub fn borrow_typed(&self) -> RefMut<'_, A> {
4099        self.inner.borrow_mut()
4100    }
4101
4102    pub fn try_borrow_typed(&self) -> Result<RefMut<'_, A>, std::cell::BorrowMutError> {
4103        self.inner.try_borrow_mut()
4104    }
4105
4106    pub fn into_inner(self) -> A {
4107        self.inner.into_inner()
4108    }
4109}
4110
4111impl<A: Applier + 'static> ApplierHost for ConcreteApplierHost<A> {
4112    fn borrow_dyn(&self) -> RefMut<'_, dyn Applier> {
4113        RefMut::map(self.inner.borrow_mut(), |applier| {
4114            applier as &mut dyn Applier
4115        })
4116    }
4117
4118    fn compact(&self) {
4119        self.inner.borrow_mut().compact();
4120    }
4121}
4122
4123pub struct ApplierGuard<'a, A: Applier + 'static> {
4124    inner: RefMut<'a, A>,
4125}
4126
4127impl<'a, A: Applier + 'static> ApplierGuard<'a, A> {
4128    fn new(inner: RefMut<'a, A>) -> Self {
4129        Self { inner }
4130    }
4131}
4132
4133impl<'a, A: Applier + 'static> Deref for ApplierGuard<'a, A> {
4134    type Target = A;
4135
4136    fn deref(&self) -> &Self::Target {
4137        &self.inner
4138    }
4139}
4140
4141impl<'a, A: Applier + 'static> DerefMut for ApplierGuard<'a, A> {
4142    fn deref_mut(&mut self) -> &mut Self::Target {
4143        &mut self.inner
4144    }
4145}
4146
4147pub struct SlotsHost {
4148    storage_key: Cell<usize>,
4149    inner: RefCell<SlotsHostInner>,
4150}
4151
4152#[derive(Debug, Default)]
4153pub(crate) struct SlotPassOutcome {
4154    pub(crate) compacted: bool,
4155    pub(crate) compact_anchor_registry_storage: bool,
4156    pub(crate) compact_payload_storage: bool,
4157}
4158
4159#[derive(Default)]
4160pub(crate) struct FinishedSlotPass {
4161    pub(crate) outcome: SlotPassOutcome,
4162    pub(crate) detached_root_children: Vec<slot::DetachedSubtree>,
4163}
4164
4165struct ActivePassState {
4166    state: slot::SlotWriteSessionState,
4167}
4168
4169struct SlotsHostInner {
4170    table: SlotTable,
4171    nested_hosts: Vec<std::rc::Weak<SlotsHost>>,
4172    lifecycle: slot::SlotLifecycleCoordinator,
4173    runtime_state: Option<Rc<crate::composer::ComposerRuntimeState>>,
4174    active_pass: Option<ActivePassState>,
4175}
4176
4177impl Drop for SlotsHost {
4178    fn drop(&mut self) {
4179        let storage_key = self.storage_key.get();
4180        let inner = self.inner.get_mut();
4181        if let Some(state) = inner.runtime_state.clone() {
4182            if let Err(err) = state.dispose_retained_subtrees_for_host(
4183                storage_key,
4184                &mut inner.table,
4185                &mut inner.lifecycle,
4186            ) {
4187                log::error!(
4188                    "retained subtree disposal failed while dropping SlotsHost {storage_key}: {err}"
4189                );
4190                state.abandon_retained_subtrees_for_host(
4191                    storage_key,
4192                    &mut inner.table,
4193                    &mut inner.lifecycle,
4194                );
4195            } else {
4196                state.clear_host_storage_key(storage_key);
4197            }
4198        }
4199        inner.lifecycle.dispose_slot_table(&mut inner.table);
4200    }
4201}
4202
4203impl SlotsHost {
4204    pub fn storage_key(&self) -> usize {
4205        self.storage_key.get()
4206    }
4207
4208    pub fn new(storage: SlotTable) -> Self {
4209        let storage_key = storage.storage_id();
4210        Self {
4211            storage_key: Cell::new(storage_key),
4212            inner: RefCell::new(SlotsHostInner {
4213                table: storage,
4214                nested_hosts: Vec::new(),
4215                lifecycle: slot::SlotLifecycleCoordinator::default(),
4216                runtime_state: None,
4217                active_pass: None,
4218            }),
4219        }
4220    }
4221
4222    pub fn note_nested_host(&self, nested: &Rc<SlotsHost>) {
4223        let Ok(mut inner) = self.inner.try_borrow_mut() else {
4224            return;
4225        };
4226        inner.nested_hosts.retain(|held| held.upgrade().is_some());
4227        if inner
4228            .nested_hosts
4229            .iter()
4230            .any(|held| held.upgrade().is_some_and(|host| Rc::ptr_eq(&host, nested)))
4231        {
4232            return;
4233        }
4234        inner.nested_hosts.push(Rc::downgrade(nested));
4235    }
4236
4237    pub(crate) fn forget_effects(&self) -> bool {
4238        let (forgotten, nested, runtime_state) = {
4239            let Ok(mut inner) = self.inner.try_borrow_mut() else {
4240                return false;
4241            };
4242            if inner.active_pass.is_some() {
4243                return false;
4244            }
4245            let drops = inner.table.take_effect_drops();
4246            inner.nested_hosts.retain(|held| held.upgrade().is_some());
4247            let nested: Vec<Rc<SlotsHost>> = inner
4248                .nested_hosts
4249                .iter()
4250                .filter_map(std::rc::Weak::upgrade)
4251                .collect();
4252            (drops, nested, inner.runtime_state.clone())
4253        };
4254        let mut any = !forgotten.is_empty();
4255        drop(forgotten);
4256        for host in nested {
4257            any |= host.forget_effects();
4258        }
4259        if any && let Some(runtime_state) = runtime_state {
4260            runtime_state.force_recompose_host_scopes(self.storage_key());
4261        }
4262        any
4263    }
4264
4265    pub(crate) fn bind_runtime_state(&self, state: &Rc<crate::composer::ComposerRuntimeState>) {
4266        let mut inner = self.inner.borrow_mut();
4267        inner.runtime_state = Some(Rc::clone(state));
4268    }
4269
4270    pub(crate) fn rebind_orphaned_runtime_state(
4271        &self,
4272        state: &Rc<crate::composer::ComposerRuntimeState>,
4273    ) -> bool {
4274        let inner = self.inner.borrow();
4275        if inner.active_pass.is_some() {
4276            log::error!("cannot rebind SlotsHost during an active pass");
4277            return false;
4278        }
4279        let Some(bound_state) = inner.runtime_state.as_ref() else {
4280            drop(inner);
4281            self.bind_runtime_state(state);
4282            return true;
4283        };
4284        if Rc::ptr_eq(bound_state, state) {
4285            return true;
4286        }
4287        if bound_state.has_live_applier_host() {
4288            return false;
4289        }
4290        drop(inner);
4291
4292        let mut inner = self.inner.borrow_mut();
4293        let Some(bound_state) = inner.runtime_state.as_ref() else {
4294            inner.runtime_state = Some(Rc::clone(state));
4295            return true;
4296        };
4297        if Rc::ptr_eq(bound_state, state) {
4298            return true;
4299        }
4300        if bound_state.has_live_applier_host() {
4301            return false;
4302        }
4303
4304        let previous_state = Rc::clone(bound_state);
4305        let mut lifecycle = std::mem::take(&mut inner.lifecycle);
4306        lifecycle.flush_pending_drops();
4307        let host_key = self.storage_key();
4308        if previous_state
4309            .dispose_retained_subtrees_for_host(host_key, &mut inner.table, &mut lifecycle)
4310            .is_err()
4311        {
4312            inner.lifecycle = lifecycle;
4313            return false;
4314        }
4315        previous_state.clear_host(self);
4316        lifecycle.flush_pending_drops();
4317        inner.runtime_state = Some(Rc::clone(state));
4318        inner.lifecycle = lifecycle;
4319        true
4320    }
4321
4322    pub(crate) fn runtime_state(&self) -> Option<Rc<crate::composer::ComposerRuntimeState>> {
4323        self.inner.borrow().runtime_state.clone()
4324    }
4325
4326    pub(crate) fn borrow(&self) -> Ref<'_, SlotTable> {
4327        Ref::map(self.inner.borrow(), |inner| &inner.table)
4328    }
4329
4330    pub(crate) fn borrow_mut(&self) -> RefMut<'_, SlotTable> {
4331        RefMut::map(self.inner.borrow_mut(), |inner| &mut inner.table)
4332    }
4333
4334    pub fn into_table(self: Rc<Self>) -> Result<SlotTable, NodeError> {
4335        if Rc::strong_count(&self) != 1 {
4336            return Err(NodeError::SlotHostUnavailable {
4337                operation: "SlotsHost::into_table",
4338                reason: "other host references are alive",
4339            });
4340        }
4341        self.take_table_for_transfer()
4342    }
4343
4344    fn take_table_for_transfer(&self) -> Result<SlotTable, NodeError> {
4345        let inner = self.inner.borrow();
4346        if inner.active_pass.is_some() {
4347            return Err(NodeError::SlotHostUnavailable {
4348                operation: "SlotsHost::into_table",
4349                reason: "slot pass is active",
4350            });
4351        }
4352        drop(inner);
4353        let mut inner = self.inner.borrow_mut();
4354        let mut lifecycle = std::mem::take(&mut inner.lifecycle);
4355        lifecycle.flush_pending_drops();
4356        if let Some(state) = inner.runtime_state.clone() {
4357            let host_key = self.storage_key();
4358            state.dispose_retained_subtrees_for_host(host_key, &mut inner.table, &mut lifecycle)?;
4359            state.clear_host(self);
4360            lifecycle.flush_pending_drops();
4361        }
4362        let taken = std::mem::take(&mut inner.table);
4363        self.storage_key.set(inner.table.storage_id());
4364        inner.runtime_state = None;
4365        inner.lifecycle = lifecycle;
4366        Ok(taken)
4367    }
4368
4369    pub fn reset(&self) -> Result<(), NodeError> {
4370        let inner = self.inner.borrow();
4371        if inner.active_pass.is_some() {
4372            return Err(NodeError::SlotHostUnavailable {
4373                operation: "SlotsHost::reset",
4374                reason: "slot pass is active",
4375            });
4376        }
4377        let runtime_state = inner.runtime_state.clone();
4378        drop(inner);
4379        let mut inner = self.inner.borrow_mut();
4380        let mut lifecycle = std::mem::take(&mut inner.lifecycle);
4381        if let Some(state) = runtime_state {
4382            let host_key = self.storage_key();
4383            state.dispose_retained_subtrees_for_host(host_key, &mut inner.table, &mut lifecycle)?;
4384            state.clear_host(self);
4385        }
4386        lifecycle.dispose_slot_table(&mut inner.table);
4387        inner.table = SlotTable::default();
4388        self.storage_key.set(inner.table.storage_id());
4389        inner.runtime_state = None;
4390        inner.lifecycle = slot::SlotLifecycleCoordinator::default();
4391        Ok(())
4392    }
4393
4394    pub(crate) fn abandon_after_apply_failure(&self) {
4395        let inner = self.inner.borrow();
4396        if inner.active_pass.is_some() {
4397            log::error!("cannot abandon SlotsHost during an active pass");
4398            return;
4399        }
4400        let runtime_state = inner.runtime_state.clone();
4401        drop(inner);
4402        let mut inner = self.inner.borrow_mut();
4403        let mut lifecycle = std::mem::take(&mut inner.lifecycle);
4404        if let Some(state) = runtime_state {
4405            let host_key = self.storage_key();
4406            state.abandon_retained_subtrees_for_host(host_key, &mut inner.table, &mut lifecycle);
4407        }
4408        lifecycle.dispose_slot_table(&mut inner.table);
4409        inner.table = SlotTable::default();
4410        self.storage_key.set(inner.table.storage_id());
4411        inner.runtime_state = None;
4412        inner.lifecycle = slot::SlotLifecycleCoordinator::default();
4413    }
4414
4415    pub(crate) fn debug_stats(&self) -> SlotTableDebugStats {
4416        let inner = self.inner.borrow();
4417        let local = inner.table.debug_stats();
4418        let lifecycle = inner.lifecycle.debug_stats();
4419        let retention = inner
4420            .runtime_state
4421            .clone()
4422            .map(|state| state.slot_retention_debug_stats(self))
4423            .unwrap_or_default();
4424        SlotTableDebugStats::from_parts(local, lifecycle, retention)
4425    }
4426
4427    pub(crate) fn debug_snapshot(&self) -> slot::SlotDebugSnapshot {
4428        let inner = self.inner.borrow();
4429        let mut snapshot = inner.table.debug_snapshot();
4430        if let Some(state) = inner.runtime_state.clone() {
4431            state.fill_slot_debug_snapshot(self, &mut snapshot);
4432        }
4433        snapshot
4434    }
4435
4436    pub(crate) fn begin_pass(&self, mode: slot::SlotPassMode) {
4437        let mut inner = self.inner.borrow_mut();
4438        if inner.active_pass.is_some() {
4439            log::error!("slot pass already active for host");
4440            return;
4441        }
4442        let mut state = slot::SlotWriteSessionState::default();
4443        state.reset_for_pass(mode);
4444        inner.active_pass = Some(ActivePassState { state });
4445    }
4446
4447    pub(crate) fn has_active_pass(&self) -> bool {
4448        self.inner.borrow().active_pass.is_some()
4449    }
4450
4451    pub(crate) fn try_push_branch_fold(&self, key: Key) -> Option<usize> {
4452        let mut inner = self.inner.try_borrow_mut().ok()?;
4453        let pass = inner.active_pass.as_mut()?;
4454        Some(pass.state.push_branch_fold(key))
4455    }
4456
4457    pub(crate) fn try_close_branch_fold(&self, token: usize) -> bool {
4458        let Ok(mut inner) = self.inner.try_borrow_mut() else {
4459            return false;
4460        };
4461        let Some(pass) = inner.active_pass.as_mut() else {
4462            return false;
4463        };
4464        pass.state.close_branch_fold(token);
4465        true
4466    }
4467
4468    pub(crate) fn abandon_active_pass(&self) {
4469        self.inner.borrow_mut().active_pass = None;
4470    }
4471
4472    pub(crate) fn with_write_session<R>(
4473        &self,
4474        f: impl FnOnce(&mut slot::SlotWriteSession<'_>) -> R,
4475    ) -> R {
4476        let mut inner = self.inner.borrow_mut();
4477        let SlotsHostInner {
4478            table,
4479            lifecycle,
4480            active_pass,
4481            ..
4482        } = &mut *inner;
4483        let active_pass = active_pass
4484            .as_mut()
4485            .expect("slot write session requires an active pass");
4486        let mut session = table.write_session(lifecycle, &mut active_pass.state);
4487        f(&mut session)
4488    }
4489
4490    pub(crate) fn with_table_and_lifecycle_mut<R>(
4491        &self,
4492        f: impl FnOnce(&mut SlotTable, &mut slot::SlotLifecycleCoordinator) -> R,
4493    ) -> R {
4494        let mut inner = self.inner.borrow_mut();
4495        let SlotsHostInner {
4496            table, lifecycle, ..
4497        } = &mut *inner;
4498        f(table, lifecycle)
4499    }
4500
4501    pub(crate) fn finish_pass(
4502        &self,
4503        applier: &mut dyn Applier,
4504    ) -> Result<FinishedSlotPass, NodeError> {
4505        let mut inner = self.inner.borrow_mut();
4506        let SlotsHostInner {
4507            table,
4508            lifecycle,
4509            active_pass: active_pass_slot,
4510            ..
4511        } = &mut *inner;
4512        let Some(mut active_pass) = active_pass_slot.take() else {
4513            return Ok(FinishedSlotPass::default());
4514        };
4515
4516        active_pass.state.flush_payload_location_refreshes(table);
4517
4518        #[cfg(debug_assertions)]
4519        if let Err(err) = active_pass.state.validate(table) {
4520            log::error!("slot writer invariant violation before finalize_pass: {err:?}");
4521            return Err(NodeError::SlotHostUnavailable {
4522                operation: "SlotsHost::finish_pass",
4523                reason: "slot writer invariant violation",
4524            });
4525        }
4526
4527        let detached_root_children = {
4528            let mut session = table.write_session(lifecycle, &mut active_pass.state);
4529            session.finalize_pass(applier)?
4530        };
4531
4532        Ok(FinishedSlotPass {
4533            outcome: SlotPassOutcome {
4534                compacted: active_pass.state.request_compaction,
4535                compact_anchor_registry_storage: active_pass
4536                    .state
4537                    .request_anchor_storage_compaction,
4538                compact_payload_storage: active_pass.state.request_payload_storage_compaction,
4539            },
4540            detached_root_children,
4541        })
4542    }
4543
4544    pub(crate) fn flush_pending_drops(&self) {
4545        self.inner.borrow_mut().lifecycle.flush_pending_drops();
4546    }
4547
4548    pub(crate) fn complete_pass_cleanup(&self, outcome: &SlotPassOutcome) {
4549        let mut inner = self.inner.borrow_mut();
4550        let SlotsHostInner {
4551            table,
4552            lifecycle,
4553            runtime_state,
4554            ..
4555        } = &mut *inner;
4556        lifecycle.flush_pending_drops();
4557        if outcome.compacted {
4558            table.compact_storage();
4559            lifecycle.compact_storage();
4560        }
4561        if let Some(state) = runtime_state.clone() {
4562            state.compact_table_identity_storage_for_host(
4563                self,
4564                table,
4565                outcome.compact_anchor_registry_storage,
4566                outcome.compact_payload_storage,
4567            );
4568        } else {
4569            if outcome.compact_anchor_registry_storage {
4570                table.compact_anchor_registry_storage(None);
4571            }
4572            if outcome.compact_payload_storage {
4573                table.compact_payload_anchor_registry_storage(None);
4574            }
4575        }
4576        table.assert_fast_integrity("slot pass cleanup");
4577        #[cfg(any(test, debug_assertions))]
4578        {
4579            table.debug_verify();
4580            if let Some(state) = runtime_state.clone() {
4581                state.debug_verify_host(self, table);
4582            }
4583        }
4584    }
4585}
4586
4587fn build_child_positions(children: &[NodeId]) -> HashMap<NodeId, usize> {
4588    let mut positions = HashMap::default();
4589    positions.reserve(children.len());
4590    for (index, &child) in children.iter().enumerate() {
4591        positions.insert(child, index);
4592    }
4593    positions
4594}
4595
4596fn refresh_child_positions(
4597    current: &[NodeId],
4598    positions: &mut HashMap<NodeId, usize>,
4599    start: usize,
4600    end: usize,
4601) {
4602    if current.is_empty() || start >= current.len() {
4603        return;
4604    }
4605    let end = end.min(current.len() - 1);
4606    for (offset, &child) in current[start..=end].iter().enumerate() {
4607        positions.insert(child, start + offset);
4608    }
4609}
4610
4611fn insert_child_into_diff_state(
4612    current: &mut ChildList,
4613    positions: &mut HashMap<NodeId, usize>,
4614    index: usize,
4615    child: NodeId,
4616) {
4617    let index = index.min(current.len());
4618    current.insert(index, child);
4619    refresh_child_positions(current, positions, index, current.len() - 1);
4620}
4621
4622fn move_child_in_diff_state(
4623    current: &mut ChildList,
4624    positions: &mut HashMap<NodeId, usize>,
4625    from_index: usize,
4626    target_index: usize,
4627) -> usize {
4628    let child = current.remove(from_index);
4629    let to_index = target_index.min(current.len());
4630    current.insert(to_index, child);
4631    refresh_child_positions(
4632        current,
4633        positions,
4634        from_index.min(to_index),
4635        from_index.max(to_index),
4636    );
4637    to_index
4638}
4639
4640pub(crate) use state::MutableStateInner;
4641pub use state::{
4642    MutableState, OwnedMutableState, SnapshotStateList, SnapshotStateMap, State,
4643    StateSubscriptionHold,
4644};
4645
4646fn hash_key<K: Hash>(key: &K) -> Key {
4647    let mut hasher = hash::default::new();
4648    key.hash(&mut hasher);
4649    hasher.finish()
4650}
4651
4652pub(crate) fn explicit_group_key_seed<K: Hash>(
4653    key: &K,
4654    caller: &'static std::panic::Location<'static>,
4655) -> slot::GroupKeySeed {
4656    let source_key = location_key(caller.file(), caller.line(), caller.column());
4657    let explicit_key = hash_key(key);
4658    slot::GroupKeySeed::keyed(source_key, explicit_key)
4659}
4660
4661#[cfg(test)]
4662#[path = "tests/mod.rs"]
4663mod tests;
4664
4665#[cfg(test)]
4666#[path = "tests/recursive_decrease_increase_test.rs"]
4667mod recursive_decrease_increase_test;
4668
4669pub mod collections;
4670pub mod hash;
4671
4672/// Where a test writes real files. Behind `test-helpers` so only a test build
4673/// of the workspace carries it.
4674#[cfg(any(test, feature = "test-helpers"))]
4675pub mod test_scratch;
4676#[cfg(any(test, feature = "test-helpers"))]
4677pub use test_scratch::test_scratch_dir;
4678
4679pub(crate) fn note_structural(reason: &str, parent_id: NodeId, child_id: NodeId) {
4680    if env_flag!("CRANPOSE_STRUCTURAL_DIAG") {
4681        eprintln!("[structural] {reason} parent={parent_id} child={child_id}");
4682    }
4683}
4684
4685pub(crate) fn note_structural_move(parent_id: NodeId, from_index: usize, to_index: usize) {
4686    if env_flag!("CRANPOSE_STRUCTURAL_DIAG") {
4687        eprintln!("[structural] move parent={parent_id} from={from_index} to={to_index}");
4688    }
4689}