semi-persistent-egraph 0.2.0

Semi-persistent equality saturation engine with e-matching, rewrite scheduling, and proof logging
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//! Search-space layer: OR/AND arenas, context interner, node/edge caches (§4.2).
//!
//! The search space is an AND/OR graph where OR nodes are subproblems `AU(l, r)`
//! keyed by the class pair plus two opaque context-id slots. Side modes use one
//! class context per slot; pair mode stores an ordered-pair context in the first.
//! AND nodes are chosen factorings (operator + paired children). Everything here
//! is immutable once pushed (hash-cons semantics).
//! All storage uses semi-persistent containers (AppendOnlyVec for structural fields,
//! SpMap for deduplication caches); mark/restore truncates them as one unit.

use crate::config::AuIds;
use crate::containers::{
    AppendOnlyVec, DenseId, IndexLike, MapToken, ShrinkPolicy, SpMap, VecToken,
};

use super::{AuIds31, Span};

// ---------------------------------------------------------------------------
// Id types
// ---------------------------------------------------------------------------

crate::containers::define_id31! {
    /// Index of an OR node in the search-space layer.
    pub struct OrId / StoredOrId, "or";
}

crate::containers::define_id31! {
    /// Index of a cached action list in the action cache.
    pub struct ActionId / StoredActionId, "act";
}

crate::containers::define_id31! {
    /// Interned context id (a sorted vector of AuClassId).
    pub struct CtxId / StoredCtxId, "ctx";
}

// ---------------------------------------------------------------------------
// CycleMode
// ---------------------------------------------------------------------------

/// Which path component breaks cycles (§2.3).
///
/// The two legacy modes track the left and right class paths separately.
/// [`CycleMode::Pair`] tracks ordered class pairs instead, so revisiting one
/// side is allowed when the other side has changed. Every AU algorithm
/// consumes this same policy: root Exact, UCT, and Exact calls delegated by
/// UCT.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum CycleMode {
    /// Side-based filtering against ancestor contexts only. A class can occur
    /// at most twice per side on a path (once as the current node, once as a
    /// child).
    #[default]
    AncestorOnly,
    /// Side-based filtering against ancestors and the current `(l, r)`. A
    /// class occurs at most once per side on a path.
    CurrentInclusive,
    /// Pair-based filtering against ancestors and the current ordered pair.
    /// A left or right class may repeat by itself; only an already-active
    /// `(left, right)` pair is blocked.
    Pair,
}

// ---------------------------------------------------------------------------
// Context interner (semi-persistent: AppendOnlyVec + SpMap)
// ---------------------------------------------------------------------------

/// Interns sorted context-item vectors as context ids. Two equal vectors get
/// the same context id; comparison is then a single integer compare.
///
/// Both pools and the dedup map are addressed by ids whose `Index` is `A::Index`
/// (`A::Context` for `spans`, `A::ContextElem` for `items`, and `index`'s log
/// positions are what `A::Context`s are minted from), so that word is the index type
/// rather than `usize`.
pub struct ContextStore<A: AuIds = AuIds31, T = <A as AuIds>::Class>
where
    T: Copy + Ord + core::hash::Hash,
{
    /// Each interned context's data as a typed span into `items`.
    spans: AppendOnlyVec<Span<A::ContextElem>, A::Index>,
    /// Pool of items (all interned contexts concatenated).
    items: AppendOnlyVec<T, A::Index>,
    /// Deduplication map: sorted item vector -> context id.
    index: SpMap<Vec<T>, A::Context, A::Index>,
}

/// Token for restoring a `ContextStore` to a previous state.
#[derive(Clone, Copy, Debug)]
pub struct ContextStoreToken {
    spans: VecToken,
    items: VecToken,
    index: MapToken,
}

impl<A: AuIds, T> ContextStore<A, T>
where
    T: Copy + Ord + core::hash::Hash,
{
    pub fn new() -> Self {
        let mut store = ContextStore {
            spans: AppendOnlyVec::new(),
            items: AppendOnlyVec::new(),
            index: SpMap::new(),
        };
        store.intern(&[]);
        store
    }

    pub fn empty(&self) -> A::Context {
        // The empty context is interned first in `new`, so id 0 is it. Id 0 exists in every
        // id family, so this mint needs no check.
        A::Context::from_usize(0)
    }

    pub fn intern(&mut self, sorted_items: &[T]) -> A::Context {
        if let Some(log_idx) = self.index.id_of(&sorted_items.to_vec()) {
            return *self.index.get_val(log_idx);
        }
        let id: A::Context = crate::id::id_at_index(self.spans.len());
        let start = self.items.len().as_usize();
        for &item in sorted_items {
            self.items
                .try_push(item)
                .expect("AU arena sized by its index word");
        }
        self.spans
            .try_push(Span::new(start, sorted_items.len()))
            .expect("AU arena sized by its index word");
        self.index
            .try_insert(sorted_items.to_vec(), id)
            .expect("AU arena sized by its index word");
        id
    }

    #[inline]
    pub fn get(&self, id: A::Context) -> &[T] {
        let span = *self.spans.get(id.to_index());
        let start = span.start_usize();
        let len = span.len_usize();
        // `as_slice()` is the verified accessor for exactly this: its
        // postcondition is `r@ == self.view()`, so the contiguity this used to
        // assert with `from_raw_parts` is now a proof obligation the container
        // discharges. The span was built by `intern`, which pushes the elements
        // consecutively, so `[start, start + len)` is in bounds — and if it ever
        // were not, this panics instead of reading out of bounds.
        &self.items.as_slice()[start..start + len]
    }

    #[inline]
    pub fn contains(&self, id: A::Context, item: T) -> bool {
        self.get(id).binary_search(&item).is_ok()
    }

    /// Number of interned contexts, in the configured index word (a context count is
    /// a position count: the next context interns at exactly this index).
    pub fn len(&self) -> A::Index {
        self.spans.len()
    }

    pub fn is_empty(&self) -> bool {
        self.spans.is_empty()
    }

    pub fn mark(&mut self) -> ContextStoreToken {
        ContextStoreToken {
            spans: self
                .spans
                .try_mark(ShrinkPolicy::Never)
                .expect("mark: depth bounded by the search driver"),
            items: self
                .items
                .try_mark(ShrinkPolicy::Never)
                .expect("mark: depth bounded by the search driver"),
            index: self
                .index
                .try_mark(ShrinkPolicy::Never)
                .expect("mark: depth bounded by the search driver"),
        }
    }

    pub fn is_valid_token(&self, token: &ContextStoreToken) -> bool {
        self.spans.is_valid_token(&token.spans)
            && self.items.is_valid_token(&token.items)
            && self.index.is_valid_token(&token.index)
    }

    pub fn restore(&mut self, token: ContextStoreToken) {
        self.index
            .try_restore(token.index)
            .expect("restore: token minted by this container's own mark");
        self.items
            .try_restore(token.items)
            .expect("restore: token minted by this container's own mark");
        self.spans
            .try_restore(token.spans)
            .expect("restore: token minted by this container's own mark");
    }
}

impl<A: AuIds, T> Default for ContextStore<A, T>
where
    T: Copy + Ord + core::hash::Hash,
{
    fn default() -> Self {
        Self::new()
    }
}

/// One contextual Exact/UCT entry context in a representation independent of
/// the interner ids used by a particular [`SearchSpace`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum CycleContext<C> {
    Sides { left: Vec<C>, right: Vec<C> },
    Pairs(Vec<(C, C)>),
}

// ---------------------------------------------------------------------------
// OR arena (semi-persistent: AppendOnlyVec + SpMap)
// ---------------------------------------------------------------------------

/// The OR-node arena: each node is a subproblem `AU(l, r)` with cycle contexts.
/// Every column is addressed by `A::Or`, and `by_key`'s log positions are what the
/// `A::Or`s are minted from, so the index word is `A::Index` throughout.
pub struct OrArena<A: AuIds = AuIds31> {
    pub left: AppendOnlyVec<A::Class, A::Index>,
    pub right: AppendOnlyVec<A::Class, A::Index>,
    pub left_ctx: AppendOnlyVec<A::Context, A::Index>,
    pub right_ctx: AppendOnlyVec<A::Context, A::Index>,
    pub terminal: AppendOnlyVec<bool, A::Index>,
    pub left_best_size: AppendOnlyVec<u32, A::Index>,
    pub right_best_size: AppendOnlyVec<u32, A::Index>,
    pub by_key: SpMap<(A::Class, A::Class, A::Context, A::Context), A::Or, A::Index>,
}

/// Token for restoring an `OrArena`.
#[derive(Clone, Copy, Debug)]
pub struct OrArenaToken {
    left: VecToken,
    right: VecToken,
    left_ctx: VecToken,
    right_ctx: VecToken,
    terminal: VecToken,
    left_best_size: VecToken,
    right_best_size: VecToken,
    by_key: MapToken,
}

impl<A: AuIds> OrArena<A> {
    pub fn new() -> Self {
        OrArena {
            left: AppendOnlyVec::new(),
            right: AppendOnlyVec::new(),
            left_ctx: AppendOnlyVec::new(),
            right_ctx: AppendOnlyVec::new(),
            terminal: AppendOnlyVec::new(),
            left_best_size: AppendOnlyVec::new(),
            right_best_size: AppendOnlyVec::new(),
            by_key: SpMap::new(),
        }
    }

    /// Number of OR nodes, in the configured index word (the next node lands at
    /// exactly this index).
    pub fn len(&self) -> A::Index {
        self.left.len()
    }

    pub fn is_empty(&self) -> bool {
        self.left.is_empty()
    }

    pub fn mark(&mut self) -> OrArenaToken {
        OrArenaToken {
            left: self
                .left
                .try_mark(ShrinkPolicy::Never)
                .expect("mark: depth bounded by the search driver"),
            right: self
                .right
                .try_mark(ShrinkPolicy::Never)
                .expect("mark: depth bounded by the search driver"),
            left_ctx: self
                .left_ctx
                .try_mark(ShrinkPolicy::Never)
                .expect("mark: depth bounded by the search driver"),
            right_ctx: self
                .right_ctx
                .try_mark(ShrinkPolicy::Never)
                .expect("mark: depth bounded by the search driver"),
            terminal: self
                .terminal
                .try_mark(ShrinkPolicy::Never)
                .expect("mark: depth bounded by the search driver"),
            left_best_size: self
                .left_best_size
                .try_mark(ShrinkPolicy::Never)
                .expect("mark: depth bounded by the search driver"),
            right_best_size: self
                .right_best_size
                .try_mark(ShrinkPolicy::Never)
                .expect("mark: depth bounded by the search driver"),
            by_key: self
                .by_key
                .try_mark(ShrinkPolicy::Never)
                .expect("mark: depth bounded by the search driver"),
        }
    }

    pub fn restore(&mut self, token: OrArenaToken) {
        self.by_key
            .try_restore(token.by_key)
            .expect("restore: token minted by this container's own mark");
        self.right_best_size
            .try_restore(token.right_best_size)
            .expect("restore: token minted by this container's own mark");
        self.left_best_size
            .try_restore(token.left_best_size)
            .expect("restore: token minted by this container's own mark");
        self.terminal
            .try_restore(token.terminal)
            .expect("restore: token minted by this container's own mark");
        self.right_ctx
            .try_restore(token.right_ctx)
            .expect("restore: token minted by this container's own mark");
        self.left_ctx
            .try_restore(token.left_ctx)
            .expect("restore: token minted by this container's own mark");
        self.right
            .try_restore(token.right)
            .expect("restore: token minted by this container's own mark");
        self.left
            .try_restore(token.left)
            .expect("restore: token minted by this container's own mark");
    }

    pub fn is_valid_token(&self, token: &OrArenaToken) -> bool {
        self.left.is_valid_token(&token.left)
    }
}

impl<A: AuIds> Default for OrArena<A> {
    fn default() -> Self {
        Self::new()
    }
}

// ---------------------------------------------------------------------------
// SearchSpace: combines the above into one structure
// ---------------------------------------------------------------------------

/// Token for restoring the entire search-space layer. Validity is delegated
/// to the inner semi-persistent containers' branch genealogy.
#[derive(Clone, Copy, Debug)]
pub struct SpaceToken {
    or_arena: OrArenaToken,
    contexts: ContextStoreToken,
    pair_contexts: ContextStoreToken,
}

/// The complete search-space layer shared by all algorithms in a session.
pub struct SearchSpace<A: AuIds = AuIds31> {
    pub or_arena: OrArena<A>,
    pub contexts: ContextStore<A>,
    pub pair_contexts: ContextStore<A, (A::Class, A::Class)>,
    pub cycle_mode: CycleMode,
}

impl<A: AuIds> SearchSpace<A> {
    pub fn new(cycle_mode: CycleMode) -> Self {
        SearchSpace {
            or_arena: OrArena::new(),
            contexts: ContextStore::new(),
            pair_contexts: ContextStore::new(),
            cycle_mode,
        }
    }

    /// The two opaque context ids used for a root state.
    ///
    /// Pair mode stores its ordered-pair context in the left slot and keeps
    /// the right slot empty. Side modes use both slots as before.
    pub fn empty_contexts(&self) -> (A::Context, A::Context) {
        match self.cycle_mode {
            CycleMode::Pair => (self.pair_contexts.empty(), self.pair_contexts.empty()),
            CycleMode::AncestorOnly | CycleMode::CurrentInclusive => {
                (self.contexts.empty(), self.contexts.empty())
            }
        }
    }

    /// Copy one OR node's context into a representation another search space
    /// can intern. Hybrid Exact uses this to enter the exact state represented
    /// by a UCT node rather than silently changing cycle policy.
    pub(crate) fn cycle_context(&self, or_id: A::Or) -> CycleContext<A::Class> {
        let ctx_l = *self.or_arena.left_ctx.get(or_id.to_index());
        let ctx_r = *self.or_arena.right_ctx.get(or_id.to_index());
        match self.cycle_mode {
            CycleMode::Pair => CycleContext::Pairs(self.pair_contexts.get(ctx_l).to_vec()),
            CycleMode::AncestorOnly | CycleMode::CurrentInclusive => CycleContext::Sides {
                left: self.contexts.get(ctx_l).to_vec(),
                right: self.contexts.get(ctx_r).to_vec(),
            },
        }
    }

    /// Intern an external context under this space's configured policy.
    pub(crate) fn intern_cycle_context(
        &mut self,
        context: &CycleContext<A::Class>,
    ) -> (A::Context, A::Context) {
        match (self.cycle_mode, context) {
            (
                CycleMode::AncestorOnly | CycleMode::CurrentInclusive,
                CycleContext::Sides { left, right },
            ) => (self.contexts.intern(left), self.contexts.intern(right)),
            (CycleMode::Pair, CycleContext::Pairs(pairs)) => {
                (self.pair_contexts.intern(pairs), self.pair_contexts.empty())
            }
            _ => panic!("cycle context does not match the search space's cycle mode"),
        }
    }

    /// Look up or create an OR node for the given state. Returns `(id, is_new)`.
    pub fn get_or_insert_or_node(
        &mut self,
        l: A::Class,
        r: A::Class,
        ctx_l: A::Context,
        ctx_r: A::Context,
        left_best_size: u32,
        right_best_size: u32,
    ) -> (A::Or, bool) {
        let key = (l, r, ctx_l, ctx_r);
        if let Some(log_idx) = self.or_arena.by_key.id_of(&key) {
            return (*self.or_arena.by_key.get_val(log_idx), false);
        }
        let id: A::Or = crate::id::id_at_index(self.or_arena.len());
        self.or_arena
            .left
            .try_push(l)
            .expect("AU arena sized by its index word");
        self.or_arena
            .right
            .try_push(r)
            .expect("AU arena sized by its index word");
        self.or_arena
            .left_ctx
            .try_push(ctx_l)
            .expect("AU arena sized by its index word");
        self.or_arena
            .right_ctx
            .try_push(ctx_r)
            .expect("AU arena sized by its index word");
        self.or_arena
            .terminal
            .try_push(l == r)
            .expect("AU arena sized by its index word");
        self.or_arena
            .left_best_size
            .try_push(left_best_size)
            .expect("AU arena sized by its index word");
        self.or_arena
            .right_best_size
            .try_push(right_best_size)
            .expect("AU arena sized by its index word");
        self.or_arena
            .by_key
            .try_insert(key, id)
            .expect("AU arena sized by its index word");
        (id, true)
    }

    /// Derive the child context for one side (§2.3).
    pub fn derive_child_context(
        &mut self,
        parent_ctx: A::Context,
        parent_class: A::Class,
        is_reachable_from_child: impl Fn(A::Class) -> bool,
    ) -> A::Context {
        let parent_classes = self.contexts.get(parent_ctx);

        let mut result: Vec<A::Class> = Vec::new();
        for &c in parent_classes {
            if is_reachable_from_child(c) {
                result.push(c);
            }
        }
        if is_reachable_from_child(parent_class) && result.binary_search(&parent_class).is_err() {
            result.push(parent_class);
            result.sort_unstable();
        }

        self.contexts.intern(&result)
    }

    /// Derive both child-context ids under the configured cycle policy.
    pub fn derive_child_contexts(
        &mut self,
        parent_or: A::Or,
        _child_l: A::Class,
        _child_r: A::Class,
        is_left_reachable: impl Fn(A::Class) -> bool,
        is_right_reachable: impl Fn(A::Class) -> bool,
    ) -> (A::Context, A::Context) {
        let index = parent_or.to_index();
        let parent_l = *self.or_arena.left.get(index);
        let parent_r = *self.or_arena.right.get(index);
        let ctx_l = *self.or_arena.left_ctx.get(index);
        let ctx_r = *self.or_arena.right_ctx.get(index);

        match self.cycle_mode {
            CycleMode::AncestorOnly | CycleMode::CurrentInclusive => (
                self.derive_child_context(ctx_l, parent_l, is_left_reachable),
                self.derive_child_context(ctx_r, parent_r, is_right_reachable),
            ),
            CycleMode::Pair => {
                let mut result: Vec<(A::Class, A::Class)> = self
                    .pair_contexts
                    .get(ctx_l)
                    .iter()
                    .copied()
                    .filter(|(left, right)| is_left_reachable(*left) && is_right_reachable(*right))
                    .collect();
                let parent = (parent_l, parent_r);
                if is_left_reachable(parent_l)
                    && is_right_reachable(parent_r)
                    && result.binary_search(&parent).is_err()
                {
                    result.push(parent);
                    result.sort_unstable();
                }
                (
                    self.pair_contexts.intern(&result),
                    self.pair_contexts.empty(),
                )
            }
        }
    }

    /// Intern `ctx` extended with `class` (no-op when already present).
    ///
    /// Identity padding needs this: the injected identity class is not a
    /// structural child of any member, so [`Self::derive_child_context`]'s
    /// reachability filter records nothing for it, and without the extension
    /// a padding-created cell can repeat its ancestor's full OR key exactly.
    /// Extending the padded cell's side contexts
    /// restores the rank argument's "context grows" disjunct (§3.2):
    /// contexts are bounded by the class count, so the recursion terminates.
    pub fn extend_context(&mut self, ctx: A::Context, class: A::Class) -> A::Context {
        if self.contexts.contains(ctx, class) {
            return ctx;
        }
        let mut classes: Vec<A::Class> = self.contexts.get(ctx).to_vec();
        classes.push(class);
        classes.sort_unstable();
        self.contexts.intern(&classes)
    }

    /// Apply the identity-padding rank guard to side contexts. Pair mode
    /// already blocks an exact child-pair recurrence, so no synthetic pair is
    /// needed for padding.
    pub fn extend_child_contexts(
        &mut self,
        ctx_l: A::Context,
        ctx_r: A::Context,
        class: A::Class,
    ) -> (A::Context, A::Context) {
        match self.cycle_mode {
            CycleMode::Pair => (ctx_l, ctx_r),
            CycleMode::AncestorOnly | CycleMode::CurrentInclusive => (
                self.extend_context(ctx_l, class),
                self.extend_context(ctx_r, class),
            ),
        }
    }

    /// Check if an action's child pair is blocked by the cycle mode filter.
    pub fn is_cycle_blocked(&self, or_id: A::Or, child_l: A::Class, child_r: A::Class) -> bool {
        let ctx_l = *self.or_arena.left_ctx.get(or_id.to_index());
        let ctx_r = *self.or_arena.right_ctx.get(or_id.to_index());

        match self.cycle_mode {
            CycleMode::AncestorOnly => {
                self.contexts.contains(ctx_l, child_l) || self.contexts.contains(ctx_r, child_r)
            }
            CycleMode::CurrentInclusive => {
                if self.contexts.contains(ctx_l, child_l) || self.contexts.contains(ctx_r, child_r)
                {
                    return true;
                }
                let l = *self.or_arena.left.get(or_id.to_index());
                let r = *self.or_arena.right.get(or_id.to_index());
                child_l == l || child_r == r
            }
            CycleMode::Pair => {
                if self.pair_contexts.contains(ctx_l, (child_l, child_r)) {
                    return true;
                }
                let l = *self.or_arena.left.get(or_id.to_index());
                let r = *self.or_arena.right.get(or_id.to_index());
                child_l == l && child_r == r
            }
        }
    }

    pub fn mark(&mut self) -> SpaceToken {
        SpaceToken {
            or_arena: self.or_arena.mark(),
            contexts: self.contexts.mark(),
            pair_contexts: self.pair_contexts.mark(),
        }
    }

    /// Is this token restorable right now (same instances, live branches on
    /// every inner container)?
    pub fn is_valid_token(&self, token: &SpaceToken) -> bool {
        self.or_arena.is_valid_token(&token.or_arena)
            && self.contexts.is_valid_token(&token.contexts)
            && self.pair_contexts.is_valid_token(&token.pair_contexts)
    }

    pub fn restore(&mut self, token: SpaceToken) {
        self.or_arena.restore(token.or_arena);
        self.contexts.restore(token.contexts);
        self.pair_contexts.restore(token.pair_contexts);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::au::AuClassId;

    #[test]
    fn context_interner_empty() {
        let store: ContextStore = ContextStore::new();
        assert_eq!(store.empty(), CtxId::from_usize(0));
        assert_eq!(store.get(store.empty()), &[]);
        assert!(!store.contains(store.empty(), AuClassId::from_usize(0)));
    }

    #[test]
    fn context_interner_dedup() {
        let mut store: ContextStore = ContextStore::new();
        let c0 = AuClassId::from_usize(0);
        let c1 = AuClassId::from_usize(1);
        let c2 = AuClassId::from_usize(2);

        let ctx_a = store.intern(&[c0, c1]);
        let ctx_b = store.intern(&[c0, c1]);
        assert_eq!(ctx_a, ctx_b);

        let ctx_c = store.intern(&[c0, c1, c2]);
        assert_ne!(ctx_a, ctx_c);

        assert!(store.contains(ctx_a, c0));
        assert!(store.contains(ctx_a, c1));
        assert!(!store.contains(ctx_a, c2));
        assert!(store.contains(ctx_c, c2));
    }

    #[test]
    fn or_node_dedup() {
        let mut space: SearchSpace = SearchSpace::new(CycleMode::AncestorOnly);
        let c0 = AuClassId::from_usize(0);
        let c1 = AuClassId::from_usize(1);
        let ctx = space.contexts.empty();

        let (id1, new1) = space.get_or_insert_or_node(c0, c1, ctx, ctx, 1, 1);
        assert!(new1);

        let (id2, new2) = space.get_or_insert_or_node(c0, c1, ctx, ctx, 1, 1);
        assert!(!new2);
        assert_eq!(id1, id2);

        let (id3, new3) = space.get_or_insert_or_node(c1, c0, ctx, ctx, 1, 1);
        assert!(new3);
        assert_ne!(id1, id3);
    }

    #[test]
    fn derive_child_context_acyclic() {
        let mut space: SearchSpace = SearchSpace::new(CycleMode::AncestorOnly);
        let parent_ctx = space.contexts.empty();
        let parent_class = AuClassId::from_usize(0);

        let child_ctx = space.derive_child_context(parent_ctx, parent_class, |_| false);
        assert_eq!(child_ctx, space.contexts.empty());
    }

    #[test]
    fn derive_child_context_cyclic() {
        let mut space: SearchSpace = SearchSpace::new(CycleMode::AncestorOnly);
        let c0 = AuClassId::from_usize(0);
        let c1 = AuClassId::from_usize(1);

        let parent_ctx = space.contexts.intern(&[c0]);
        let parent_class = c1;

        let child_ctx =
            space.derive_child_context(parent_ctx, parent_class, |c| c == c0 || c == c1);

        let ctx_classes = space.contexts.get(child_ctx);
        assert_eq!(ctx_classes, &[c0, c1]);
    }

    #[test]
    fn cycle_blocking_ancestor_only() {
        let mut space: SearchSpace = SearchSpace::new(CycleMode::AncestorOnly);
        let c0 = AuClassId::from_usize(0);
        let c1 = AuClassId::from_usize(1);
        let c2 = AuClassId::from_usize(2);

        let ctx_l = space.contexts.intern(&[c0]);
        let ctx_r = space.contexts.empty();
        let (or_id, _) = space.get_or_insert_or_node(c1, c2, ctx_l, ctx_r, 1, 1);

        assert!(space.is_cycle_blocked(or_id, c0, c2));
        assert!(!space.is_cycle_blocked(or_id, c1, c2));
        assert!(!space.is_cycle_blocked(or_id, c1, c2));
    }

    #[test]
    fn cycle_blocking_current_inclusive() {
        let mut space: SearchSpace = SearchSpace::new(CycleMode::CurrentInclusive);
        let c0 = AuClassId::from_usize(0);
        let c1 = AuClassId::from_usize(1);
        let c2 = AuClassId::from_usize(2);

        let ctx_l = space.contexts.empty();
        let ctx_r = space.contexts.empty();
        let (or_id, _) = space.get_or_insert_or_node(c1, c2, ctx_l, ctx_r, 1, 1);

        assert!(space.is_cycle_blocked(or_id, c1, c0));
        assert!(space.is_cycle_blocked(or_id, c0, c2));
        assert!(!space.is_cycle_blocked(or_id, c0, c0));
    }

    #[test]
    fn cycle_blocking_pair_preserves_one_sided_revisits() {
        let mut space: SearchSpace = SearchSpace::new(CycleMode::Pair);
        let c0 = AuClassId::from_usize(0);
        let c1 = AuClassId::from_usize(1);
        let c2 = AuClassId::from_usize(2);
        let (empty_l, empty_r) = space.empty_contexts();
        let (root, _) = space.get_or_insert_or_node(c1, c2, empty_l, empty_r, 1, 1);

        assert!(space.is_cycle_blocked(root, c1, c2));
        assert!(!space.is_cycle_blocked(root, c1, c0));
        assert!(!space.is_cycle_blocked(root, c0, c2));

        let (child_l, child_r) = space.derive_child_contexts(root, c1, c0, |_| true, |_| true);
        let (child, _) = space.get_or_insert_or_node(c1, c0, child_l, child_r, 1, 1);
        assert!(space.is_cycle_blocked(child, c1, c2));
        assert!(!space.is_cycle_blocked(child, c1, c1));
        assert_eq!(
            space.cycle_context(child),
            CycleContext::Pairs(vec![(c1, c2)])
        );
    }

    #[test]
    fn terminal_when_l_eq_r() {
        let mut space: SearchSpace = SearchSpace::new(CycleMode::AncestorOnly);
        let c0 = AuClassId::from_usize(0);
        let ctx = space.contexts.empty();

        let (or_id, _) = space.get_or_insert_or_node(c0, c0, ctx, ctx, 1, 1);
        assert!(*space.or_arena.terminal.get(or_id.to_index()));
    }

    #[test]
    fn mark_restore_truncates() {
        let mut space: SearchSpace = SearchSpace::new(CycleMode::AncestorOnly);
        let c0 = AuClassId::from_usize(0);
        let c1 = AuClassId::from_usize(1);
        let c2 = AuClassId::from_usize(2);
        let ctx = space.contexts.empty();

        let (id1, _) = space.get_or_insert_or_node(c0, c1, ctx, ctx, 1, 1);
        let token = space.mark();

        let (_id2, _) = space.get_or_insert_or_node(c1, c2, ctx, ctx, 1, 1);
        assert_eq!(space.or_arena.len(), 2);

        space.restore(token);
        assert_eq!(space.or_arena.len(), 1);

        // The first node is still there.
        let (id1b, new) = space.get_or_insert_or_node(c0, c1, ctx, ctx, 1, 1);
        assert!(!new);
        assert_eq!(id1, id1b);

        // The second node was rolled back; re-inserting it is new.
        let (_, new) = space.get_or_insert_or_node(c1, c2, ctx, ctx, 1, 1);
        assert!(new);
    }

    #[test]
    fn mark_restore_truncates_pair_contexts() {
        let mut space: SearchSpace = SearchSpace::new(CycleMode::Pair);
        let c0 = AuClassId::from_usize(0);
        let c1 = AuClassId::from_usize(1);
        let c2 = AuClassId::from_usize(2);
        let (empty_l, empty_r) = space.empty_contexts();
        let (root, _) = space.get_or_insert_or_node(c0, c1, empty_l, empty_r, 1, 1);
        let token = space.mark();

        let (child_l, child_r) = space.derive_child_contexts(root, c1, c2, |_| true, |_| true);
        let (child, _) = space.get_or_insert_or_node(c1, c2, child_l, child_r, 1, 1);
        assert_eq!(
            space.cycle_context(child),
            CycleContext::Pairs(vec![(c0, c1)])
        );
        assert_eq!(space.pair_contexts.len().as_usize(), 2);

        space.restore(token);
        assert_eq!(space.or_arena.len(), 1);
        assert_eq!(space.pair_contexts.len().as_usize(), 1);
        assert_eq!(space.cycle_context(root), CycleContext::Pairs(Vec::new()));

        let (child_l, child_r) = space.derive_child_contexts(root, c1, c2, |_| true, |_| true);
        let (_, new) = space.get_or_insert_or_node(c1, c2, child_l, child_r, 1, 1);
        assert!(new);
    }
}