Skip to main content

cranpose_core/
retention.rs

1use std::cmp::Ordering;
2
3#[cfg(any(test, debug_assertions))]
4use crate::slot::{AnchorState, PayloadAnchorLifecycle, SlotInvariantError};
5#[cfg(any(test, debug_assertions))]
6use crate::{AnchorId, SlotTable};
7use crate::{
8    ScopeId,
9    collections::map::HashMap,
10    slot::{DetachedSubtree, GroupKey, NodeLifecycle},
11};
12
13/// What a group's content becomes when the group leaves the composition.
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
15pub enum RetentionMode {
16    /// Disposes the group's content as soon as the group leaves the composition.
17    #[default]
18    DisposeWhenInactive,
19    /// Detaches the group and keeps its content, so the group returns with its nodes and state when
20    /// its key is composed again. The [`RetentionPolicy`] budget can still evict it.
21    RetainWhenInactive,
22}
23
24/// Limits on how much content a composition keeps for groups that left it. Content over a limit is
25/// evicted in the order of the [`RetentionEvictionPolicy`].
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub struct RetentionBudget {
28    /// Most detached subtrees to keep at once. `None` sets no limit.
29    pub max_retained_subtrees: Option<usize>,
30    /// Most heap bytes the retained subtrees may take together. `None` sets no limit.
31    pub max_retained_bytes: Option<usize>,
32    /// Most composition passes a subtree may stay retained before it is evicted. `None` sets no age
33    /// limit.
34    pub max_age_passes: Option<u64>,
35}
36
37impl RetentionBudget {
38    /// A budget with no limit on any measure.
39    pub const UNBOUNDED: Self = Self {
40        max_retained_subtrees: None,
41        max_retained_bytes: None,
42        max_age_passes: None,
43    };
44}
45
46impl Default for RetentionBudget {
47    fn default() -> Self {
48        Self::UNBOUNDED
49    }
50}
51
52/// Which retained subtree is evicted first when a [`RetentionBudget`] is exceeded.
53#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
54pub enum RetentionEvictionPolicy {
55    /// The subtree that was detached the longest ago.
56    #[default]
57    LeastRecentlyDetached,
58    /// The subtree whose last restore is the oldest. Subtrees never restored go first.
59    LeastRecentlyRestored,
60    /// The subtree that takes the most heap memory.
61    LargestFirst,
62}
63
64/// How a composition limits and evicts retained content: the budget it may keep and the order in
65/// which it drops subtrees that exceed the budget.
66#[derive(Debug, Clone, Copy, PartialEq, Eq)]
67pub struct RetentionPolicy {
68    /// The limits on how much retained content the composition keeps.
69    pub budget: RetentionBudget,
70    /// Which retained subtree is evicted first when the budget is exceeded.
71    pub eviction: RetentionEvictionPolicy,
72}
73
74impl RetentionPolicy {
75    /// A policy with an unbounded budget that evicts the least recently detached subtree first.
76    pub const UNBOUNDED: Self = Self {
77        budget: RetentionBudget::UNBOUNDED,
78        eviction: RetentionEvictionPolicy::LeastRecentlyDetached,
79    };
80}
81
82impl Default for RetentionPolicy {
83    fn default() -> Self {
84        Self::UNBOUNDED
85    }
86}
87
88#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
89pub(crate) struct RetainKey {
90    pub(crate) parent_scope: Option<ScopeId>,
91    pub(crate) key: GroupKey,
92}
93
94impl RetainKey {
95    pub(crate) fn for_group(parent_scope: Option<ScopeId>, key: GroupKey) -> Self {
96        Self {
97            parent_scope: if key.is_movable() { None } else { parent_scope },
98            key,
99        }
100    }
101}
102
103pub(crate) struct RetainedGroup {
104    pub(crate) subtree: DetachedSubtree,
105    detached_pass: u64,
106    detached_order: u64,
107    last_restored_order: u64,
108    pinned: bool,
109}
110
111impl RetainedGroup {
112    fn node_count(&self) -> usize {
113        self.subtree.node_count()
114    }
115
116    fn payload_count(&self) -> usize {
117        self.subtree.payload_count()
118    }
119
120    fn scope_count(&self) -> usize {
121        self.subtree.scope_count()
122    }
123
124    fn anchor_count(&self) -> usize {
125        self.subtree.anchor_count()
126    }
127
128    fn heap_bytes(&self) -> usize {
129        self.subtree.heap_bytes()
130    }
131}
132
133#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
134pub(crate) struct RetentionDebugStats {
135    pub(crate) subtree_count: usize,
136    pub(crate) group_count: usize,
137    pub(crate) payload_count: usize,
138    pub(crate) node_count: usize,
139    pub(crate) scope_count: usize,
140    pub(crate) anchor_count: usize,
141    pub(crate) heap_bytes: usize,
142    pub(crate) evictions_total: usize,
143}
144
145pub(crate) struct RetentionManager {
146    groups: HashMap<RetainKey, RetainedGroup>,
147    restored_at_by_key: HashMap<RetainKey, u64>,
148    policy: RetentionPolicy,
149    pass_clock: u64,
150    operation_clock: u64,
151    evictions_total: usize,
152}
153
154impl Default for RetentionManager {
155    fn default() -> Self {
156        Self::new(RetentionPolicy::default())
157    }
158}
159
160#[derive(Clone, Copy)]
161pub(crate) enum RestoreRecord {
162    Keep,
163    ClearForDisposal,
164}
165
166#[derive(Clone, Copy, PartialEq, Eq)]
167pub(crate) enum RetentionPin {
168    Unpinned,
169    Pinned,
170}
171
172impl RetentionManager {
173    pub(crate) fn new(policy: RetentionPolicy) -> Self {
174        Self {
175            groups: HashMap::default(),
176            restored_at_by_key: HashMap::default(),
177            policy,
178            pass_clock: 0,
179            operation_clock: 0,
180            evictions_total: 0,
181        }
182    }
183
184    pub(crate) fn set_policy(&mut self, policy: RetentionPolicy) {
185        self.policy = policy;
186    }
187
188    pub(crate) fn take(&mut self, key: RetainKey) -> Option<DetachedSubtree> {
189        self.take_with_mode(key, RestoreRecord::Keep)
190    }
191
192    pub(crate) fn take_with_mode(
193        &mut self,
194        key: RetainKey,
195        record: RestoreRecord,
196    ) -> Option<DetachedSubtree> {
197        let retained = self.groups.get(&key)?;
198        if !retained_subtree_matches_key(&retained.subtree, key, "restore") {
199            return None;
200        }
201        if !retained_subtree_root_is_detached(&retained.subtree, key, "restore") {
202            return None;
203        }
204        if !retained_subtree_nodes_have_lifecycle(
205            &retained.subtree,
206            key,
207            NodeLifecycle::RetainedDetached,
208            "restore",
209        ) {
210            return None;
211        }
212        let retained = self.groups.remove(&key)?;
213        match record {
214            RestoreRecord::Keep => {
215                let restored_order = self.tick_operation();
216                self.restored_at_by_key.insert(key, restored_order);
217            }
218            RestoreRecord::ClearForDisposal => {
219                self.restored_at_by_key.remove(&key);
220            }
221        }
222        Some(retained.subtree)
223    }
224
225    pub(crate) fn len(&self) -> usize {
226        self.groups.len()
227    }
228
229    pub(crate) fn is_small_for_reuse(&self) -> bool {
230        self.groups.capacity() <= 64 && self.restored_at_by_key.capacity() <= 64
231    }
232
233    pub(crate) fn take_after_restore_preflight(
234        &mut self,
235        key: RetainKey,
236        preflight: impl FnOnce(&mut DetachedSubtree) -> bool,
237    ) -> Option<DetachedSubtree> {
238        if !preflight(&mut self.groups.get_mut(&key)?.subtree) {
239            log::error!(
240                "retention restore preflight rejected subtree for parent_scope={:?} key={:?}",
241                key.parent_scope,
242                key.key
243            );
244            return None;
245        }
246        self.take(key)
247    }
248
249    pub(crate) fn contains(&self, key: RetainKey) -> bool {
250        self.groups.contains_key(&key)
251    }
252
253    #[cfg(test)]
254    pub(crate) fn insert(
255        &mut self,
256        key: RetainKey,
257        subtree: DetachedSubtree,
258    ) -> Vec<DetachedSubtree> {
259        self.insert_with_pin(key, subtree, RetentionPin::Unpinned)
260    }
261
262    #[inline(never)]
263    pub(crate) fn insert_with_pin(
264        &mut self,
265        key: RetainKey,
266        mut subtree: DetachedSubtree,
267        pin: RetentionPin,
268    ) -> Vec<DetachedSubtree> {
269        if self.groups.contains_key(&key) {
270            log::error!(
271                "retention insert rejected duplicate key for parent_scope={:?} key={:?}",
272                key.parent_scope,
273                key.key
274            );
275            return vec![subtree];
276        }
277        if !retained_subtree_matches_key(&subtree, key, "insert") {
278            return vec![subtree];
279        }
280        if !retained_subtree_root_is_detached(&subtree, key, "insert") {
281            return vec![subtree];
282        }
283        let detached_order = self.tick_operation();
284        let last_restored_order = self.restored_at_by_key.remove(&key).unwrap_or_default();
285        subtree.mark_nodes_retained_detached();
286        self.groups.insert(
287            key,
288            RetainedGroup {
289                subtree,
290                detached_pass: self.pass_clock,
291                detached_order,
292                last_restored_order,
293                pinned: pin == RetentionPin::Pinned,
294            },
295        );
296        self.evict_to_budget()
297    }
298
299    pub(crate) fn is_empty(&self) -> bool {
300        self.groups.is_empty()
301    }
302
303    pub(crate) fn debug_stats(&self) -> RetentionDebugStats {
304        RetentionDebugStats {
305            subtree_count: self.groups.len(),
306            group_count: self
307                .groups
308                .values()
309                .map(|retained| retained.subtree.group_count())
310                .sum(),
311            payload_count: self.groups.values().map(RetainedGroup::payload_count).sum(),
312            node_count: self.groups.values().map(RetainedGroup::node_count).sum(),
313            scope_count: self.groups.values().map(RetainedGroup::scope_count).sum(),
314            anchor_count: self.groups.values().map(RetainedGroup::anchor_count).sum(),
315            heap_bytes: self.groups.values().map(RetainedGroup::heap_bytes).sum(),
316            evictions_total: self.evictions_total,
317        }
318    }
319
320    pub(crate) fn into_subtrees(self) -> Vec<DetachedSubtree> {
321        self.groups
322            .into_values()
323            .map(|retained| retained.subtree)
324            .collect()
325    }
326
327    pub(crate) fn subtrees(&self) -> impl Iterator<Item = &DetachedSubtree> + '_ {
328        self.groups.values().map(|retained| &retained.subtree)
329    }
330
331    #[cfg(test)]
332    pub(crate) fn subtrees_mut(&mut self) -> impl Iterator<Item = &mut DetachedSubtree> + '_ {
333        self.groups
334            .values_mut()
335            .map(|retained| &mut retained.subtree)
336    }
337
338    #[cfg(any(test, debug_assertions))]
339    pub(crate) fn validate(&self, table: &SlotTable) -> Result<(), SlotInvariantError> {
340        for (key, retained) in &self.groups {
341            let subtree = &retained.subtree;
342            subtree.validate_detached()?;
343            let Some(root_key) = subtree.root_key_checked() else {
344                return Err(SlotInvariantError::DetachedSubtreeEmpty);
345            };
346            if root_key != key.key {
347                return Err(SlotInvariantError::RetainedRootKeyMismatch {
348                    parent_scope: key.parent_scope,
349                    expected: key.key,
350                    actual: root_key,
351                });
352            }
353
354            let root_parent_anchor = subtree
355                .root_parent_anchor_checked()
356                .unwrap_or(AnchorId::INVALID);
357            if root_parent_anchor.is_valid() {
358                return Err(SlotInvariantError::RetainedRootHasActiveParent {
359                    root_key,
360                    parent_anchor: root_parent_anchor,
361                });
362            }
363
364            for anchor in subtree.group_anchors() {
365                match table.anchor_state(anchor) {
366                    Some(AnchorState::Detached) => {}
367                    Some(AnchorState::Active(active_index)) => {
368                        return Err(SlotInvariantError::RetainedSubtreeAnchorStillActive {
369                            root_key,
370                            anchor,
371                            active_index: active_index as usize,
372                        });
373                    }
374                    actual => {
375                        return Err(SlotInvariantError::RetainedAnchorStateMismatch {
376                            root_key,
377                            anchor,
378                            actual,
379                        });
380                    }
381                }
382            }
383
384            for scope in subtree.scopes() {
385                if table.active_group_for_scope(scope).is_some() {
386                    return Err(SlotInvariantError::RetainedScopeStillActive {
387                        root_key,
388                        scope_id: scope.id(),
389                        active_anchor: scope.group_anchor(),
390                    });
391                }
392            }
393
394            for payload_anchor in subtree.payload_anchors() {
395                match table.payload_anchor_lifecycle(payload_anchor) {
396                    Some(PayloadAnchorLifecycle::Detached) => {}
397                    Some(PayloadAnchorLifecycle::Active) => {
398                        let Some((active_owner, active_index)) =
399                            table.payload_anchor_active_location(payload_anchor)
400                        else {
401                            return Err(SlotInvariantError::RetainedPayloadAnchorStateMismatch {
402                                root_key,
403                                payload_anchor,
404                                actual: Some(PayloadAnchorLifecycle::Active),
405                            });
406                        };
407                        return Err(SlotInvariantError::RetainedPayloadAnchorStillActive {
408                            root_key,
409                            payload_anchor,
410                            active_owner,
411                            active_index,
412                        });
413                    }
414                    actual => {
415                        return Err(SlotInvariantError::RetainedPayloadAnchorStateMismatch {
416                            root_key,
417                            payload_anchor,
418                            actual,
419                        });
420                    }
421                }
422            }
423
424            for (node_id, lifecycle) in subtree.node_states() {
425                if lifecycle != NodeLifecycle::RetainedDetached {
426                    return Err(SlotInvariantError::RetainedNodeLifecycleMismatch {
427                        root_key,
428                        node_id,
429                        actual: lifecycle,
430                    });
431                }
432            }
433        }
434        Ok(())
435    }
436
437    #[cfg(any(test, debug_assertions))]
438    pub(crate) fn debug_verify(&self, table: &SlotTable) {
439        if crate::slot::slot_validation_diagnostics_enabled()
440            && let Err(err) = self.validate(table)
441        {
442            panic!("retention invariant violation: {err:?}");
443        }
444    }
445
446    pub(crate) fn evictions_total(&self) -> usize {
447        self.evictions_total
448    }
449
450    pub(crate) fn advance_pass(&mut self) -> Vec<DetachedSubtree> {
451        self.pass_clock = self.pass_clock.saturating_add(1);
452        self.evict_to_budget()
453    }
454
455    fn tick_operation(&mut self) -> u64 {
456        self.operation_clock = self.operation_clock.saturating_add(1);
457        self.operation_clock
458    }
459
460    fn evict_to_budget(&mut self) -> Vec<DetachedSubtree> {
461        let mut evicted = Vec::new();
462        while let Some(key) = self.budget_eviction_key() {
463            let Some(retained) = self.groups.remove(&key) else {
464                break;
465            };
466            self.restored_at_by_key.remove(&key);
467            self.evictions_total = self.evictions_total.saturating_add(1);
468            if !retained_subtree_matches_key(&retained.subtree, key, "eviction")
469                || !retained_subtree_root_is_detached(&retained.subtree, key, "eviction")
470                || !retained_subtree_nodes_have_lifecycle(
471                    &retained.subtree,
472                    key,
473                    NodeLifecycle::RetainedDetached,
474                    "eviction",
475                )
476            {
477                log::error!(
478                    "retention eviction returned malformed retained subtree for caller-owned disposal"
479                );
480                evicted.push(retained.subtree);
481                continue;
482            }
483            evicted.push(retained.subtree);
484        }
485        evicted
486    }
487
488    fn budget_eviction_key(&self) -> Option<RetainKey> {
489        if self.groups.is_empty() {
490            return None;
491        }
492
493        if let Some(max_age_passes) = self.policy.budget.max_age_passes
494            && let Some(key) = self.age_eviction_key(max_age_passes)
495        {
496            return Some(key);
497        }
498
499        let over_count = self
500            .policy
501            .budget
502            .max_retained_subtrees
503            .is_some_and(|max| self.groups.len() > max);
504        let over_bytes = self
505            .policy
506            .budget
507            .max_retained_bytes
508            .is_some_and(|max| self.retained_heap_bytes() > max);
509
510        (over_count || over_bytes)
511            .then(|| self.policy_eviction_key())
512            .flatten()
513    }
514
515    fn evictable(&self) -> impl Iterator<Item = (&RetainKey, &RetainedGroup)> + '_ {
516        self.groups.iter().filter(|(_, retained)| !retained.pinned)
517    }
518
519    fn age_eviction_key(&self, max_age_passes: u64) -> Option<RetainKey> {
520        self.evictable()
521            .filter(|(_, retained)| {
522                self.pass_clock.saturating_sub(retained.detached_pass) > max_age_passes
523            })
524            .min_by(|(left_key, left), (right_key, right)| {
525                left.detached_pass
526                    .cmp(&right.detached_pass)
527                    .then_with(|| left.detached_order.cmp(&right.detached_order))
528                    .then_with(|| retain_key_cmp(left_key, right_key))
529            })
530            .map(|(key, _)| *key)
531    }
532
533    fn policy_eviction_key(&self) -> Option<RetainKey> {
534        match self.policy.eviction {
535            RetentionEvictionPolicy::LeastRecentlyDetached => self.least_recently_detached_key(),
536            RetentionEvictionPolicy::LeastRecentlyRestored => self.least_recently_restored_key(),
537            RetentionEvictionPolicy::LargestFirst => self.largest_first_key(),
538        }
539    }
540
541    fn least_recently_detached_key(&self) -> Option<RetainKey> {
542        self.evictable()
543            .min_by(|(left_key, left), (right_key, right)| {
544                left.detached_order
545                    .cmp(&right.detached_order)
546                    .then_with(|| retain_key_cmp(left_key, right_key))
547            })
548            .map(|(key, _)| *key)
549    }
550
551    fn least_recently_restored_key(&self) -> Option<RetainKey> {
552        self.evictable()
553            .min_by(|(left_key, left), (right_key, right)| {
554                left.last_restored_order
555                    .cmp(&right.last_restored_order)
556                    .then_with(|| left.detached_order.cmp(&right.detached_order))
557                    .then_with(|| retain_key_cmp(left_key, right_key))
558            })
559            .map(|(key, _)| *key)
560    }
561
562    fn largest_first_key(&self) -> Option<RetainKey> {
563        self.evictable()
564            .max_by(|(left_key, left), (right_key, right)| {
565                left.heap_bytes()
566                    .cmp(&right.heap_bytes())
567                    .then_with(|| retain_key_cmp(left_key, right_key))
568            })
569            .map(|(key, _)| *key)
570    }
571
572    fn retained_heap_bytes(&self) -> usize {
573        self.groups.values().map(RetainedGroup::heap_bytes).sum()
574    }
575}
576
577fn retained_subtree_matches_key(
578    subtree: &DetachedSubtree,
579    key: RetainKey,
580    context: &'static str,
581) -> bool {
582    let Some(root_key) = subtree.root_key_checked() else {
583        log::error!(
584            "retention {context} rejected empty subtree for parent_scope={:?} key={:?}",
585            key.parent_scope,
586            key.key
587        );
588        return false;
589    };
590    if root_key != key.key {
591        log::error!(
592            "retention {context} rejected root key mismatch for parent_scope={:?}: expected {:?}, actual {:?}",
593            key.parent_scope,
594            key.key,
595            root_key
596        );
597        return false;
598    }
599    true
600}
601
602fn retained_subtree_root_is_detached(
603    subtree: &DetachedSubtree,
604    key: RetainKey,
605    context: &'static str,
606) -> bool {
607    let Some(parent_anchor) = subtree.root_parent_anchor_checked() else {
608        log::error!(
609            "retention {context} rejected empty subtree for parent_scope={:?} key={:?}",
610            key.parent_scope,
611            key.key
612        );
613        return false;
614    };
615    if parent_anchor.is_valid() {
616        log::error!(
617            "retention {context} rejected attached root parent {:?} for parent_scope={:?} key={:?}",
618            parent_anchor,
619            key.parent_scope,
620            key.key
621        );
622        return false;
623    }
624    true
625}
626
627fn retained_subtree_nodes_have_lifecycle(
628    subtree: &DetachedSubtree,
629    key: RetainKey,
630    expected: NodeLifecycle,
631    context: &'static str,
632) -> bool {
633    if let Some((node_id, actual)) = subtree.first_node_lifecycle_mismatch(expected) {
634        log::error!(
635            "retention {context} rejected node lifecycle mismatch for node {node_id} parent_scope={:?} key={:?}: expected {:?}, actual {:?}",
636            key.parent_scope,
637            key.key,
638            expected,
639            actual
640        );
641        return false;
642    }
643    true
644}
645
646fn retain_key_cmp(left: &RetainKey, right: &RetainKey) -> Ordering {
647    (
648        left.parent_scope,
649        left.key.static_key,
650        left.key.explicit_key,
651        left.key.ordinal,
652    )
653        .cmp(&(
654            right.parent_scope,
655            right.key.static_key,
656            right.key.explicit_key,
657            right.key.ordinal,
658        ))
659}
660
661#[cfg(test)]
662#[path = "tests/retention_tests.rs"]
663mod tests;