Skip to main content

semi_persistent_egraph/au/
space.rs

1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// SPDX-License-Identifier: Apache-2.0
3//! Search-space layer: OR/AND arenas, context interner, node/edge caches (§4.2).
4//!
5//! The search space is an AND/OR graph where OR nodes are subproblems `AU(l, r)`
6//! keyed by the class pair plus two opaque context-id slots. Side modes use one
7//! class context per slot; pair mode stores an ordered-pair context in the first.
8//! AND nodes are chosen factorings (operator + paired children). Everything here
9//! is immutable once pushed (hash-cons semantics).
10//! All storage uses semi-persistent containers (AppendOnlyVec for structural fields,
11//! SpMap for deduplication caches); mark/restore truncates them as one unit.
12
13use crate::config::AuIds;
14use crate::containers::{
15    AppendOnlyVec, DenseId, IndexLike, MapToken, ShrinkPolicy, SpMap, VecToken,
16};
17
18use super::{AuIds31, Span};
19
20// ---------------------------------------------------------------------------
21// Id types
22// ---------------------------------------------------------------------------
23
24crate::containers::define_id31! {
25    /// Index of an OR node in the search-space layer.
26    pub struct OrId / StoredOrId, "or";
27}
28
29crate::containers::define_id31! {
30    /// Index of a cached action list in the action cache.
31    pub struct ActionId / StoredActionId, "act";
32}
33
34crate::containers::define_id31! {
35    /// Interned context id (a sorted vector of AuClassId).
36    pub struct CtxId / StoredCtxId, "ctx";
37}
38
39// ---------------------------------------------------------------------------
40// CycleMode
41// ---------------------------------------------------------------------------
42
43/// Which path component breaks cycles (§2.3).
44///
45/// The two legacy modes track the left and right class paths separately.
46/// [`CycleMode::Pair`] tracks ordered class pairs instead, so revisiting one
47/// side is allowed when the other side has changed. Every AU algorithm
48/// consumes this same policy: root Exact, UCT, and Exact calls delegated by
49/// UCT.
50#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
51pub enum CycleMode {
52    /// Side-based filtering against ancestor contexts only. A class can occur
53    /// at most twice per side on a path (once as the current node, once as a
54    /// child).
55    #[default]
56    AncestorOnly,
57    /// Side-based filtering against ancestors and the current `(l, r)`. A
58    /// class occurs at most once per side on a path.
59    CurrentInclusive,
60    /// Pair-based filtering against ancestors and the current ordered pair.
61    /// A left or right class may repeat by itself; only an already-active
62    /// `(left, right)` pair is blocked.
63    Pair,
64}
65
66// ---------------------------------------------------------------------------
67// Context interner (semi-persistent: AppendOnlyVec + SpMap)
68// ---------------------------------------------------------------------------
69
70/// Interns sorted context-item vectors as context ids. Two equal vectors get
71/// the same context id; comparison is then a single integer compare.
72///
73/// Both pools and the dedup map are addressed by ids whose `Index` is `A::Index`
74/// (`A::Context` for `spans`, `A::ContextElem` for `items`, and `index`'s log
75/// positions are what `A::Context`s are minted from), so that word is the index type
76/// rather than `usize`.
77pub struct ContextStore<A: AuIds = AuIds31, T = <A as AuIds>::Class>
78where
79    T: Copy + Ord + core::hash::Hash,
80{
81    /// Each interned context's data as a typed span into `items`.
82    spans: AppendOnlyVec<Span<A::ContextElem>, A::Index>,
83    /// Pool of items (all interned contexts concatenated).
84    items: AppendOnlyVec<T, A::Index>,
85    /// Deduplication map: sorted item vector -> context id.
86    index: SpMap<Vec<T>, A::Context, A::Index>,
87}
88
89/// Token for restoring a `ContextStore` to a previous state.
90#[derive(Clone, Copy, Debug)]
91pub struct ContextStoreToken {
92    spans: VecToken,
93    items: VecToken,
94    index: MapToken,
95}
96
97impl<A: AuIds, T> ContextStore<A, T>
98where
99    T: Copy + Ord + core::hash::Hash,
100{
101    pub fn new() -> Self {
102        let mut store = ContextStore {
103            spans: AppendOnlyVec::new(),
104            items: AppendOnlyVec::new(),
105            index: SpMap::new(),
106        };
107        store.intern(&[]);
108        store
109    }
110
111    pub fn empty(&self) -> A::Context {
112        // The empty context is interned first in `new`, so id 0 is it. Id 0 exists in every
113        // id family, so this mint needs no check.
114        A::Context::from_usize(0)
115    }
116
117    pub fn intern(&mut self, sorted_items: &[T]) -> A::Context {
118        if let Some(log_idx) = self.index.id_of(&sorted_items.to_vec()) {
119            return *self.index.get_val(log_idx);
120        }
121        let id: A::Context = crate::id::id_at_index(self.spans.len());
122        let start = self.items.len().as_usize();
123        for &item in sorted_items {
124            self.items
125                .try_push(item)
126                .expect("AU arena sized by its index word");
127        }
128        self.spans
129            .try_push(Span::new(start, sorted_items.len()))
130            .expect("AU arena sized by its index word");
131        self.index
132            .try_insert(sorted_items.to_vec(), id)
133            .expect("AU arena sized by its index word");
134        id
135    }
136
137    #[inline]
138    pub fn get(&self, id: A::Context) -> &[T] {
139        let span = *self.spans.get(id.to_index());
140        let start = span.start_usize();
141        let len = span.len_usize();
142        // `as_slice()` is the verified accessor for exactly this: its
143        // postcondition is `r@ == self.view()`, so the contiguity this used to
144        // assert with `from_raw_parts` is now a proof obligation the container
145        // discharges. The span was built by `intern`, which pushes the elements
146        // consecutively, so `[start, start + len)` is in bounds — and if it ever
147        // were not, this panics instead of reading out of bounds.
148        &self.items.as_slice()[start..start + len]
149    }
150
151    #[inline]
152    pub fn contains(&self, id: A::Context, item: T) -> bool {
153        self.get(id).binary_search(&item).is_ok()
154    }
155
156    /// Number of interned contexts, in the configured index word (a context count is
157    /// a position count: the next context interns at exactly this index).
158    pub fn len(&self) -> A::Index {
159        self.spans.len()
160    }
161
162    pub fn is_empty(&self) -> bool {
163        self.spans.is_empty()
164    }
165
166    pub fn mark(&mut self) -> ContextStoreToken {
167        ContextStoreToken {
168            spans: self
169                .spans
170                .try_mark(ShrinkPolicy::Never)
171                .expect("mark: depth bounded by the search driver"),
172            items: self
173                .items
174                .try_mark(ShrinkPolicy::Never)
175                .expect("mark: depth bounded by the search driver"),
176            index: self
177                .index
178                .try_mark(ShrinkPolicy::Never)
179                .expect("mark: depth bounded by the search driver"),
180        }
181    }
182
183    pub fn is_valid_token(&self, token: &ContextStoreToken) -> bool {
184        self.spans.is_valid_token(&token.spans)
185            && self.items.is_valid_token(&token.items)
186            && self.index.is_valid_token(&token.index)
187    }
188
189    pub fn restore(&mut self, token: ContextStoreToken) {
190        self.index
191            .try_restore(token.index)
192            .expect("restore: token minted by this container's own mark");
193        self.items
194            .try_restore(token.items)
195            .expect("restore: token minted by this container's own mark");
196        self.spans
197            .try_restore(token.spans)
198            .expect("restore: token minted by this container's own mark");
199    }
200}
201
202impl<A: AuIds, T> Default for ContextStore<A, T>
203where
204    T: Copy + Ord + core::hash::Hash,
205{
206    fn default() -> Self {
207        Self::new()
208    }
209}
210
211/// One contextual Exact/UCT entry context in a representation independent of
212/// the interner ids used by a particular [`SearchSpace`].
213#[derive(Clone, Debug, PartialEq, Eq)]
214pub(crate) enum CycleContext<C> {
215    Sides { left: Vec<C>, right: Vec<C> },
216    Pairs(Vec<(C, C)>),
217}
218
219// ---------------------------------------------------------------------------
220// OR arena (semi-persistent: AppendOnlyVec + SpMap)
221// ---------------------------------------------------------------------------
222
223/// The OR-node arena: each node is a subproblem `AU(l, r)` with cycle contexts.
224/// Every column is addressed by `A::Or`, and `by_key`'s log positions are what the
225/// `A::Or`s are minted from, so the index word is `A::Index` throughout.
226pub struct OrArena<A: AuIds = AuIds31> {
227    pub left: AppendOnlyVec<A::Class, A::Index>,
228    pub right: AppendOnlyVec<A::Class, A::Index>,
229    pub left_ctx: AppendOnlyVec<A::Context, A::Index>,
230    pub right_ctx: AppendOnlyVec<A::Context, A::Index>,
231    pub terminal: AppendOnlyVec<bool, A::Index>,
232    pub left_best_size: AppendOnlyVec<u32, A::Index>,
233    pub right_best_size: AppendOnlyVec<u32, A::Index>,
234    pub by_key: SpMap<(A::Class, A::Class, A::Context, A::Context), A::Or, A::Index>,
235}
236
237/// Token for restoring an `OrArena`.
238#[derive(Clone, Copy, Debug)]
239pub struct OrArenaToken {
240    left: VecToken,
241    right: VecToken,
242    left_ctx: VecToken,
243    right_ctx: VecToken,
244    terminal: VecToken,
245    left_best_size: VecToken,
246    right_best_size: VecToken,
247    by_key: MapToken,
248}
249
250impl<A: AuIds> OrArena<A> {
251    pub fn new() -> Self {
252        OrArena {
253            left: AppendOnlyVec::new(),
254            right: AppendOnlyVec::new(),
255            left_ctx: AppendOnlyVec::new(),
256            right_ctx: AppendOnlyVec::new(),
257            terminal: AppendOnlyVec::new(),
258            left_best_size: AppendOnlyVec::new(),
259            right_best_size: AppendOnlyVec::new(),
260            by_key: SpMap::new(),
261        }
262    }
263
264    /// Number of OR nodes, in the configured index word (the next node lands at
265    /// exactly this index).
266    pub fn len(&self) -> A::Index {
267        self.left.len()
268    }
269
270    pub fn is_empty(&self) -> bool {
271        self.left.is_empty()
272    }
273
274    pub fn mark(&mut self) -> OrArenaToken {
275        OrArenaToken {
276            left: self
277                .left
278                .try_mark(ShrinkPolicy::Never)
279                .expect("mark: depth bounded by the search driver"),
280            right: self
281                .right
282                .try_mark(ShrinkPolicy::Never)
283                .expect("mark: depth bounded by the search driver"),
284            left_ctx: self
285                .left_ctx
286                .try_mark(ShrinkPolicy::Never)
287                .expect("mark: depth bounded by the search driver"),
288            right_ctx: self
289                .right_ctx
290                .try_mark(ShrinkPolicy::Never)
291                .expect("mark: depth bounded by the search driver"),
292            terminal: self
293                .terminal
294                .try_mark(ShrinkPolicy::Never)
295                .expect("mark: depth bounded by the search driver"),
296            left_best_size: self
297                .left_best_size
298                .try_mark(ShrinkPolicy::Never)
299                .expect("mark: depth bounded by the search driver"),
300            right_best_size: self
301                .right_best_size
302                .try_mark(ShrinkPolicy::Never)
303                .expect("mark: depth bounded by the search driver"),
304            by_key: self
305                .by_key
306                .try_mark(ShrinkPolicy::Never)
307                .expect("mark: depth bounded by the search driver"),
308        }
309    }
310
311    pub fn restore(&mut self, token: OrArenaToken) {
312        self.by_key
313            .try_restore(token.by_key)
314            .expect("restore: token minted by this container's own mark");
315        self.right_best_size
316            .try_restore(token.right_best_size)
317            .expect("restore: token minted by this container's own mark");
318        self.left_best_size
319            .try_restore(token.left_best_size)
320            .expect("restore: token minted by this container's own mark");
321        self.terminal
322            .try_restore(token.terminal)
323            .expect("restore: token minted by this container's own mark");
324        self.right_ctx
325            .try_restore(token.right_ctx)
326            .expect("restore: token minted by this container's own mark");
327        self.left_ctx
328            .try_restore(token.left_ctx)
329            .expect("restore: token minted by this container's own mark");
330        self.right
331            .try_restore(token.right)
332            .expect("restore: token minted by this container's own mark");
333        self.left
334            .try_restore(token.left)
335            .expect("restore: token minted by this container's own mark");
336    }
337
338    pub fn is_valid_token(&self, token: &OrArenaToken) -> bool {
339        self.left.is_valid_token(&token.left)
340    }
341}
342
343impl<A: AuIds> Default for OrArena<A> {
344    fn default() -> Self {
345        Self::new()
346    }
347}
348
349// ---------------------------------------------------------------------------
350// SearchSpace: combines the above into one structure
351// ---------------------------------------------------------------------------
352
353/// Token for restoring the entire search-space layer. Validity is delegated
354/// to the inner semi-persistent containers' branch genealogy.
355#[derive(Clone, Copy, Debug)]
356pub struct SpaceToken {
357    or_arena: OrArenaToken,
358    contexts: ContextStoreToken,
359    pair_contexts: ContextStoreToken,
360}
361
362/// The complete search-space layer shared by all algorithms in a session.
363pub struct SearchSpace<A: AuIds = AuIds31> {
364    pub or_arena: OrArena<A>,
365    pub contexts: ContextStore<A>,
366    pub pair_contexts: ContextStore<A, (A::Class, A::Class)>,
367    pub cycle_mode: CycleMode,
368}
369
370impl<A: AuIds> SearchSpace<A> {
371    pub fn new(cycle_mode: CycleMode) -> Self {
372        SearchSpace {
373            or_arena: OrArena::new(),
374            contexts: ContextStore::new(),
375            pair_contexts: ContextStore::new(),
376            cycle_mode,
377        }
378    }
379
380    /// The two opaque context ids used for a root state.
381    ///
382    /// Pair mode stores its ordered-pair context in the left slot and keeps
383    /// the right slot empty. Side modes use both slots as before.
384    pub fn empty_contexts(&self) -> (A::Context, A::Context) {
385        match self.cycle_mode {
386            CycleMode::Pair => (self.pair_contexts.empty(), self.pair_contexts.empty()),
387            CycleMode::AncestorOnly | CycleMode::CurrentInclusive => {
388                (self.contexts.empty(), self.contexts.empty())
389            }
390        }
391    }
392
393    /// Copy one OR node's context into a representation another search space
394    /// can intern. Hybrid Exact uses this to enter the exact state represented
395    /// by a UCT node rather than silently changing cycle policy.
396    pub(crate) fn cycle_context(&self, or_id: A::Or) -> CycleContext<A::Class> {
397        let ctx_l = *self.or_arena.left_ctx.get(or_id.to_index());
398        let ctx_r = *self.or_arena.right_ctx.get(or_id.to_index());
399        match self.cycle_mode {
400            CycleMode::Pair => CycleContext::Pairs(self.pair_contexts.get(ctx_l).to_vec()),
401            CycleMode::AncestorOnly | CycleMode::CurrentInclusive => CycleContext::Sides {
402                left: self.contexts.get(ctx_l).to_vec(),
403                right: self.contexts.get(ctx_r).to_vec(),
404            },
405        }
406    }
407
408    /// Intern an external context under this space's configured policy.
409    pub(crate) fn intern_cycle_context(
410        &mut self,
411        context: &CycleContext<A::Class>,
412    ) -> (A::Context, A::Context) {
413        match (self.cycle_mode, context) {
414            (
415                CycleMode::AncestorOnly | CycleMode::CurrentInclusive,
416                CycleContext::Sides { left, right },
417            ) => (self.contexts.intern(left), self.contexts.intern(right)),
418            (CycleMode::Pair, CycleContext::Pairs(pairs)) => {
419                (self.pair_contexts.intern(pairs), self.pair_contexts.empty())
420            }
421            _ => panic!("cycle context does not match the search space's cycle mode"),
422        }
423    }
424
425    /// Look up or create an OR node for the given state. Returns `(id, is_new)`.
426    pub fn get_or_insert_or_node(
427        &mut self,
428        l: A::Class,
429        r: A::Class,
430        ctx_l: A::Context,
431        ctx_r: A::Context,
432        left_best_size: u32,
433        right_best_size: u32,
434    ) -> (A::Or, bool) {
435        let key = (l, r, ctx_l, ctx_r);
436        if let Some(log_idx) = self.or_arena.by_key.id_of(&key) {
437            return (*self.or_arena.by_key.get_val(log_idx), false);
438        }
439        let id: A::Or = crate::id::id_at_index(self.or_arena.len());
440        self.or_arena
441            .left
442            .try_push(l)
443            .expect("AU arena sized by its index word");
444        self.or_arena
445            .right
446            .try_push(r)
447            .expect("AU arena sized by its index word");
448        self.or_arena
449            .left_ctx
450            .try_push(ctx_l)
451            .expect("AU arena sized by its index word");
452        self.or_arena
453            .right_ctx
454            .try_push(ctx_r)
455            .expect("AU arena sized by its index word");
456        self.or_arena
457            .terminal
458            .try_push(l == r)
459            .expect("AU arena sized by its index word");
460        self.or_arena
461            .left_best_size
462            .try_push(left_best_size)
463            .expect("AU arena sized by its index word");
464        self.or_arena
465            .right_best_size
466            .try_push(right_best_size)
467            .expect("AU arena sized by its index word");
468        self.or_arena
469            .by_key
470            .try_insert(key, id)
471            .expect("AU arena sized by its index word");
472        (id, true)
473    }
474
475    /// Derive the child context for one side (§2.3).
476    pub fn derive_child_context(
477        &mut self,
478        parent_ctx: A::Context,
479        parent_class: A::Class,
480        is_reachable_from_child: impl Fn(A::Class) -> bool,
481    ) -> A::Context {
482        let parent_classes = self.contexts.get(parent_ctx);
483
484        let mut result: Vec<A::Class> = Vec::new();
485        for &c in parent_classes {
486            if is_reachable_from_child(c) {
487                result.push(c);
488            }
489        }
490        if is_reachable_from_child(parent_class) && result.binary_search(&parent_class).is_err() {
491            result.push(parent_class);
492            result.sort_unstable();
493        }
494
495        self.contexts.intern(&result)
496    }
497
498    /// Derive both child-context ids under the configured cycle policy.
499    pub fn derive_child_contexts(
500        &mut self,
501        parent_or: A::Or,
502        _child_l: A::Class,
503        _child_r: A::Class,
504        is_left_reachable: impl Fn(A::Class) -> bool,
505        is_right_reachable: impl Fn(A::Class) -> bool,
506    ) -> (A::Context, A::Context) {
507        let index = parent_or.to_index();
508        let parent_l = *self.or_arena.left.get(index);
509        let parent_r = *self.or_arena.right.get(index);
510        let ctx_l = *self.or_arena.left_ctx.get(index);
511        let ctx_r = *self.or_arena.right_ctx.get(index);
512
513        match self.cycle_mode {
514            CycleMode::AncestorOnly | CycleMode::CurrentInclusive => (
515                self.derive_child_context(ctx_l, parent_l, is_left_reachable),
516                self.derive_child_context(ctx_r, parent_r, is_right_reachable),
517            ),
518            CycleMode::Pair => {
519                let mut result: Vec<(A::Class, A::Class)> = self
520                    .pair_contexts
521                    .get(ctx_l)
522                    .iter()
523                    .copied()
524                    .filter(|(left, right)| is_left_reachable(*left) && is_right_reachable(*right))
525                    .collect();
526                let parent = (parent_l, parent_r);
527                if is_left_reachable(parent_l)
528                    && is_right_reachable(parent_r)
529                    && result.binary_search(&parent).is_err()
530                {
531                    result.push(parent);
532                    result.sort_unstable();
533                }
534                (
535                    self.pair_contexts.intern(&result),
536                    self.pair_contexts.empty(),
537                )
538            }
539        }
540    }
541
542    /// Intern `ctx` extended with `class` (no-op when already present).
543    ///
544    /// Identity padding needs this: the injected identity class is not a
545    /// structural child of any member, so [`Self::derive_child_context`]'s
546    /// reachability filter records nothing for it, and without the extension
547    /// a padding-created cell can repeat its ancestor's full OR key exactly.
548    /// Extending the padded cell's side contexts
549    /// restores the rank argument's "context grows" disjunct (§3.2):
550    /// contexts are bounded by the class count, so the recursion terminates.
551    pub fn extend_context(&mut self, ctx: A::Context, class: A::Class) -> A::Context {
552        if self.contexts.contains(ctx, class) {
553            return ctx;
554        }
555        let mut classes: Vec<A::Class> = self.contexts.get(ctx).to_vec();
556        classes.push(class);
557        classes.sort_unstable();
558        self.contexts.intern(&classes)
559    }
560
561    /// Apply the identity-padding rank guard to side contexts. Pair mode
562    /// already blocks an exact child-pair recurrence, so no synthetic pair is
563    /// needed for padding.
564    pub fn extend_child_contexts(
565        &mut self,
566        ctx_l: A::Context,
567        ctx_r: A::Context,
568        class: A::Class,
569    ) -> (A::Context, A::Context) {
570        match self.cycle_mode {
571            CycleMode::Pair => (ctx_l, ctx_r),
572            CycleMode::AncestorOnly | CycleMode::CurrentInclusive => (
573                self.extend_context(ctx_l, class),
574                self.extend_context(ctx_r, class),
575            ),
576        }
577    }
578
579    /// Check if an action's child pair is blocked by the cycle mode filter.
580    pub fn is_cycle_blocked(&self, or_id: A::Or, child_l: A::Class, child_r: A::Class) -> bool {
581        let ctx_l = *self.or_arena.left_ctx.get(or_id.to_index());
582        let ctx_r = *self.or_arena.right_ctx.get(or_id.to_index());
583
584        match self.cycle_mode {
585            CycleMode::AncestorOnly => {
586                self.contexts.contains(ctx_l, child_l) || self.contexts.contains(ctx_r, child_r)
587            }
588            CycleMode::CurrentInclusive => {
589                if self.contexts.contains(ctx_l, child_l) || self.contexts.contains(ctx_r, child_r)
590                {
591                    return true;
592                }
593                let l = *self.or_arena.left.get(or_id.to_index());
594                let r = *self.or_arena.right.get(or_id.to_index());
595                child_l == l || child_r == r
596            }
597            CycleMode::Pair => {
598                if self.pair_contexts.contains(ctx_l, (child_l, child_r)) {
599                    return true;
600                }
601                let l = *self.or_arena.left.get(or_id.to_index());
602                let r = *self.or_arena.right.get(or_id.to_index());
603                child_l == l && child_r == r
604            }
605        }
606    }
607
608    pub fn mark(&mut self) -> SpaceToken {
609        SpaceToken {
610            or_arena: self.or_arena.mark(),
611            contexts: self.contexts.mark(),
612            pair_contexts: self.pair_contexts.mark(),
613        }
614    }
615
616    /// Is this token restorable right now (same instances, live branches on
617    /// every inner container)?
618    pub fn is_valid_token(&self, token: &SpaceToken) -> bool {
619        self.or_arena.is_valid_token(&token.or_arena)
620            && self.contexts.is_valid_token(&token.contexts)
621            && self.pair_contexts.is_valid_token(&token.pair_contexts)
622    }
623
624    pub fn restore(&mut self, token: SpaceToken) {
625        self.or_arena.restore(token.or_arena);
626        self.contexts.restore(token.contexts);
627        self.pair_contexts.restore(token.pair_contexts);
628    }
629}
630
631#[cfg(test)]
632mod tests {
633    use super::*;
634    use crate::au::AuClassId;
635
636    #[test]
637    fn context_interner_empty() {
638        let store: ContextStore = ContextStore::new();
639        assert_eq!(store.empty(), CtxId::from_usize(0));
640        assert_eq!(store.get(store.empty()), &[]);
641        assert!(!store.contains(store.empty(), AuClassId::from_usize(0)));
642    }
643
644    #[test]
645    fn context_interner_dedup() {
646        let mut store: ContextStore = ContextStore::new();
647        let c0 = AuClassId::from_usize(0);
648        let c1 = AuClassId::from_usize(1);
649        let c2 = AuClassId::from_usize(2);
650
651        let ctx_a = store.intern(&[c0, c1]);
652        let ctx_b = store.intern(&[c0, c1]);
653        assert_eq!(ctx_a, ctx_b);
654
655        let ctx_c = store.intern(&[c0, c1, c2]);
656        assert_ne!(ctx_a, ctx_c);
657
658        assert!(store.contains(ctx_a, c0));
659        assert!(store.contains(ctx_a, c1));
660        assert!(!store.contains(ctx_a, c2));
661        assert!(store.contains(ctx_c, c2));
662    }
663
664    #[test]
665    fn or_node_dedup() {
666        let mut space: SearchSpace = SearchSpace::new(CycleMode::AncestorOnly);
667        let c0 = AuClassId::from_usize(0);
668        let c1 = AuClassId::from_usize(1);
669        let ctx = space.contexts.empty();
670
671        let (id1, new1) = space.get_or_insert_or_node(c0, c1, ctx, ctx, 1, 1);
672        assert!(new1);
673
674        let (id2, new2) = space.get_or_insert_or_node(c0, c1, ctx, ctx, 1, 1);
675        assert!(!new2);
676        assert_eq!(id1, id2);
677
678        let (id3, new3) = space.get_or_insert_or_node(c1, c0, ctx, ctx, 1, 1);
679        assert!(new3);
680        assert_ne!(id1, id3);
681    }
682
683    #[test]
684    fn derive_child_context_acyclic() {
685        let mut space: SearchSpace = SearchSpace::new(CycleMode::AncestorOnly);
686        let parent_ctx = space.contexts.empty();
687        let parent_class = AuClassId::from_usize(0);
688
689        let child_ctx = space.derive_child_context(parent_ctx, parent_class, |_| false);
690        assert_eq!(child_ctx, space.contexts.empty());
691    }
692
693    #[test]
694    fn derive_child_context_cyclic() {
695        let mut space: SearchSpace = SearchSpace::new(CycleMode::AncestorOnly);
696        let c0 = AuClassId::from_usize(0);
697        let c1 = AuClassId::from_usize(1);
698
699        let parent_ctx = space.contexts.intern(&[c0]);
700        let parent_class = c1;
701
702        let child_ctx =
703            space.derive_child_context(parent_ctx, parent_class, |c| c == c0 || c == c1);
704
705        let ctx_classes = space.contexts.get(child_ctx);
706        assert_eq!(ctx_classes, &[c0, c1]);
707    }
708
709    #[test]
710    fn cycle_blocking_ancestor_only() {
711        let mut space: SearchSpace = SearchSpace::new(CycleMode::AncestorOnly);
712        let c0 = AuClassId::from_usize(0);
713        let c1 = AuClassId::from_usize(1);
714        let c2 = AuClassId::from_usize(2);
715
716        let ctx_l = space.contexts.intern(&[c0]);
717        let ctx_r = space.contexts.empty();
718        let (or_id, _) = space.get_or_insert_or_node(c1, c2, ctx_l, ctx_r, 1, 1);
719
720        assert!(space.is_cycle_blocked(or_id, c0, c2));
721        assert!(!space.is_cycle_blocked(or_id, c1, c2));
722        assert!(!space.is_cycle_blocked(or_id, c1, c2));
723    }
724
725    #[test]
726    fn cycle_blocking_current_inclusive() {
727        let mut space: SearchSpace = SearchSpace::new(CycleMode::CurrentInclusive);
728        let c0 = AuClassId::from_usize(0);
729        let c1 = AuClassId::from_usize(1);
730        let c2 = AuClassId::from_usize(2);
731
732        let ctx_l = space.contexts.empty();
733        let ctx_r = space.contexts.empty();
734        let (or_id, _) = space.get_or_insert_or_node(c1, c2, ctx_l, ctx_r, 1, 1);
735
736        assert!(space.is_cycle_blocked(or_id, c1, c0));
737        assert!(space.is_cycle_blocked(or_id, c0, c2));
738        assert!(!space.is_cycle_blocked(or_id, c0, c0));
739    }
740
741    #[test]
742    fn cycle_blocking_pair_preserves_one_sided_revisits() {
743        let mut space: SearchSpace = SearchSpace::new(CycleMode::Pair);
744        let c0 = AuClassId::from_usize(0);
745        let c1 = AuClassId::from_usize(1);
746        let c2 = AuClassId::from_usize(2);
747        let (empty_l, empty_r) = space.empty_contexts();
748        let (root, _) = space.get_or_insert_or_node(c1, c2, empty_l, empty_r, 1, 1);
749
750        assert!(space.is_cycle_blocked(root, c1, c2));
751        assert!(!space.is_cycle_blocked(root, c1, c0));
752        assert!(!space.is_cycle_blocked(root, c0, c2));
753
754        let (child_l, child_r) = space.derive_child_contexts(root, c1, c0, |_| true, |_| true);
755        let (child, _) = space.get_or_insert_or_node(c1, c0, child_l, child_r, 1, 1);
756        assert!(space.is_cycle_blocked(child, c1, c2));
757        assert!(!space.is_cycle_blocked(child, c1, c1));
758        assert_eq!(
759            space.cycle_context(child),
760            CycleContext::Pairs(vec![(c1, c2)])
761        );
762    }
763
764    #[test]
765    fn terminal_when_l_eq_r() {
766        let mut space: SearchSpace = SearchSpace::new(CycleMode::AncestorOnly);
767        let c0 = AuClassId::from_usize(0);
768        let ctx = space.contexts.empty();
769
770        let (or_id, _) = space.get_or_insert_or_node(c0, c0, ctx, ctx, 1, 1);
771        assert!(*space.or_arena.terminal.get(or_id.to_index()));
772    }
773
774    #[test]
775    fn mark_restore_truncates() {
776        let mut space: SearchSpace = SearchSpace::new(CycleMode::AncestorOnly);
777        let c0 = AuClassId::from_usize(0);
778        let c1 = AuClassId::from_usize(1);
779        let c2 = AuClassId::from_usize(2);
780        let ctx = space.contexts.empty();
781
782        let (id1, _) = space.get_or_insert_or_node(c0, c1, ctx, ctx, 1, 1);
783        let token = space.mark();
784
785        let (_id2, _) = space.get_or_insert_or_node(c1, c2, ctx, ctx, 1, 1);
786        assert_eq!(space.or_arena.len(), 2);
787
788        space.restore(token);
789        assert_eq!(space.or_arena.len(), 1);
790
791        // The first node is still there.
792        let (id1b, new) = space.get_or_insert_or_node(c0, c1, ctx, ctx, 1, 1);
793        assert!(!new);
794        assert_eq!(id1, id1b);
795
796        // The second node was rolled back; re-inserting it is new.
797        let (_, new) = space.get_or_insert_or_node(c1, c2, ctx, ctx, 1, 1);
798        assert!(new);
799    }
800
801    #[test]
802    fn mark_restore_truncates_pair_contexts() {
803        let mut space: SearchSpace = SearchSpace::new(CycleMode::Pair);
804        let c0 = AuClassId::from_usize(0);
805        let c1 = AuClassId::from_usize(1);
806        let c2 = AuClassId::from_usize(2);
807        let (empty_l, empty_r) = space.empty_contexts();
808        let (root, _) = space.get_or_insert_or_node(c0, c1, empty_l, empty_r, 1, 1);
809        let token = space.mark();
810
811        let (child_l, child_r) = space.derive_child_contexts(root, c1, c2, |_| true, |_| true);
812        let (child, _) = space.get_or_insert_or_node(c1, c2, child_l, child_r, 1, 1);
813        assert_eq!(
814            space.cycle_context(child),
815            CycleContext::Pairs(vec![(c0, c1)])
816        );
817        assert_eq!(space.pair_contexts.len().as_usize(), 2);
818
819        space.restore(token);
820        assert_eq!(space.or_arena.len(), 1);
821        assert_eq!(space.pair_contexts.len().as_usize(), 1);
822        assert_eq!(space.cycle_context(root), CycleContext::Pairs(Vec::new()));
823
824        let (child_l, child_r) = space.derive_child_contexts(root, c1, c2, |_| true, |_| true);
825        let (_, new) = space.get_or_insert_or_node(c1, c2, child_l, child_r, 1, 1);
826        assert!(new);
827    }
828}