Skip to main content

semi_persistent_egraph/au/
terms.rs

1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// SPDX-License-Identifier: Apache-2.0
3//! Result-term pool (§4.4): hash-consed arena of anti-unifier terms.
4//!
5//! Terms are `(TermOp, children)` where children are spans into a shared pool.
6//! `Variants` nodes have two children (left, right projections). Size counts 1
7//! per ordinary node and 0 for each `Variants` node (its children are counted).
8
9use crate::canon::{MSetCanon, VarCanon};
10use crate::config::{AuIds, EGraphConfig};
11use crate::containers::{
12    AppendOnlyVec, DenseId, IndexLike, MapToken, ShrinkPolicy, SpMap, VecToken,
13};
14use crate::literal::LitVal;
15use crate::multiplicity::MultiplicityLike;
16
17use super::egraph_api::{AuSnapshot, ClassOf};
18use super::{AuIds31, Span};
19
20crate::containers::define_id31! {
21    /// Index of a term in the hash-consed term pool.
22    pub struct TermId / StoredTermId, "t";
23}
24
25/// The operator of a term node.
26#[derive(Debug, Clone, PartialEq, Eq, Hash)]
27pub enum TermOp<O: DenseId, V: DenseId> {
28    /// An e-graph operator (from the original e-graph).
29    EGraph(O),
30    /// A literal value.
31    Literal(O, V),
32    /// A `Variants(left, right)` node: where left and right differ.
33    Variants,
34}
35
36/// Hash-consed term pool. Structurally equal terms get the same term id.
37/// All fields are semi-persistent (AppendOnlyVec/SpMap); mark/restore truncates.
38/// The id family `A` defaults to the 31-bit family; a Config64 session
39/// instantiates `TermPool<O, V, AuIds64>` through `Cfg::Au`.
40///
41/// Every pool here is addressed by an id whose `Index` is `A::Index`, so that word —
42/// not `usize` — is the index type: the five term-indexed columns are addressed by
43/// `A::Term`, `child_pool` by `A::TermChild`, and `by_structure`'s log positions are
44/// what `A::Term`s are minted from. Pinning them keeps each saved frame length and
45/// each hash-index value at the configured width instead of 8 bytes.
46pub struct TermPool<O: DenseId, V: DenseId, A: AuIds = AuIds31> {
47    ops: AppendOnlyVec<TermOp<O, V>, A::Index>,
48    child_spans: AppendOnlyVec<Span<A::TermChild>, A::Index>,
49    child_pool: AppendOnlyVec<A::Term, A::Index>,
50    sizes: AppendOnlyVec<u32, A::Index>,
51    vmasses: AppendOnlyVec<u32, A::Index>,
52    by_structure: SpMap<(TermOp<O, V>, Vec<A::Term>), A::Term, A::Index>,
53    /// Memoized [`build_best_term`] result per snapshot class.
54    ///
55    /// A class's minimal member is fixed by the snapshot, so its extracted term
56    /// is a pure function of the class id; caching it makes `build_best_term`
57    /// amortized O(1) per class after the first build instead of re-walking the
58    /// member tree on every call (quadratic on deep chains). The cache lives in
59    /// the same semi-persistent storage as the term columns and is truncated by
60    /// the same token bundle, so a surviving entry always names a surviving
61    /// term: the entry was appended after its term was interned, and restore
62    /// truncates both logs at the same mark.
63    ///
64    /// Class ids are snapshot-relative, so the cache assumes every
65    /// `build_best_term` call on this pool uses the same snapshot. That holds
66    /// by construction: every pool is created next to one snapshot
67    /// (`session.rs`, `exact.rs`, `mcgs.rs`) and never outlives it.
68    best_terms: SpMap<A::Class, A::Term, A::Index>,
69}
70
71/// Token for restoring a `TermPool` to a previous state.
72#[derive(Clone, Copy, Debug)]
73pub struct TermPoolToken {
74    ops: VecToken,
75    child_spans: VecToken,
76    child_pool: VecToken,
77    sizes: VecToken,
78    vmasses: VecToken,
79    by_structure: MapToken,
80    best_terms: MapToken,
81}
82
83impl<O: DenseId + core::hash::Hash, V: DenseId + core::hash::Hash, A: AuIds> TermPool<O, V, A> {
84    pub fn new() -> Self {
85        TermPool {
86            ops: AppendOnlyVec::new(),
87            child_spans: AppendOnlyVec::new(),
88            child_pool: AppendOnlyVec::new(),
89            sizes: AppendOnlyVec::new(),
90            vmasses: AppendOnlyVec::new(),
91            by_structure: SpMap::new(),
92            best_terms: SpMap::new(),
93        }
94    }
95
96    /// Number of interned terms, in the configured index word.
97    ///
98    /// A term count is a position count — the next term interns at exactly this
99    /// index — so it is reported in `A::Index` rather than widened to `usize`.
100    pub fn len(&self) -> A::Index {
101        self.ops.len()
102    }
103
104    pub fn is_empty(&self) -> bool {
105        self.ops.is_empty()
106    }
107
108    /// Intern a term. Returns the existing id if structurally equal term exists.
109    pub fn intern(&mut self, op: TermOp<O, V>, children: &[A::Term]) -> A::Term {
110        let key = (op.clone(), children.to_vec());
111        if let Some(log_idx) = self.by_structure.id_of(&key) {
112            return *self.by_structure.get_val(log_idx);
113        }
114
115        let id: A::Term = crate::id::id_at_index(self.ops.len());
116        let start = self.child_pool.len().as_usize();
117        for &c in children {
118            self.child_pool
119                .try_push(c)
120                .expect("AU arena sized by its index word");
121        }
122
123        // Expanded sizes saturate. They do not wrap, and they do not panic.
124        //
125        // A term is a hash-consed DAG, so the *expanded* size these fields count is
126        // exponential in the DAG's depth: a chain of 32 binary nodes already names
127        // 2^32 leaves out of 33 stored rows. `u32` is therefore reachable from a
128        // pool small enough to build, and no wider word makes it unreachable — `u64`
129        // only moves the chain to depth 64. The width is a storage choice; the
130        // arithmetic has to be total either way.
131        //
132        // Saturation rather than a panic because these two fields are read only as
133        // the `quality` ranking key, where lower is better. A term too large to
134        // count belongs at the *worst* end of that order, which is exactly where
135        // `u32::MAX` puts it; two such terms tie, and a tie between candidates
136        // nobody can materialize costs nothing. Wrapping put them at the *best*
137        // end — a 2^32-node generalization scored 0 and was selected as the minimal
138        // one. That was silent: `Iterator::sum` on `u32` panics in debug and wraps
139        // in release, so it only ever misbehaved in the configuration that ships.
140        //
141        // `AuSnapshot::best_size` takes the same view from the other side: it
142        // reserves `u32::MAX` as an explicit "no finite representative" sentinel and
143        // rejects any total that reaches it (`egraph_api.rs`).
144        let child_size_sum = children.iter().fold(0u32, |acc, &c| {
145            acc.saturating_add(*self.sizes.get(c.to_index()))
146        });
147        let (size, vmass) = match &op {
148            TermOp::Variants => (child_size_sum, child_size_sum),
149            _ => {
150                let vm = children.iter().fold(0u32, |acc, &c| {
151                    acc.saturating_add(*self.vmasses.get(c.to_index()))
152                });
153                (child_size_sum.saturating_add(1), vm)
154            }
155        };
156
157        self.ops
158            .try_push(op)
159            .expect("AU arena sized by its index word");
160        self.child_spans
161            .try_push(Span::new(start, children.len()))
162            .expect("AU arena sized by its index word");
163        self.sizes
164            .try_push(size)
165            .expect("AU arena sized by its index word");
166        self.vmasses
167            .try_push(vmass)
168            .expect("AU arena sized by its index word");
169        self.by_structure
170            .try_insert(key, id)
171            .expect("AU arena sized by its index word");
172        id
173    }
174
175    /// Intern the result term of one action.
176    ///
177    /// `commutative` MUST be true exactly for operators whose canonical node kind is
178    /// commutative (SPair, MSet, Set): their children are sorted into canonical
179    /// structural order. For ordered operators (Plain*, Seq) it MUST be false: the
180    /// pair order of the action is positional semantics and is preserved verbatim.
181    ///
182    /// Counts arrive at the *surface* width. Two callers feed this: the structural path,
183    /// whose counts are [`EGraphConfig::M`] multiplicities, and the transport path, whose
184    /// counts are flow cells at the solver's own narrower capacity. `u64` is the one width
185    /// that holds both without a fallible conversion — [`MultiplicityLike::to_u64`] is
186    /// total and lossless at every configured width — and the count is consumed here
187    /// rather than stored, so the width costs nothing beyond the call.
188    ///
189    /// [`EGraphConfig::M`]: crate::config::EGraphConfig::M
190    /// [`MultiplicityLike::to_u64`]: crate::multiplicity::MultiplicityLike::to_u64
191    pub fn intern_action_result(
192        &mut self,
193        op: TermOp<O, V>,
194        children_with_counts: &[(A::Term, u64)],
195        commutative: bool,
196    ) -> A::Term {
197        // Expand counts into repeated children.
198        let mut expanded: Vec<A::Term> = Vec::new();
199        for &(child, count) in children_with_counts {
200            for _ in 0..count {
201                expanded.push(child);
202            }
203        }
204        if commutative {
205            // Canonical structural order: allocation-independent, so the same
206            // semantic result interns identically regardless of construction order.
207            expanded.sort_by(|&a, &b| self.structural_cmp(a, b));
208        }
209        self.intern(op, &expanded)
210    }
211
212    /// Total structural order on terms, independent of allocation order:
213    /// operator variant rank, then operator/value ids, then arity, then children
214    /// lexicographically. Equal ids are structurally equal (hash-consing), so this
215    /// returns `Equal` only for identical ids.
216    ///
217    /// Iterative (explicit work stack): the first non-`Equal` comparison in
218    /// depth-first, left-to-right order decides, exactly like the recursive
219    /// lexicographic definition. Depth is heap-bounded, not call-stack-bounded.
220    pub fn structural_cmp(&self, a: A::Term, b: A::Term) -> core::cmp::Ordering {
221        use core::cmp::Ordering;
222        fn rank<O: DenseId, V: DenseId>(op: &TermOp<O, V>) -> u8 {
223            match op {
224                TermOp::EGraph(_) => 0,
225                TermOp::Literal(_, _) => 1,
226                TermOp::Variants => 2,
227            }
228        }
229        let mut stack: Vec<(A::Term, A::Term)> = vec![(a, b)];
230        while let Some((a, b)) = stack.pop() {
231            if a == b {
232                continue;
233            }
234            let (oa, ob) = (self.op(a), self.op(b));
235            let ord = rank(oa).cmp(&rank(ob));
236            if ord != Ordering::Equal {
237                return ord;
238            }
239            let ord = match (oa, ob) {
240                (TermOp::EGraph(x), TermOp::EGraph(y)) => x.to_usize().cmp(&y.to_usize()),
241                (TermOp::Literal(x, v), TermOp::Literal(y, w)) => x
242                    .to_usize()
243                    .cmp(&y.to_usize())
244                    .then(v.to_usize().cmp(&w.to_usize())),
245                _ => Ordering::Equal,
246            };
247            if ord != Ordering::Equal {
248                return ord;
249            }
250            let (ca, cb) = (self.children(a), self.children(b));
251            let ord = ca.len().cmp(&cb.len());
252            if ord != Ordering::Equal {
253                return ord;
254            }
255            // Push child pairs in reverse so the leftmost pair is compared first.
256            for (&x, &y) in ca.iter().zip(cb.iter()).rev() {
257                stack.push((x, y));
258            }
259        }
260        Ordering::Equal
261    }
262
263    /// Get the size of a term. Saturates at `u32::MAX` for terms whose expanded
264    /// size exceeds the counter (see `intern`); such a term is ranked worst, never
265    /// best.
266    #[inline]
267    pub fn size(&self, id: A::Term) -> u32 {
268        *self.sizes.get(id.to_index())
269    }
270
271    /// Get the variant mass of a term: concrete nodes under `Variants` nodes.
272    /// `size - variant_mass` is the backbone (shared structure) size.
273    #[inline]
274    pub fn variant_mass(&self, id: A::Term) -> u32 {
275        *self.vmasses.get(id.to_index())
276    }
277
278    /// The lexicographic quality key `(size, variant_mass)`. Lower is better:
279    /// primary objective is minimum size; at equal size the term with less
280    /// variant mass has more backbone (more factored structure) and wins.
281    ///
282    /// Both components saturate (`intern`), so the order is total and monotone but
283    /// loses discrimination among terms too large to count — they all tie at the
284    /// bottom. That is the intended degradation: the alternative, wrapping, inverted
285    /// the comparison and made the largest term look like the best one.
286    #[inline]
287    pub fn quality(&self, id: A::Term) -> (u32, u32) {
288        (
289            *self.sizes.get(id.to_index()),
290            *self.vmasses.get(id.to_index()),
291        )
292    }
293
294    /// Get the operator of a term.
295    #[inline]
296    pub fn op(&self, id: A::Term) -> &TermOp<O, V> {
297        self.ops.get(id.to_index())
298    }
299
300    /// Get the children of a term.
301    #[inline]
302    pub fn children(&self, id: A::Term) -> &[A::Term] {
303        let span = *self.child_spans.get(id.to_index());
304        let (start, len) = (span.start_usize(), span.len_usize());
305        // Verified `as_slice()` instead of `from_raw_parts` — see the counterpart in
306        // `space.rs::ContextStore::get`. The children of a term are pushed
307        // consecutively when it is interned, so the span is in bounds.
308        &self.child_pool.as_slice()[start..start + len]
309    }
310
311    /// The memoized minimal term for a snapshot class, if one was built since
312    /// the last surviving mark (see `best_terms`).
313    #[inline]
314    fn cached_best_term(&self, class: A::Class) -> Option<A::Term> {
315        self.best_terms.get_by_key(&class).copied()
316    }
317
318    /// Record the minimal term extracted for a snapshot class. Callers check
319    /// the cache first, so a key is never overwritten (no shadow log entries).
320    fn cache_best_term(&mut self, class: A::Class, term: A::Term) {
321        debug_assert!(
322            self.best_terms.id_of(&class).is_none(),
323            "best-term cache entries are written at most once per class"
324        );
325        self.best_terms
326            .try_insert(class, term)
327            .expect("AU arena sized by its index word");
328    }
329
330    pub fn mark(&mut self) -> TermPoolToken {
331        TermPoolToken {
332            ops: self
333                .ops
334                .try_mark(ShrinkPolicy::Never)
335                .expect("mark: depth bounded by the search driver"),
336            child_spans: self
337                .child_spans
338                .try_mark(ShrinkPolicy::Never)
339                .expect("mark: depth bounded by the search driver"),
340            child_pool: self
341                .child_pool
342                .try_mark(ShrinkPolicy::Never)
343                .expect("mark: depth bounded by the search driver"),
344            sizes: self
345                .sizes
346                .try_mark(ShrinkPolicy::Never)
347                .expect("mark: depth bounded by the search driver"),
348            vmasses: self
349                .vmasses
350                .try_mark(ShrinkPolicy::Never)
351                .expect("mark: depth bounded by the search driver"),
352            by_structure: self
353                .by_structure
354                .try_mark(ShrinkPolicy::Never)
355                .expect("mark: depth bounded by the search driver"),
356            best_terms: self
357                .best_terms
358                .try_mark(ShrinkPolicy::Never)
359                .expect("mark: depth bounded by the search driver"),
360        }
361    }
362
363    /// Is this token restorable right now (same instances, live branches on
364    /// every inner container)?
365    pub fn is_valid_token(&self, token: &TermPoolToken) -> bool {
366        self.ops.is_valid_token(&token.ops)
367            && self.child_spans.is_valid_token(&token.child_spans)
368            && self.child_pool.is_valid_token(&token.child_pool)
369            && self.sizes.is_valid_token(&token.sizes)
370            && self.vmasses.is_valid_token(&token.vmasses)
371            && self.by_structure.is_valid_token(&token.by_structure)
372            && self.best_terms.is_valid_token(&token.best_terms)
373    }
374
375    pub fn restore(&mut self, token: TermPoolToken) {
376        self.best_terms
377            .try_restore(token.best_terms)
378            .expect("restore: token minted by this container's own mark");
379        self.by_structure
380            .try_restore(token.by_structure)
381            .expect("restore: token minted by this container's own mark");
382        self.vmasses
383            .try_restore(token.vmasses)
384            .expect("restore: token minted by this container's own mark");
385        self.sizes
386            .try_restore(token.sizes)
387            .expect("restore: token minted by this container's own mark");
388        self.child_pool
389            .try_restore(token.child_pool)
390            .expect("restore: token minted by this container's own mark");
391        self.child_spans
392            .try_restore(token.child_spans)
393            .expect("restore: token minted by this container's own mark");
394        self.ops
395            .try_restore(token.ops)
396            .expect("restore: token minted by this container's own mark");
397    }
398
399    /// Project one side of the anti-unifier: replace every `Variants` node —
400    /// at any depth — by its left (side 0) or right (side 1) child, recursively.
401    /// The result contains no `Variants` node (§1: variant projection must land
402    /// in the source class). New nodes may be interned for rebuilt spines.
403    ///
404    /// Iterative post-order fold (explicit frame stack): each frame projects
405    /// its children left to right, then re-interns only if a child changed, so
406    /// the interning order matches the recursive definition exactly. A
407    /// `Variants` node is a tail step (follow the chosen arm), so it never
408    /// occupies a frame. Depth is heap-bounded, not call-stack-bounded.
409    pub fn project(&mut self, id: A::Term, side: usize) -> A::Term {
410        debug_assert!(side < 2);
411        struct Frame<T, Op> {
412            id: T,
413            op: Op,
414            children: Vec<T>,
415            cursor: usize,
416            new_children: Vec<T>,
417            changed: bool,
418        }
419        let mut stack: Vec<Frame<A::Term, TermOp<O, V>>> = Vec::new();
420        let mut pending = id;
421        loop {
422            // Enter: resolve the Variants chain (tail steps), push a frame.
423            let mut nid = pending;
424            while matches!(self.op(nid), TermOp::Variants) {
425                nid = self.children(nid)[side];
426            }
427            let children = self.children(nid).to_vec();
428            let capacity = children.len();
429            stack.push(Frame {
430                id: nid,
431                op: self.op(nid).clone(),
432                children,
433                cursor: 0,
434                new_children: Vec::with_capacity(capacity),
435                changed: false,
436            });
437            // Advance the top frame; complete frames deliver upward.
438            loop {
439                let top = stack.last_mut().expect("project stack cannot be empty");
440                if top.cursor < top.children.len() {
441                    pending = top.children[top.cursor];
442                    break; // descend into the next child
443                }
444                let frame = stack.pop().expect("project stack cannot be empty");
445                let projected = if frame.changed {
446                    self.intern(frame.op, &frame.new_children)
447                } else {
448                    frame.id
449                };
450                let Some(parent) = stack.last_mut() else {
451                    return projected;
452                };
453                let original = parent.children[parent.cursor];
454                parent.changed |= projected != original;
455                parent.new_children.push(projected);
456                parent.cursor += 1;
457            }
458        }
459    }
460
461    /// Does this term contain any `Variants` node (at any depth)?
462    /// Iterative DFS with an explicit stack; depth is heap-bounded.
463    pub fn has_variants(&self, id: A::Term) -> bool {
464        let mut stack: Vec<A::Term> = vec![id];
465        while let Some(t) = stack.pop() {
466            if matches!(self.op(t), TermOp::Variants) {
467                return true;
468            }
469            stack.extend_from_slice(self.children(t));
470        }
471        false
472    }
473}
474
475impl<O: DenseId + core::hash::Hash, V: DenseId + core::hash::Hash> Default for TermPool<O, V> {
476    fn default() -> Self {
477        Self::new()
478    }
479}
480
481impl<O: DenseId, V: DenseId> core::fmt::Debug for TermPool<O, V> {
482    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
483        f.debug_struct("TermPool")
484            .field("len", &self.ops.len())
485            .finish()
486    }
487}
488
489/// Evaluate the shared terminal generalize action for a class pair.
490///
491/// Equal classes yield their smallest concrete representative. Unequal classes
492/// yield `Variants(best_term(l), best_term(r))` without recursively factoring
493/// either representative; operator-aware factoring belongs to structural
494/// actions shared by Exact and UCT.
495pub(crate) fn evaluate_generalize_action<
496    Cfg: EGraphConfig,
497    L: LitVal,
498    const T: bool,
499    const P: bool,
500>(
501    snap: &AuSnapshot<Cfg, L, T, P>,
502    pool: &mut TermPool<Cfg::O, Cfg::V, Cfg::Au>,
503    l: ClassOf<Cfg>,
504    r: ClassOf<Cfg>,
505) -> <Cfg::Au as AuIds>::Term
506where
507    MSetCanon: VarCanon<Cfg::G, Cfg::C>,
508{
509    if l == r {
510        return build_best_term(snap, pool, l);
511    }
512    let l_term = build_best_term(snap, pool, l);
513    let r_term = build_best_term(snap, pool, r);
514    pool.intern(TermOp::Variants, &[l_term, r_term])
515}
516
517/// Build the best (smallest) concrete term for a class, interned in the pool.
518///
519/// Iterative post-order fold (explicit frame stack): each frame resolves its
520/// class's best node, evaluates child classes left to right (in
521/// `for_each_child` order, repeating AC children per multiplicity), then
522/// interns — the same interning order as the recursive definition. Depth is
523/// heap-bounded, not call-stack-bounded.
524///
525/// Memoized per class in the pool: the result is a pure
526/// function of `(snap, class)` and the pool binds to one snapshot, so a
527/// completed class's term is cached and later builds return it without
528/// re-walking the member tree — amortized O(1) per class after the first
529/// build. The cache changes nothing observable: interning is idempotent, so
530/// the uncached walk would re-intern the identical ids in the identical
531/// order; only the redundant walk is skipped. Restore truncates the cache
532/// with the pool's other columns, so an entry never outlives its term.
533pub fn build_best_term<Cfg: EGraphConfig, L: LitVal, const T: bool, const P: bool>(
534    snap: &AuSnapshot<Cfg, L, T, P>,
535    pool: &mut TermPool<Cfg::O, Cfg::V, Cfg::Au>,
536    class: ClassOf<Cfg>,
537) -> <Cfg::Au as AuIds>::Term
538where
539    MSetCanon: VarCanon<Cfg::G, Cfg::C>,
540{
541    struct Frame<O, C, M, Term> {
542        /// The class this frame extracts, cached when the frame completes.
543        class: C,
544        op: O,
545        /// Child classes with multiplicities, in `for_each_child` order.
546        child_classes: Vec<(C, M)>,
547        cursor: usize,
548        children: Vec<Term>,
549    }
550    let eg = snap.egraph();
551    let mut stack: Vec<Frame<Cfg::O, ClassOf<Cfg>, Cfg::M, <Cfg::Au as AuIds>::Term>> = Vec::new();
552    let mut pending = class;
553    loop {
554        // Enter: cached classes complete immediately, as do literals; other
555        // nodes resolve the class's best node and get a frame.
556        let mut done: Option<<Cfg::Au as AuIds>::Term> = None;
557        if let Some(term) = pool.cached_best_term(pending) {
558            done = Some(term);
559        } else {
560            let best_id = snap.best_node(pending);
561            let op = eg.node_op(best_id);
562            if let Some(val_id) = eg.get_lit_val_id(best_id) {
563                let term = pool.intern(TermOp::Literal(op, val_id), &[]);
564                pool.cache_best_term(pending, term);
565                done = Some(term);
566            } else {
567                let mut child_classes: Vec<(ClassOf<Cfg>, Cfg::M)> = Vec::new();
568                eg.for_each_child(best_id, |child, mult| {
569                    child_classes.push((snap.class_of(child).unwrap(), mult));
570                });
571                stack.push(Frame {
572                    class: pending,
573                    op,
574                    child_classes,
575                    cursor: 0,
576                    children: Vec::new(),
577                });
578            }
579        }
580        // Advance: deliver any completed term upward, then descend or compose.
581        loop {
582            if let Some(term) = done.take() {
583                let Some(parent) = stack.last_mut() else {
584                    return term;
585                };
586                let (_, mult) = parent.child_classes[parent.cursor];
587                for _ in 0..mult.to_usize() {
588                    parent.children.push(term);
589                }
590                parent.cursor += 1;
591            }
592            let top = stack
593                .last_mut()
594                .expect("build_best_term stack cannot be empty");
595            if top.cursor < top.child_classes.len() {
596                pending = top.child_classes[top.cursor].0;
597                break; // descend into the next child class
598            }
599            let frame = stack.pop().expect("build_best_term stack cannot be empty");
600            let term = pool.intern(TermOp::EGraph(frame.op), &frame.children);
601            pool.cache_best_term(frame.class, term);
602            done = Some(term);
603        }
604    }
605}
606
607#[cfg(test)]
608mod tests {
609    use super::*;
610    use crate::egraph::EGraph31;
611    use crate::id::OpId;
612    use crate::literal::NiraLitVal;
613
614    #[test]
615    fn term_pool_dedup() {
616        let mut pool = TermPool::<OpId, crate::id::ENodeId>::new();
617        let op = OpId::from_usize(0);
618
619        let leaf = pool.intern(TermOp::EGraph(op), &[]);
620        let leaf2 = pool.intern(TermOp::EGraph(op), &[]);
621        assert_eq!(leaf, leaf2);
622        assert_eq!(pool.size(leaf), 1);
623    }
624
625    #[test]
626    fn term_size_variants_zero() {
627        let mut pool = TermPool::<OpId, crate::id::ENodeId>::new();
628        let op = OpId::from_usize(0);
629
630        let left = pool.intern(TermOp::EGraph(op), &[]);
631        let right = pool.intern(TermOp::EGraph(OpId::from_usize(1)), &[]);
632        let variants = pool.intern(TermOp::Variants, &[left, right]);
633
634        // Variants costs 0, children cost 1 each.
635        assert_eq!(pool.size(variants), 2);
636    }
637
638    #[test]
639    fn generalize_action_identical_class_returns_best_term() {
640        let mut eg = EGraph31::<NiraLitVal, false, false>::new();
641        let int = eg.intern_sort("Int");
642        let a_op = eg.register_op0("a", int);
643        let a = eg.add(a_op, &[]);
644        eg.rebuild();
645
646        let snap = AuSnapshot::new(&eg).unwrap();
647        let ac = snap.class_of(a).unwrap();
648
649        let mut pool = TermPool::new();
650        let result = evaluate_generalize_action(&snap, &mut pool, ac, ac);
651        assert_eq!(pool.size(result), 1);
652        assert_eq!(*pool.op(result), TermOp::EGraph(a_op));
653    }
654
655    #[test]
656    fn generalize_action_unequal_classes_returns_best_term_variants() {
657        let mut eg = EGraph31::<NiraLitVal, false, false>::new();
658        let int = eg.intern_sort("Int");
659        let a_op = eg.register_op0("a", int);
660        let b_op = eg.register_op0("b", int);
661        let a = eg.add(a_op, &[]);
662        let b = eg.add(b_op, &[]);
663        eg.rebuild();
664
665        let snap = AuSnapshot::new(&eg).unwrap();
666        let ac = snap.class_of(a).unwrap();
667        let bc = snap.class_of(b).unwrap();
668
669        let mut pool = TermPool::new();
670        let result = evaluate_generalize_action(&snap, &mut pool, ac, bc);
671        // Variants(a, b) -> size 2 (1+1, Variants itself costs 0).
672        assert_eq!(pool.size(result), 2);
673        assert_eq!(*pool.op(result), TermOp::Variants);
674        assert_eq!(pool.children(result).len(), 2);
675    }
676
677    /// P1 regression: projection must descend below ordinary operators.
678    /// project(f(a, Variants(b,c)), 0) = f(a, b); side 1 = f(a, c).
679    #[test]
680    fn projection_is_deep() {
681        let mut pool = TermPool::<OpId, crate::id::ENodeId>::new();
682        let f = OpId::from_usize(0);
683        let a = pool.intern(TermOp::EGraph(OpId::from_usize(1)), &[]);
684        let b = pool.intern(TermOp::EGraph(OpId::from_usize(2)), &[]);
685        let c = pool.intern(TermOp::EGraph(OpId::from_usize(3)), &[]);
686        let v = pool.intern(TermOp::Variants, &[b, c]);
687        let root = pool.intern(TermOp::EGraph(f), &[a, v]);
688
689        let left = pool.project(root, 0);
690        let right = pool.project(root, 1);
691
692        assert!(!pool.has_variants(left));
693        assert!(!pool.has_variants(right));
694        assert_eq!(pool.children(left), &[a, b]);
695        assert_eq!(pool.children(right), &[a, c]);
696
697        // Nested Variants inside a chosen arm are resolved too.
698        let v2 = pool.intern(TermOp::Variants, &[v, a]);
699        let root2 = pool.intern(TermOp::EGraph(f), &[v2, a]);
700        let l2 = pool.project(root2, 0);
701        assert!(!pool.has_variants(l2));
702        assert_eq!(pool.children(l2), &[b, a]);
703    }
704
705    /// P0 regression: ordered operators preserve positional child order even
706    /// when the positional order disagrees with TermId order.
707    #[test]
708    fn ordered_children_not_sorted() {
709        let mut pool = TermPool::<OpId, crate::id::ENodeId>::new();
710        let f = OpId::from_usize(0);
711        // Allocate `b` FIRST so its TermId sorts before the Variants node.
712        let b = pool.intern(TermOp::EGraph(OpId::from_usize(2)), &[]);
713        let a = pool.intern(TermOp::EGraph(OpId::from_usize(1)), &[]);
714        let c = pool.intern(TermOp::EGraph(OpId::from_usize(3)), &[]);
715        let v = pool.intern(TermOp::Variants, &[a, c]);
716
717        // Ordered: f(Variants(a,c), b) must keep the Variants first.
718        let ordered = pool.intern_action_result(TermOp::EGraph(f), &[(v, 1), (b, 1)], false);
719        assert_eq!(pool.children(ordered), &[v, b]);
720
721        // Commutative: children are sorted structurally (EGraph ops rank before
722        // Variants), independent of allocation order.
723        let comm = pool.intern_action_result(TermOp::EGraph(f), &[(v, 1), (b, 1)], true);
724        assert_eq!(pool.children(comm), &[b, v]);
725    }
726
727    /// Variant mass: backbone nodes are excluded; everything under Variants counts.
728    #[test]
729    fn variant_mass_arithmetic() {
730        let mut pool = TermPool::<OpId, crate::id::ENodeId>::new();
731        let f = OpId::from_usize(0);
732        let x = pool.intern(TermOp::EGraph(OpId::from_usize(1)), &[]);
733        let y = pool.intern(TermOp::EGraph(OpId::from_usize(2)), &[]);
734        let fy = pool.intern(TermOp::EGraph(f), &[y]);
735
736        // Variants(x, f(y)): size 3, all variant mass.
737        let bare = pool.intern(TermOp::Variants, &[x, fy]);
738        assert_eq!(pool.quality(bare), (3, 3));
739
740        // f(Variants(x, y)): size 3, variant mass 2 — one backbone node.
741        let v = pool.intern(TermOp::Variants, &[x, y]);
742        let factored = pool.intern(TermOp::EGraph(f), &[v]);
743        assert_eq!(pool.quality(factored), (3, 2));
744
745        // The factored form is strictly better in the lexicographic order.
746        assert!(pool.quality(factored) < pool.quality(bare));
747    }
748
749    /// A term whose expanded size passes `u32` saturates and stays the *worst*
750    /// candidate. 33 stored rows are enough to name 2^32 leaves, so this is not a
751    /// hypothetical width: it is what wrapping arithmetic looked like in release,
752    /// where the giant term scored 0 and beat every real generalization.
753    #[test]
754    fn expanded_size_saturates_and_ranks_worst() {
755        let mut pool = TermPool::<OpId, crate::id::ENodeId>::new();
756        let x = pool.intern(TermOp::EGraph(OpId::from_usize(0)), &[]);
757        assert_eq!(pool.size(x), 1);
758
759        // Each level doubles: `size(v_k) == 2^k`, so `v_32` would be 2^32.
760        let mut v = x;
761        for level in 1..=31u32 {
762            v = pool.intern(TermOp::Variants, &[v, v]);
763            assert_eq!(pool.size(v), 1u32 << level, "level {level} is exact");
764        }
765
766        let over = pool.intern(TermOp::Variants, &[v, v]);
767        assert_eq!(pool.size(over), u32::MAX);
768        assert_eq!(pool.variant_mass(over), u32::MAX);
769
770        // Saturated, so it ranks below the largest exactly-counted term — and below
771        // the leaf. Wrapping would have made it `(0, 0)`: the best score possible.
772        assert!(pool.quality(v) < pool.quality(over));
773        assert!(pool.quality(x) < pool.quality(over));
774
775        // A backbone node above a saturated child stays saturated (`1 + MAX`).
776        let wrapped = pool.intern(TermOp::EGraph(OpId::from_usize(1)), &[over]);
777        assert_eq!(pool.size(wrapped), u32::MAX);
778    }
779
780    #[test]
781    fn generalize_action_does_not_positionally_factor_shared_structure() {
782        let mut eg = EGraph31::<NiraLitVal, false, false>::new();
783        let int = eg.intern_sort("Int");
784        let a_op = eg.register_op0("a", int);
785        let b_op = eg.register_op0("b", int);
786        let c_op = eg.register_op0("c", int);
787        let f_op = eg.register_op2("f", int, int, int);
788
789        let a = eg.add(a_op, &[]);
790        let b = eg.add(b_op, &[]);
791        let c = eg.add(c_op, &[]);
792        let fab = eg.add(f_op, &[a, b]);
793        let fac = eg.add(f_op, &[a, c]);
794        eg.rebuild();
795
796        let snap = AuSnapshot::new(&eg).unwrap();
797        let lc = snap.class_of(fab).unwrap();
798        let rc = snap.class_of(fac).unwrap();
799
800        let mut pool = TermPool::new();
801        let result = evaluate_generalize_action(&snap, &mut pool, lc, rc);
802        // The terminal base action is whole-term generalization, not a
803        // positional zipper: Variants(f(a,b), f(a,c)) has size 3 + 3 = 6.
804        assert_eq!(pool.size(result), 6);
805        assert_eq!(*pool.op(result), TermOp::Variants);
806        let arms = pool.children(result);
807        assert_eq!(arms.len(), 2);
808        assert_eq!(*pool.op(arms[0]), TermOp::EGraph(f_op));
809        assert_eq!(*pool.op(arms[1]), TermOp::EGraph(f_op));
810    }
811
812    /// The best-term cache must be truncated by restore
813    /// exactly like the term columns, so a cache entry never names a truncated
814    /// term id. Build (pre-mark entries), mark, build more (post-mark entries),
815    /// restore, then re-build both classes: the pre-mark class must return its
816    /// surviving id without growing the pool, and the post-mark class must be
817    /// rebuilt from scratch into an in-bounds id — identical to the pre-restore
818    /// build, because the replayed interning order is identical.
819    #[test]
820    fn best_term_cache_is_truncated_by_restore() {
821        let mut eg = EGraph31::<NiraLitVal, false, false>::new();
822        let sort = eg.intern_sort("E");
823        let a_op = eg.register_op0("a", sort);
824        let f_op = eg.register_op1("f", sort, sort);
825        let g_op = eg.register_op1("g", sort, sort);
826        let a = eg.add(a_op, &[]);
827        let fa = eg.add(f_op, &[a]);
828        let gfa = eg.add(g_op, &[fa]);
829        eg.rebuild();
830
831        let snap = AuSnapshot::new(&eg).unwrap();
832        let fa_class = snap.class_of(fa).unwrap();
833        let gfa_class = snap.class_of(gfa).unwrap();
834
835        let mut pool = TermPool::new();
836        let t_fa = build_best_term(&snap, &mut pool, fa_class);
837        assert_eq!(pool.size(t_fa), 2);
838
839        let len_at_mark = pool.len();
840        let token = pool.mark();
841
842        // Post-mark: caches the gfa class and interns the g term.
843        let t_gfa = build_best_term(&snap, &mut pool, gfa_class);
844        assert_eq!(pool.size(t_gfa), 3);
845        assert_eq!(pool.children(t_gfa), &[t_fa]);
846        assert!(pool.len() > len_at_mark);
847
848        pool.restore(token);
849        assert_eq!(pool.len(), len_at_mark);
850
851        // Pre-mark entry survives: cache hit on the surviving id, no growth.
852        let t_fa2 = build_best_term(&snap, &mut pool, fa_class);
853        assert_eq!(t_fa2, t_fa);
854        assert_eq!(pool.len(), len_at_mark);
855
856        // Post-mark entry is gone: the class rebuilds from scratch into an
857        // in-bounds id — numerically equal to the pre-restore build, because
858        // restore rewound the pool to the same state it was built from.
859        let t_gfa2 = build_best_term(&snap, &mut pool, gfa_class);
860        assert_eq!(t_gfa2, t_gfa);
861        assert!(t_gfa2.to_usize() < pool.len().as_usize());
862        assert_eq!(pool.size(t_gfa2), 3);
863        assert_eq!(*pool.op(t_gfa2), TermOp::EGraph(g_op));
864        assert_eq!(pool.children(t_gfa2), &[t_fa]);
865    }
866}