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