Skip to main content

cranpose_core/
slots_host.rs

1use std::{
2    cell::{Cell, Ref, RefCell, RefMut},
3    rc::{Rc, Weak},
4};
5
6use crate::{
7    Applier, NodeError, RecomposeScope, SlotDebugSnapshot, SlotTable, SlotTableDebugStats,
8    composer, slot,
9};
10
11/// Holds a slot table into which a composition writes: the main composition has one, and each
12/// subcomposition has its own.
13pub struct SlotsHost {
14    storage_key: Cell<usize>,
15    pub(crate) inner: RefCell<SlotsHostInner>,
16}
17
18#[derive(Debug, Default)]
19pub(crate) struct SlotPassOutcome {
20    pub(crate) compacted: bool,
21    pub(crate) compact_anchor_registry_storage: bool,
22    pub(crate) compact_payload_storage: bool,
23    pub(crate) trim_growth_slack: bool,
24}
25
26#[derive(Default)]
27pub(crate) struct FinishedSlotPass {
28    pub(crate) outcome: SlotPassOutcome,
29    pub(crate) detached_root_children: Vec<slot::DetachedSubtree>,
30}
31
32pub(crate) struct SlotsHostInner {
33    table: SlotTable,
34    nested_hosts: Vec<Weak<SlotsHost>>,
35    lifecycle: slot::SlotLifecycleCoordinator,
36    runtime_state: Option<Rc<composer::ComposerRuntimeState>>,
37    /// The table's storage capacity when the active pass began; `None`
38    /// while no pass is active.
39    pub(crate) active_pass: Option<usize>,
40    /// The writer state of the active pass. Between passes a deep host,
41    /// such as an app's root, keeps its own; a shallow one's goes back to
42    /// the thread's spare states when its pass finishes.
43    pub(crate) pass_state: Option<Box<slot::SlotWriteSessionState>>,
44}
45
46// A writer state for a pass under `folds`: one of the thread's spare states
47// when it has one. Up to two spare states chain through `next_spare`.
48fn spare_write_state(folds: &Rc<slot::BranchFolds>) -> Box<slot::SlotWriteSessionState> {
49    match crate::thread_state::try_runtimes(|state| {
50        let mut head = state.spare_write_states.take()?;
51        state.spare_write_states.set(head.next_spare.take());
52        Some(head)
53    })
54    .flatten()
55    {
56        Some(mut state) => {
57            state.set_folds(Rc::clone(folds));
58            state
59        }
60        None => Box::new(slot::SlotWriteSessionState::new(Rc::clone(folds))),
61    }
62}
63
64fn recycle_write_state(mut state: Box<slot::SlotWriteSessionState>) {
65    crate::thread_state::try_runtimes(|threads| {
66        let head = threads.spare_write_states.take();
67        if head.as_ref().is_none_or(|first| first.next_spare.is_none()) {
68            state.next_spare = head;
69            threads.spare_write_states.set(Some(state));
70        } else {
71            threads.spare_write_states.set(head);
72        }
73    });
74}
75
76impl Drop for SlotsHost {
77    fn drop(&mut self) {
78        let storage_key = self.storage_key.get();
79        let inner = self.inner.get_mut();
80        if let Some(state) = inner.runtime_state.clone() {
81            state.dispose_host_on_drop(storage_key, &mut inner.table, &mut inner.lifecycle);
82        } else {
83            inner.lifecycle.dispose_slot_table(&mut inner.table);
84        }
85    }
86}
87
88impl SlotsHost {
89    /// Returns a key that identifies the slot table the host holds. It changes when the table is
90    /// replaced or taken out.
91    pub fn storage_key(&self) -> usize {
92        self.storage_key.get()
93    }
94
95    /// Creates a host around the slot table `storage`.
96    pub fn new(storage: SlotTable) -> Self {
97        let storage_key = storage.storage_id();
98        Self {
99            storage_key: Cell::new(storage_key),
100            inner: RefCell::new(SlotsHostInner {
101                table: storage,
102                nested_hosts: Vec::new(),
103                lifecycle: slot::SlotLifecycleCoordinator::default(),
104                runtime_state: None,
105                active_pass: None,
106                pass_state: None,
107            }),
108        }
109    }
110
111    /// Records `nested` as a host composed inside this one, so that forgetting effects here reaches
112    /// it too. Does nothing while this host is in use.
113    pub fn note_nested_host(&self, nested: &Rc<Self>) {
114        let Ok(mut inner) = self.inner.try_borrow_mut() else {
115            return;
116        };
117        inner.nested_hosts.retain(|held| held.upgrade().is_some());
118        if inner
119            .nested_hosts
120            .iter()
121            .any(|held| held.upgrade().is_some_and(|host| Rc::ptr_eq(&host, nested)))
122        {
123            return;
124        }
125        inner.nested_hosts.push(Rc::downgrade(nested));
126    }
127
128    pub(crate) fn forget_effects(&self) -> bool {
129        let (forgotten, nested, runtime_state) = {
130            let Ok(mut inner) = self.inner.try_borrow_mut() else {
131                return false;
132            };
133            if inner.active_pass.is_some() {
134                return false;
135            }
136            let drops = inner.table.take_effect_drops();
137            inner.nested_hosts.retain(|held| held.upgrade().is_some());
138            let nested: Vec<Rc<Self>> = inner
139                .nested_hosts
140                .iter()
141                .filter_map(Weak::upgrade)
142                .collect();
143            (drops, nested, inner.runtime_state.clone())
144        };
145        let mut any = !forgotten.is_empty();
146        drop(forgotten);
147        for host in nested {
148            any |= host.forget_effects();
149        }
150        if any {
151            self.borrow()
152                .scopes()
153                .for_each(RecomposeScope::force_recompose);
154            if let Some(runtime_state) = runtime_state {
155                runtime_state.force_recompose_retained_scopes(self.storage_key());
156            }
157        }
158        any
159    }
160
161    pub(crate) fn bind_runtime_state(&self, state: &Rc<composer::ComposerRuntimeState>) {
162        let mut inner = self.inner.borrow_mut();
163        inner.runtime_state = Some(Rc::clone(state));
164    }
165
166    pub(crate) fn rebind_orphaned_runtime_state(
167        &self,
168        state: &Rc<composer::ComposerRuntimeState>,
169    ) -> bool {
170        let inner = self.inner.borrow();
171        if inner.active_pass.is_some() {
172            log::error!("cannot rebind SlotsHost during an active pass");
173            return false;
174        }
175        let Some(bound_state) = inner.runtime_state.as_ref() else {
176            drop(inner);
177            self.bind_runtime_state(state);
178            return true;
179        };
180        if Rc::ptr_eq(bound_state, state) {
181            return true;
182        }
183        if bound_state.has_live_applier_host() {
184            return false;
185        }
186        drop(inner);
187
188        self.flush_pending_drops();
189        let mut lifecycle = {
190            let mut inner = self.inner.borrow_mut();
191            if inner.active_pass.is_some() {
192                log::error!("cannot rebind SlotsHost during an active pass");
193                return false;
194            }
195            let Some(bound_state) = inner.runtime_state.as_ref() else {
196                inner.runtime_state = Some(Rc::clone(state));
197                return true;
198            };
199            if Rc::ptr_eq(bound_state, state) {
200                return true;
201            }
202            if bound_state.has_live_applier_host() {
203                return false;
204            }
205
206            let previous_state = Rc::clone(bound_state);
207            let host_key = self.storage_key();
208            let SlotsHostInner {
209                table,
210                lifecycle,
211                runtime_state,
212                ..
213            } = &mut *inner;
214            previous_state.abandon_retained_subtrees_for_host(host_key, table, lifecycle);
215            *runtime_state = Some(Rc::clone(state));
216            std::mem::take(lifecycle)
217        };
218        lifecycle.flush_pending_drops();
219        true
220    }
221
222    pub(crate) fn runtime_state(&self) -> Option<Rc<composer::ComposerRuntimeState>> {
223        self.inner.borrow().runtime_state.clone()
224    }
225
226    pub(crate) fn runtime_state_ptr(&self) -> Option<*const composer::ComposerRuntimeState> {
227        self.inner.borrow().runtime_state.as_ref().map(Rc::as_ptr)
228    }
229
230    pub(crate) fn borrow(&self) -> Ref<'_, SlotTable> {
231        Ref::map(self.inner.borrow(), |inner| &inner.table)
232    }
233
234    pub(crate) fn borrow_mut(&self) -> RefMut<'_, SlotTable> {
235        RefMut::map(self.inner.borrow_mut(), |inner| &mut inner.table)
236    }
237
238    /// Takes the slot table out of the host after disposing what it retained. Fails if other
239    /// references to the host exist or a slot pass is active.
240    pub fn into_table(self: Rc<Self>) -> Result<SlotTable, NodeError> {
241        if Rc::strong_count(&self) != 1 {
242            return Err(NodeError::SlotHostUnavailable {
243                operation: "SlotsHost::into_table",
244                reason: "other host references are alive",
245            });
246        }
247        self.take_table_for_transfer()
248    }
249
250    fn take_table_for_transfer(&self) -> Result<SlotTable, NodeError> {
251        self.take_table_detached("SlotsHost::into_table", composer::HostTableDisposal::Keep)
252    }
253
254    fn take_table_detached(
255        &self,
256        operation: &'static str,
257        table_disposal: composer::HostTableDisposal,
258    ) -> Result<SlotTable, NodeError> {
259        let _teardown = crate::runtime::enter_state_teardown_scope();
260        if self.inner.borrow().active_pass.is_some() {
261            return Err(NodeError::SlotHostUnavailable {
262                operation,
263                reason: "slot pass is active",
264            });
265        }
266        self.flush_pending_drops();
267        let prepared = {
268            let mut inner = self.inner.borrow_mut();
269            if inner.active_pass.is_some() {
270                return Err(NodeError::SlotHostUnavailable {
271                    operation,
272                    reason: "slot pass is active",
273                });
274            }
275            let host_key = self.storage_key();
276            let SlotsHostInner {
277                table,
278                lifecycle,
279                runtime_state,
280                ..
281            } = &mut *inner;
282            runtime_state.as_ref().and_then(|state| {
283                state.prepare_retained_disposal_for_host(host_key, table, lifecycle, table_disposal)
284            })
285        };
286        if let Some(prepared) = prepared {
287            prepared.dispose()?;
288        }
289        let (taken, mut lifecycle) = {
290            let mut inner = self.inner.borrow_mut();
291            if inner.active_pass.is_some() {
292                return Err(NodeError::SlotHostUnavailable {
293                    operation,
294                    reason: "slot pass is active",
295                });
296            }
297            let SlotsHostInner {
298                table,
299                lifecycle,
300                runtime_state,
301                ..
302            } = &mut *inner;
303            if let Some(state) = runtime_state.take() {
304                state.clear_host(self, table);
305            }
306            let taken = std::mem::take(table);
307            self.storage_key.set(table.storage_id());
308            (taken, std::mem::take(lifecycle))
309        };
310        lifecycle.flush_pending_drops();
311        Ok(taken)
312    }
313
314    /// Disposes the content of the slot table and replaces it with an empty one. Fails while a slot
315    /// pass is active.
316    pub fn reset(&self) -> Result<(), NodeError> {
317        let _teardown = crate::runtime::enter_state_teardown_scope();
318        let mut old_table = self.take_table_detached(
319            "SlotsHost::reset",
320            composer::HostTableDisposal::DisposeWithRetained,
321        )?;
322        slot::SlotLifecycleCoordinator::default().dispose_slot_table(&mut old_table);
323        Ok(())
324    }
325
326    pub(crate) fn abandon_after_apply_failure(&self) {
327        let _teardown = crate::runtime::enter_state_teardown_scope();
328        let inner = self.inner.borrow();
329        if inner.active_pass.is_some() {
330            log::error!("cannot abandon SlotsHost during an active pass");
331            return;
332        }
333        let runtime_state = inner.runtime_state.clone();
334        drop(inner);
335        let mut inner = self.inner.borrow_mut();
336        let mut lifecycle = std::mem::take(&mut inner.lifecycle);
337        if let Some(state) = runtime_state {
338            let host_key = self.storage_key();
339            state.abandon_retained_subtrees_for_host(host_key, &mut inner.table, &mut lifecycle);
340        }
341        let mut old_table = std::mem::take(&mut inner.table);
342        self.storage_key.set(inner.table.storage_id());
343        inner.runtime_state = None;
344        inner.lifecycle = slot::SlotLifecycleCoordinator::default();
345        drop(inner);
346        lifecycle.dispose_slot_table(&mut old_table);
347    }
348
349    pub(crate) fn debug_stats(&self) -> SlotTableDebugStats {
350        let inner = self.inner.borrow();
351        let local = inner.table.debug_stats();
352        let lifecycle = inner.lifecycle.debug_stats();
353        let retention = inner
354            .runtime_state
355            .clone()
356            .map_or_default(|state| state.slot_retention_debug_stats(self));
357        SlotTableDebugStats::from_parts(local, lifecycle, retention)
358    }
359
360    #[cold]
361    #[inline(never)]
362    pub(crate) fn debug_snapshot(&self) -> SlotDebugSnapshot {
363        let inner = self.inner.borrow();
364        let mut snapshot = inner.table.debug_snapshot();
365        if let Some(state) = inner.runtime_state.clone() {
366            state.fill_slot_debug_snapshot(self, &mut snapshot);
367        }
368        snapshot
369    }
370
371    pub(crate) fn begin_pass(&self, mode: slot::SlotPassMode, folds: &Rc<slot::BranchFolds>) {
372        let mut inner = self.inner.borrow_mut();
373        let SlotsHostInner {
374            table,
375            active_pass,
376            pass_state,
377            ..
378        } = &mut *inner;
379        if active_pass.is_some() {
380            log::error!("slot pass already active for host");
381            return;
382        }
383        let state = match pass_state {
384            Some(state) => {
385                state.set_folds(Rc::clone(folds));
386                state
387            }
388            None => pass_state.insert(spare_write_state(folds)),
389        };
390        state.reset_for_pass(mode);
391        *active_pass = Some(table.storage_capacity());
392    }
393
394    pub(crate) fn has_active_pass(&self) -> bool {
395        self.inner.borrow().active_pass.is_some()
396    }
397
398    pub(crate) fn abandon_active_pass(&self) {
399        let mut inner = self.inner.borrow_mut();
400        inner.active_pass = None;
401        inner.table.settle_insert_run();
402    }
403
404    pub(crate) fn with_write_session<R>(
405        &self,
406        f: impl FnOnce(&mut slot::SlotWriteSession<'_>) -> R,
407    ) -> R {
408        let mut inner = self.inner.borrow_mut();
409        let SlotsHostInner {
410            table,
411            lifecycle,
412            active_pass,
413            pass_state,
414            ..
415        } = &mut *inner;
416        let state = pass_state
417            .as_mut()
418            .filter(|_| active_pass.is_some())
419            .expect("slot write session requires an active pass");
420        let mut session = table.write_session(lifecycle, state);
421        f(&mut session)
422    }
423
424    pub(crate) fn with_table_and_lifecycle_mut<R>(
425        &self,
426        f: impl FnOnce(&mut SlotTable, &mut slot::SlotLifecycleCoordinator) -> R,
427    ) -> R {
428        let mut inner = self.inner.borrow_mut();
429        let SlotsHostInner {
430            table, lifecycle, ..
431        } = &mut *inner;
432        f(table, lifecycle)
433    }
434
435    pub(crate) fn finish_pass(
436        &self,
437        applier: &mut dyn Applier,
438    ) -> Result<FinishedSlotPass, NodeError> {
439        let mut inner = self.inner.borrow_mut();
440        let SlotsHostInner {
441            table,
442            lifecycle,
443            active_pass,
444            pass_state,
445            ..
446        } = &mut *inner;
447        let (Some(storage_capacity), Some(state)) = (active_pass.take(), pass_state.as_mut())
448        else {
449            return Ok(FinishedSlotPass::default());
450        };
451
452        state.flush_payload_location_refreshes(table);
453
454        #[cfg(any(test, debug_assertions))]
455        if let Err(err) = state.validate(table) {
456            log::error!("slot writer invariant violation before finalize_pass: {err:?}");
457            return Err(NodeError::SlotHostUnavailable {
458                operation: "SlotsHost::finish_pass",
459                reason: "slot writer invariant violation",
460            });
461        }
462
463        let detached_root_children = {
464            let mut session = table.write_session(lifecycle, state);
465            session.finalize_pass(applier)?
466        };
467
468        let outcome = SlotPassOutcome {
469            compacted: state.request_compaction,
470            compact_anchor_registry_storage: state.request_anchor_storage_compaction,
471            compact_payload_storage: state.request_payload_storage_compaction,
472            trim_growth_slack: state.removed_nothing()
473                && table.storage_capacity() > storage_capacity,
474        };
475        if state.is_shared()
476            && let Some(state) = pass_state.take()
477        {
478            recycle_write_state(state);
479        }
480        Ok(FinishedSlotPass {
481            outcome,
482            detached_root_children,
483        })
484    }
485
486    pub(crate) fn flush_pending_drops(&self) {
487        if self.inner.borrow().lifecycle.pending_drops_len() == 0 {
488            return;
489        }
490        self.flush_pending_drops_slow();
491    }
492
493    #[cold]
494    #[inline(never)]
495    fn flush_pending_drops_slow(&self) {
496        loop {
497            let item = self.inner.borrow_mut().lifecycle.pop_pending_drop();
498            let Some(item) = item else { break };
499            item.dispose();
500        }
501    }
502
503    pub(crate) fn complete_pass_cleanup(&self, outcome: &SlotPassOutcome) {
504        let mut inner = self.inner.borrow_mut();
505        let SlotsHostInner {
506            table,
507            lifecycle,
508            runtime_state,
509            ..
510        } = &mut *inner;
511        debug_assert_eq!(
512            lifecycle.pending_drops_len(),
513            0,
514            "pending drops must be flushed before pass cleanup"
515        );
516        if outcome.compacted {
517            table.compact_storage();
518            lifecycle.compact_storage();
519        } else if outcome.trim_growth_slack {
520            table.trim_growth_slack();
521        }
522        if let Some(state) = runtime_state.clone() {
523            state.compact_table_identity_storage_for_host(
524                self,
525                table,
526                outcome.compact_anchor_registry_storage,
527                outcome.compact_payload_storage,
528            );
529        } else {
530            if outcome.compact_anchor_registry_storage {
531                table.compact_anchor_registry_storage(None);
532            }
533            if outcome.compact_payload_storage {
534                table.compact_payload_anchor_registry_storage(None);
535            }
536        }
537        table.assert_fast_integrity("slot pass cleanup");
538        #[cfg(any(test, debug_assertions))]
539        {
540            table.debug_verify();
541            if let Some(state) = runtime_state.clone() {
542                state.debug_verify_host(self, table);
543            }
544        }
545    }
546}