Skip to main content

cranpose_core/
composition.rs

1use std::rc::Rc;
2
3use web_time::Instant;
4
5use crate::{
6    Applier, ApplierGuard, ApplierHost, Composer, ConcreteApplierHost, DIAGNOSTICS,
7    DefaultScheduler, Key, NodeError, NodeId, PausableContent, RecomposeScope, RetentionPolicy,
8    Runtime, RuntimeHandle, ScopeId, SlotDebugSnapshot, SlotTable, SlotTableDebugStats, SlotsHost,
9    debug_scope_invalidation_sources, debug_scope_label, runtime, scheduler_ref,
10};
11
12mod scope_groups;
13
14use scope_groups::ScopeGroups;
15
16/// A running composition that turns root content into nodes. `A` is the applier type that creates
17/// and edits those nodes.
18pub struct Composition<A: Applier + 'static> {
19    /// The composer of the last pass over the root slots, kept so the next
20    /// pass reuses its core. First, so it lets go of the tree before the
21    /// fields below do.
22    parked_composer: Option<Composer>,
23    pub(crate) composer_state: Rc<crate::composer::ComposerRuntimeState>,
24    pub(crate) slots: Rc<SlotsHost>,
25    pub(crate) applier: Rc<ConcreteApplierHost<A>>,
26    pub(crate) runtime: Runtime,
27    pub(crate) root: Option<NodeId>,
28    pub(crate) root_key: Option<Key>,
29    pub(crate) root_render_requested: bool,
30    // Boxed: a pass takes it out and puts it back, and a move of the box
31    // copies a pointer where a move of the groups copies their storage.
32    scope_groups: Option<Box<ScopeGroups>>,
33    #[cfg(any(test, feature = "leak-debug"))]
34    last_pass_stats: CompositionPassDebugStats,
35    teardown: Option<runtime::StateTeardownScope>,
36}
37
38/// The budget of a frame's layout pass for pausable content, which closes
39/// when it drops: content that waited asks for the next frame.
40#[doc(hidden)]
41pub struct LayoutBudget {
42    state: Rc<crate::composer::ComposerRuntimeState>,
43    runtime: RuntimeHandle,
44}
45
46impl Drop for LayoutBudget {
47    fn drop(&mut self) {
48        self.state.pausing.close_layout(&self.runtime);
49    }
50}
51
52/// Upper bound on chained root-render replays and scope-recomposition rounds.
53///
54/// Each root render clears `root_render_requested` but may re-raise it if a
55/// recompose pass inside `render()` promotes a scope callback to the root
56/// (see `Composer::recompose_group` in recompose.rs — callbacks that cannot
57/// run invalidate their `callback_promotion_target`, and if no ancestor can
58/// absorb the callback, `request_root_render()` is called). Each promotion
59/// walks up one parent scope, so natural convergence is bounded by the
60/// composition depth. The same invariant bounds `process_invalid_scopes`:
61/// recomposing a scope may invalidate others, but the chain must terminate.
62///
63/// This constant is a safety net for reentrant-render bugs. Exceeding it
64/// trips a `debug_assert!` in dev/test builds (loud failure so regressions
65/// are caught immediately) and falls back to a break + `log::error!` in
66/// release builds so end users do not see the UI thread panic.
67pub const ROOT_RENDER_REPLAY_LIMIT: usize = 100;
68
69impl<A: Applier + 'static> Composition<A> {
70    /// Creates a composition that builds its nodes through `applier` and uses a new runtime with
71    /// the default scheduler.
72    pub fn new(applier: A) -> Self {
73        Self::with_runtime(applier, Runtime::new(scheduler_ref(DefaultScheduler)))
74    }
75
76    /// Creates a composition that builds its nodes through `applier` and uses `runtime` for state
77    /// invalidation and scheduling.
78    pub fn with_runtime(applier: A, runtime: Runtime) -> Self {
79        let composer_state = Rc::new(crate::composer::ComposerRuntimeState::default());
80        let slots = Rc::new(SlotsHost::new(SlotTable::new()));
81        let applier = Rc::new(ConcreteApplierHost::new(applier));
82        Self {
83            parked_composer: None,
84            composer_state,
85            slots,
86            applier,
87            runtime,
88            root: None,
89            root_key: None,
90            root_render_requested: false,
91            scope_groups: None,
92            #[cfg(any(test, feature = "leak-debug"))]
93            last_pass_stats: CompositionPassDebugStats::default(),
94            teardown: None,
95        }
96    }
97
98    /// Returns the root group key captured from the most recent `render()` call,
99    /// or `None` before the first render.
100    pub fn root_key(&self) -> Option<Key> {
101        self.root_key
102    }
103
104    /// Sets the budget and the eviction order for groups retained when they leave the composition.
105    /// See `RetentionMode`.
106    pub fn set_retention_policy(&self, policy: RetentionPolicy) {
107        self.composer_state.set_retention_policy(policy);
108    }
109
110    fn slots_host(&self) -> Rc<SlotsHost> {
111        Rc::clone(&self.slots)
112    }
113
114    fn applier_host(&self) -> Rc<dyn ApplierHost> {
115        Rc::<ConcreteApplierHost<A>>::clone(&self.applier)
116    }
117
118    #[expect(clippy::print_stderr, reason = "COMPOSE_DEBUG_SLOT_TABLE asks for it")]
119    fn maybe_dump_slot_table(&self, label: &str) {
120        if !DIAGNOSTICS.compose_debug_slot_table.is_set() {
121            return;
122        }
123        eprintln!(
124            "[COMPOSE_DEBUG_SLOT_TABLE] {label}\n{:#?}",
125            self.debug_slot_snapshot()
126        );
127    }
128
129    /// Returns whether a root render was requested and clears the request.
130    pub fn take_root_render_request(&mut self) -> bool {
131        std::mem::take(&mut self.root_render_requested)
132    }
133
134    /// Requests another render of the root content and schedules a frame for it.
135    pub fn request_root_render(&mut self) {
136        self.root_render_requested = true;
137        self.runtime.handle().schedule();
138    }
139
140    fn finalize_runtime_state(&mut self) {
141        if !self.runtime.has_updates()
142            && !self.runtime.has_invalid_scopes()
143            && !self.runtime.has_frame_callbacks()
144            && !self.runtime.has_pending_ui()
145        {
146            self.runtime.set_needs_frame(false);
147        }
148    }
149
150    fn abandon_host_after_apply_failure(&mut self, host: &Rc<SlotsHost>) {
151        host.abandon_after_apply_failure();
152        if Rc::ptr_eq(host, &self.slots) {
153            self.root = None;
154        }
155        self.root_render_requested = true;
156        self.finalize_runtime_state();
157    }
158
159    /// Applies the commands `composer`'s pass queued, in its queue, which
160    /// keeps its storage for the next pass, and then the runtime's updates.
161    fn apply_commands_and_updates_for_host(
162        &mut self,
163        host: &Rc<SlotsHost>,
164        runtime_handle: &RuntimeHandle,
165        composer: &Composer,
166    ) -> Result<(), NodeError> {
167        let result = composer.with_commands(|commands| {
168            let mut applier = self.applier.borrow_dyn();
169            let mut result = commands.apply(&mut *applier);
170            if result.is_ok() {
171                for update in runtime_handle.take_updates() {
172                    if let Err(err) = update.apply(&mut *applier) {
173                        result = Err(err);
174                        break;
175                    }
176                }
177            }
178            result
179        });
180        if result.is_err() {
181            self.abandon_host_after_apply_failure(host);
182        }
183        result
184    }
185
186    fn render_root_pass(&mut self, key: Key, content: &mut dyn FnMut()) -> Result<(), NodeError> {
187        self.root_key = Some(key);
188        self.root_render_requested = false;
189        let runtime_handle = self.runtime_handle();
190        runtime_handle.drain_ui();
191        let side_effects = {
192            let _teardown = runtime::enter_state_teardown_scope();
193            let composer = Composer::new_with_shared_state(
194                Rc::clone(&self.composer_state),
195                Rc::clone(&self.slots),
196                Rc::<ConcreteApplierHost<A>>::clone(&self.applier),
197                runtime_handle.clone(),
198                self.root,
199            );
200            let (root, side_effects, compact_applier) = composer.install(|composer| {
201                let ((), outcome) = composer.try_with_slot_host_pass(
202                    Rc::clone(&self.slots),
203                    crate::slot::SlotPassMode::Compose,
204                    |composer| composer.with_group(key, |_| content()),
205                )?;
206                let root = composer.root();
207                let side_effects = composer.take_side_effects();
208                Ok((root, side_effects, outcome.compacted))
209            })?;
210            #[cfg(any(test, feature = "leak-debug"))]
211            composer.with_commands(|commands| self.last_pass_stats.record(commands, &side_effects));
212            self.apply_commands_and_updates_for_host(
213                &Rc::clone(&self.slots),
214                &runtime_handle,
215                &composer,
216            )?;
217            if compact_applier {
218                self.applier.compact();
219                self.applier.borrow_dyn().clear_recycled_nodes();
220            }
221
222            self.root = root;
223            side_effects
224        };
225        runtime_handle.drain_ui();
226        for effect in side_effects {
227            effect();
228        }
229        runtime_handle.drain_ui();
230        self.maybe_dump_slot_table("root_render_pass");
231        Ok(())
232    }
233
234    fn reconcile_with_content(
235        &mut self,
236        key: Key,
237        content: &mut dyn FnMut(),
238    ) -> Result<bool, NodeError> {
239        self.root_key = Some(key);
240        let mut did_work = false;
241        let mut root_render_replays = 0usize;
242        loop {
243            did_work |= self.process_invalid_scopes_within_budget()?;
244            if !self.take_root_render_request() {
245                return Ok(did_work);
246            }
247
248            root_render_replays += 1;
249            if root_render_replays > ROOT_RENDER_REPLAY_LIMIT {
250                log::error!(
251                    "root render replay looped past {ROOT_RENDER_REPLAY_LIMIT} iterations; breaking to keep UI responsive"
252                );
253                return Err(NodeError::RecompositionLimitExceeded {
254                    operation: "root render replay",
255                    limit: ROOT_RENDER_REPLAY_LIMIT,
256                });
257            }
258
259            self.render_root_pass(key, content)?;
260            did_work = true;
261        }
262    }
263
264    /// Composes `content` as the root group identified by `key`, then recomposes the scopes that
265    /// became invalid during the pass.
266    pub fn render(&mut self, key: Key, mut content: impl FnMut()) -> Result<(), NodeError> {
267        #[cfg(any(test, feature = "leak-debug"))]
268        {
269            self.last_pass_stats = CompositionPassDebugStats::default();
270        }
271        self.render_root_pass(key, &mut content)?;
272        let _ = self.process_invalid_scopes()?;
273        Ok(())
274    }
275
276    /// Perform a root render and continue replaying any resulting root-render
277    /// requests until the composition reaches a stable fixpoint.
278    pub fn render_stable(&mut self, key: Key, mut content: impl FnMut()) -> Result<(), NodeError> {
279        #[cfg(any(test, feature = "leak-debug"))]
280        {
281            self.last_pass_stats = CompositionPassDebugStats::default();
282        }
283        self.render_root_pass(key, &mut content)?;
284        let _ = self.reconcile_with_content(key, &mut content)?;
285        Ok(())
286    }
287
288    /// Process invalid scopes and any resulting root-render requests until the
289    /// composition reaches a stable fixpoint for the supplied root content.
290    pub fn reconcile(&mut self, key: Key, mut content: impl FnMut()) -> Result<bool, NodeError> {
291        self.reconcile_with_content(key, &mut content)
292    }
293
294    /// Returns true if composition needs to process invalid scopes (recompose).
295    ///
296    /// This checks both:
297    /// - `has_updates()`: composition scopes that were invalidated by state changes
298    /// - `needs_frame()`: animation callbacks that may have pending work
299    ///
300    /// Note: For scroll performance, ensure scroll state changes use `Cell<T>` instead
301    /// of `MutableState<T>` to avoid triggering recomposition on every scroll frame.
302    pub fn should_render(&self) -> bool {
303        self.root_render_requested || self.runtime.needs_frame() || self.runtime.has_updates()
304    }
305
306    /// Whether any composition scope is actually invalid, i.e. whether running
307    /// the composable tree could produce a different result than last time.
308    ///
309    /// Deliberately excludes [`Runtime::needs_frame`], which [`Self::should_render`]
310    /// includes. An armed frame callback means the *runtime* owes someone a
311    /// tick - a future to resume, a dispatcher to drain - and every app with a
312    /// game loop or a polling effect has one armed at all times. Re-running the
313    /// composition for it recomposes a tree that nothing invalidated. Callers
314    /// deciding "should I tick" want [`Self::should_render`]; callers deciding
315    /// "should I recompose" want this.
316    ///
317    /// It is only meaningful *after* the frame callbacks have been drained: a
318    /// callback that writes state invalidates its readers as it runs, so the
319    /// answer is a question about work already discovered, not work still to
320    /// come.
321    pub fn should_recompose(&self) -> bool {
322        self.root_render_requested || self.runtime.has_updates()
323    }
324
325    /// Sets how long a frame's composition runs before composables that
326    /// pausable content calls for the first time wait for a later frame.
327    /// `None`, the default, composes such content in full in its pass. Each
328    /// frame still runs at least one body that waits.
329    pub fn set_pausable_budget(&self, budget: Option<std::time::Duration>) {
330        self.composer_state.pausing.set_budget(budget);
331    }
332
333    /// Opens the frame's budget for pausable content that a measure composes,
334    /// as `BoxWithConstraints` composes its content, until the returned
335    /// budget drops: that content composes across frames as the
336    /// composition's own does.
337    #[doc(hidden)]
338    pub fn open_layout_budget(&self) -> LayoutBudget {
339        self.composer_state.pausing.open_layout();
340        LayoutBudget {
341            state: Rc::clone(&self.composer_state),
342            runtime: self.runtime.handle(),
343        }
344    }
345
346    /// Returns a handle to the runtime this composition uses.
347    pub fn runtime_handle(&self) -> RuntimeHandle {
348        self.runtime.handle()
349    }
350
351    /// The runtime this composition runs on, to ask without a handle.
352    pub fn runtime(&self) -> &Runtime {
353        &self.runtime
354    }
355
356    /// Borrows the applier mutably. Panics if it is already borrowed.
357    pub fn applier_mut(&mut self) -> ApplierGuard<'_, A> {
358        self.applier.borrow_typed()
359    }
360
361    /// Returns the root node a pass produced, or `None` if none has yet.
362    pub fn root(&self) -> Option<NodeId> {
363        self.root
364    }
365
366    /// Returns one `(group index, call site key, scope id, subtree length)` tuple per group in the
367    /// slot table, for debugging.
368    pub fn debug_dump_slot_table_groups(&self) -> Vec<(usize, Key, Option<ScopeId>, usize)> {
369        self.slots.borrow().debug_dump_groups()
370    }
371
372    /// Returns the entries of the slot table, for debugging.
373    pub fn debug_dump_slot_entries(&self) -> Vec<crate::SlotDebugEntry> {
374        self.slots.borrow().debug_dump_slot_entries()
375    }
376
377    /// Returns the heap memory in bytes that the slot table holds.
378    pub fn slot_table_heap_bytes(&self) -> usize {
379        self.slots.borrow().heap_bytes()
380    }
381
382    /// Returns size counters of the slot table, for debugging.
383    pub fn debug_slot_table_stats(&self) -> SlotTableDebugStats {
384        self.slots.debug_stats()
385    }
386
387    /// Returns a copy of the slot table's structure, for debugging.
388    pub fn debug_slot_snapshot(&self) -> SlotDebugSnapshot {
389        self.slots.debug_snapshot()
390    }
391
392    /// Returns the buffer sizes of the last composition pass, for debugging.
393    #[cfg(any(test, feature = "leak-debug"))]
394    pub fn debug_last_pass_stats(&self) -> CompositionPassDebugStats {
395        self.last_pass_stats
396    }
397
398    #[cfg(test)]
399    pub(crate) fn debug_validate_slots(&self) -> Result<(), crate::slot::SlotInvariantError> {
400        let table = self.slots.borrow();
401        table.validate()?;
402        self.composer_state
403            .validate_host_retention(self.slots.as_ref(), &table)
404    }
405
406    /// The slots host `scope` recomposes in.
407    fn host_for_scope(&self, scope: &RecomposeScope, root_host: &Rc<SlotsHost>) -> Rc<SlotsHost> {
408        scope
409            .slots_runtime_state()
410            .and_then(|state| {
411                scope
412                    .slots_storage_key()
413                    .and_then(|storage_key| state.host_for_storage_key(storage_key))
414            })
415            .or_else(|| {
416                scope
417                    .slots_storage_key()
418                    .and_then(|storage_key| self.composer_state.host_for_storage_key(storage_key))
419            })
420            .unwrap_or_else(|| Rc::clone(root_host))
421    }
422
423    // Recomposes within a frame's budget for pausable content: bodies that
424    // wait run after the invalid scopes while the budget lasts.
425    fn process_invalid_scopes_within_budget(&mut self) -> Result<bool, NodeError> {
426        self.composer_state.pausing.start_budget();
427        let result = self.process_invalid_scopes_until_root_request();
428        self.composer_state.pausing.end_budget(&self.runtime);
429        result
430    }
431
432    fn process_invalid_scopes_until_root_request(&mut self) -> Result<bool, NodeError> {
433        let runtime_handle = self.runtime_handle();
434        let mut did_recompose = false;
435        let mut loop_count = 0;
436        loop {
437            loop_count += 1;
438            if loop_count > ROOT_RENDER_REPLAY_LIMIT {
439                log::error!(
440                    "process_invalid_scopes looped past {ROOT_RENDER_REPLAY_LIMIT} iterations; breaking to keep UI responsive"
441                );
442                return Err(NodeError::RecompositionLimitExceeded {
443                    operation: "process_invalid_scopes",
444                    limit: ROOT_RENDER_REPLAY_LIMIT,
445                });
446            }
447            runtime_handle.drain_ui();
448            self.dispose_forgotten_movables()?;
449            let (scopes, batch) = match runtime_handle.take_invalidated_scopes() {
450                Some(scopes) => (scopes, Batch::Invalid),
451                None => match self.composer_state.pausing.take_resumable() {
452                    Some((content, scopes)) => (scopes, Batch::Waiting(content)),
453                    None => break,
454                },
455            };
456            let Some(mut scopes) = self.rerun_derivations(&runtime_handle, scopes) else {
457                continue;
458            };
459            did_recompose = true;
460            let mut groups = self.scope_groups.take().unwrap_or_default();
461            groups.group(&mut scopes, |scope| self.host_for_scope(scope, &self.slots));
462            for (host, range) in groups.iter() {
463                let side_effects = self.recompose_host_scopes(
464                    host,
465                    &scopes[range.clone()],
466                    &batch,
467                    &runtime_handle,
468                )?;
469                runtime_handle.drain_ui();
470                for effect in side_effects {
471                    effect();
472                }
473                runtime_handle.drain_ui();
474                self.maybe_dump_slot_table("recompose_pass");
475                if self.root_render_requested {
476                    requeue_scopes(&runtime_handle, &batch, &scopes[range.end..]);
477                    break;
478                }
479            }
480            groups.clear();
481            self.scope_groups = Some(groups);
482            runtime_handle.recycle_scopes(scopes);
483            if let Batch::Waiting(content) = batch {
484                self.composer_state.pausing.finish_resumed(content);
485            }
486            if self.root_render_requested {
487                break;
488            }
489        }
490        self.finalize_runtime_state();
491        Ok(did_recompose)
492    }
493
494    // Recomposes `scopes` of one slot host in one pass and gives back the
495    // side effects that the pass registered.
496    fn recompose_host_scopes(
497        &mut self,
498        host: &Rc<SlotsHost>,
499        scopes: &[RecomposeScope],
500        batch: &Batch,
501        runtime_handle: &RuntimeHandle,
502    ) -> Result<Vec<Box<dyn FnOnce()>>, NodeError> {
503        let shared_state = host
504            .runtime_state()
505            .or_else(|| scopes.first().and_then(RecomposeScope::slots_runtime_state))
506            .unwrap_or_else(|| Rc::clone(&self.composer_state));
507        let threshold_ms = DIAGNOSTICS.recompose_scope_telemetry_ms.threshold_ms();
508        let _teardown = runtime::enter_state_teardown_scope();
509        let composer = Composer::for_pass(
510            self.parked_composer.take(),
511            shared_state,
512            Rc::clone(host),
513            self.applier_host(),
514            runtime_handle.clone(),
515            self.root,
516        );
517        composer.parent_stack().clear();
518        let (root, side_effects, requested_root_render, compact_applier) =
519            composer.install(|composer| {
520                let ((), outcome) = composer.try_with_slot_host_pass(
521                    Rc::clone(host),
522                    crate::slot::SlotPassMode::Recompose,
523                    |composer| match (batch, threshold_ms) {
524                        (Batch::Invalid, None) => {
525                            for scope in scopes {
526                                composer.recompose_group(scope);
527                            }
528                        }
529                        (Batch::Invalid, Some(threshold_ms)) => {
530                            recompose_timed(composer, scopes, threshold_ms);
531                        }
532                        (Batch::Waiting(content), _) => {
533                            composer.resume_waiting_bodies(content, scopes);
534                        }
535                    },
536                )?;
537                let root = composer.root();
538                let side_effects = composer.take_side_effects();
539                let requested_root_render = composer.take_root_render_request();
540                Ok((root, side_effects, requested_root_render, outcome.compacted))
541            })?;
542        #[cfg(any(test, feature = "leak-debug"))]
543        composer.with_commands(|commands| self.last_pass_stats.record(commands, &side_effects));
544        self.apply_commands_and_updates_for_host(host, runtime_handle, &composer)?;
545        if compact_applier {
546            self.applier.compact();
547            self.applier.borrow_dyn().clear_recycled_nodes();
548        }
549        if root.is_some() {
550            self.root = root;
551        }
552        if requested_root_render {
553            self.root_render_requested = true;
554        }
555        self.park_composer(host, composer);
556        Ok(side_effects)
557    }
558
559    /// Recomposes the scopes that state changes invalidated, until none remain or a root render is
560    /// requested. Returns `true` if a pass recomposed content.
561    pub fn process_invalid_scopes(&mut self) -> Result<bool, NodeError> {
562        self.process_invalid_scopes_within_budget()
563    }
564
565    // Derives the values of the derivations among `scopes` again and gives
566    // back the other scopes, or none when none is left. A derivation reads
567    // no slot: it needs a composer for the states it reads to subscribe it,
568    // and no pass over a slot table. A value that changed invalidates its
569    // readers, for the next batch.
570    fn rerun_derivations(
571        &mut self,
572        runtime: &RuntimeHandle,
573        mut scopes: Vec<RecomposeScope>,
574    ) -> Option<Vec<RecomposeScope>> {
575        if scopes.iter().any(RecomposeScope::is_derivation) {
576            self.rerun_derivations_of(runtime, &mut scopes);
577        }
578        if scopes.is_empty() {
579            runtime.recycle_scopes(scopes);
580            return None;
581        }
582        Some(scopes)
583    }
584
585    fn rerun_derivations_of(&mut self, runtime: &RuntimeHandle, scopes: &mut Vec<RecomposeScope>) {
586        let _teardown = runtime::enter_state_teardown_scope();
587        let host = self.slots_host();
588        let composer = Composer::for_pass(
589            self.parked_composer.take(),
590            Rc::clone(&self.composer_state),
591            Rc::clone(&host),
592            self.applier_host(),
593            runtime.clone(),
594            self.root,
595        );
596        composer.install(|composer| {
597            for scope in scopes.iter().filter(|scope| scope.is_derivation()) {
598                composer.recompose_group(scope);
599            }
600        });
601        self.park_composer(&host, composer);
602        scopes.retain(|scope| !scope.is_derivation());
603    }
604
605    // Keeps the composer of a pass for the next pass. After a pass over
606    // another host's slots it is bound to the root's again, so the kept core
607    // holds no other host.
608    fn park_composer(&mut self, host: &Rc<SlotsHost>, composer: Composer) {
609        let Some(parked) = composer.park() else {
610            return;
611        };
612        self.parked_composer = if Rc::ptr_eq(host, &self.slots) {
613            Some(parked)
614        } else {
615            Composer::for_pass(
616                Some(parked),
617                Rc::clone(&self.composer_state),
618                self.slots_host(),
619                self.applier_host(),
620                self.runtime_handle(),
621                self.root,
622            )
623            .park()
624        };
625    }
626
627    fn dispose_forgotten_movables(&mut self) -> Result<(), NodeError> {
628        let ids = self.runtime.take_forgotten_movables();
629        if ids.is_empty() {
630            return Ok(());
631        }
632        self.forget_movables(&ids)
633    }
634
635    // Out of line: a pass rarely forgets movable content, and the check
636    // before this runs on every pass.
637    #[inline(never)]
638    fn forget_movables(&mut self, ids: &[Key]) -> Result<(), NodeError> {
639        let runtime_handle = self.runtime_handle();
640        let _teardown = runtime::enter_state_teardown_scope();
641        let host = self.slots_host();
642        let composer = Composer::new_with_shared_state(
643            Rc::clone(&self.composer_state),
644            Rc::clone(&host),
645            self.applier_host(),
646            runtime_handle.clone(),
647            self.root,
648        );
649        composer.install(|composer| composer.forget_movables(ids))?;
650        self.apply_commands_and_updates_for_host(&host, &runtime_handle, &composer)
651    }
652
653    /// Applies the node updates that the runtime has queued to the applier, without recomposing.
654    pub fn flush_pending_node_updates(&mut self) -> Result<(), NodeError> {
655        let updates = self.runtime.take_updates();
656        let mut applier = self.applier.borrow_dyn();
657        for update in updates {
658            update.apply(&mut *applier)?;
659        }
660        Ok(())
661    }
662}
663
664// Recomposes each scope and reports the ones that took `threshold_ms` or
665// more, as scope telemetry asks.
666#[expect(clippy::print_stderr, reason = "a scope telemetry threshold asks")]
667fn recompose_timed(composer: &Composer, scopes: &[RecomposeScope], threshold_ms: f64) {
668    for scope in scopes {
669        let start = Instant::now();
670        composer.recompose_group(scope);
671        let elapsed_ms = start.elapsed().as_secs_f64() * 1000.0;
672        if elapsed_ms >= threshold_ms {
673            eprintln!(
674                "[recompose-scope-telemetry] scope_id={} label={:?} elapsed_ms={elapsed_ms:.3} invalidation_sources={:?}",
675                scope.id(),
676                debug_scope_label(scope.id()),
677                debug_scope_invalidation_sources(scope.id())
678            );
679        }
680    }
681}
682
683// Where the scopes of a pass come from.
684enum Batch {
685    // Scopes that state changes invalidated.
686    Invalid,
687    // Bodies of pausable content that waited for this frame.
688    Waiting(PausableContent),
689}
690
691// Leaves the scopes that a root render request cut off for the next pass;
692// bodies of pausable content wait for a later frame.
693fn requeue_scopes(runtime_handle: &RuntimeHandle, batch: &Batch, scopes: &[RecomposeScope]) {
694    for scope in scopes {
695        match batch {
696            Batch::Invalid => runtime_handle.requeue_invalid_scope(scope),
697            Batch::Waiting(content) => content.keep_waiting(scope),
698        }
699    }
700}
701
702impl<A: Applier + 'static> Drop for Composition<A> {
703    fn drop(&mut self) {
704        #[cfg(target_os = "android")]
705        self.runtime.restore_thread_state();
706        self.teardown = Some(runtime::enter_state_teardown_scope());
707    }
708}
709
710/// The largest sizes that the command queues and the side effect list reached during one
711/// composition pass, for debugging memory use.
712#[cfg(any(test, feature = "leak-debug"))]
713#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
714pub struct CompositionPassDebugStats {
715    /// Most node commands queued at once.
716    pub commands_len: usize,
717    /// Largest capacity reserved for node commands.
718    pub commands_cap: usize,
719    /// Most bytes of command arguments queued at once.
720    pub command_payload_len_bytes: usize,
721    /// Largest capacity reserved for command arguments, in bytes.
722    pub command_payload_cap_bytes: usize,
723    /// Most child list updates queued at once.
724    pub sync_children_len: usize,
725    /// Largest capacity reserved for child list updates.
726    pub sync_children_cap: usize,
727    /// Most child ids stored for child list updates.
728    pub sync_child_ids_len: usize,
729    /// Largest capacity reserved for those child ids.
730    pub sync_child_ids_cap: usize,
731    /// Most side effects queued at once.
732    pub side_effects_len: usize,
733    /// Largest capacity reserved for the side effects.
734    pub side_effects_cap: usize,
735}
736
737#[cfg(any(test, feature = "leak-debug"))]
738impl CompositionPassDebugStats {
739    fn record(&mut self, commands: &crate::CommandQueue, side_effects: &Vec<Box<dyn FnOnce()>>) {
740        self.commands_len = self.commands_len.max(commands.len());
741        self.commands_cap = self.commands_cap.max(commands.capacity());
742        self.command_payload_len_bytes = self
743            .command_payload_len_bytes
744            .max(commands.payload_len_bytes());
745        self.command_payload_cap_bytes = self
746            .command_payload_cap_bytes
747            .max(commands.payload_capacity_bytes());
748        self.sync_children_len = self.sync_children_len.max(commands.sync_children.len());
749        self.sync_children_cap = self
750            .sync_children_cap
751            .max(commands.sync_children.capacity());
752        self.sync_child_ids_len = self.sync_child_ids_len.max(commands.sync_child_ids.len());
753        self.sync_child_ids_cap = self
754            .sync_child_ids_cap
755            .max(commands.sync_child_ids.capacity());
756        self.side_effects_len = self.side_effects_len.max(side_effects.len());
757        self.side_effects_cap = self.side_effects_cap.max(side_effects.capacity());
758    }
759}