Skip to main content

semi_persistent_egraph/
egraph.rs

1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// SPDX-License-Identifier: Apache-2.0
3//! The semi-persistent e-graph: add, merge, find, rebuild, mark, restore.
4
5use crate::canon::{MSetCanon, MSetClamp, VarCanon};
6use crate::classes::EClasses;
7use crate::config::EGraphConfig;
8use crate::containers::DenseId;
9use crate::containers::IndexLike;
10use crate::containers::ShrinkPolicy;
11use crate::literal::{LitVal, LitValStore, LitValStoreToken};
12use crate::multiplicity::MultiplicityLike;
13use crate::node_store::{Added, NodeStore, NodeStoreToken};
14use crate::registry::{
15    AxiomRegistry, AxiomRegistryToken, OpKind, OpRegistry, OpRegistryToken, RuleRegistry,
16    RuleRegistryToken, SortRegistry, SortRegistryToken,
17};
18use crate::typed_routing::NodeRef;
19use crate::union_find::{Justification, ProofBuf};
20
21/// How a completion op's monomial counts are bounded during normalization (design "three
22/// independent axes"): unbounded ℕ (MSet plain AC), clamped to {0,1} by dedup (Set idempotent =
23/// ACI), or reduced mod `order` (nilpotent, e.g. XOR at order 2 — stored MSet, the clamp is the
24/// algebra axis, not the storage axis). Selects the normalize/reduct
25/// reduction in `cc_round`.
26#[derive(Clone, Copy, Debug, PartialEq, Eq)]
27pub(crate) enum CompletionClamp {
28    Multiset,
29    Idempotent,
30    Nilpotent { order: u8 },
31}
32
33#[derive(Clone, Copy, Debug)]
34pub struct EGraphToken {
35    classes: crate::classes::EClassesToken,
36    nodes: NodeStoreToken,
37    sorts: SortRegistryToken,
38    ops: OpRegistryToken,
39    rules: RuleRegistryToken,
40    axioms: AxiomRegistryToken,
41    lits: LitValStoreToken,
42    unit_node: crate::containers::MapToken,
43    inverse_op: crate::containers::MapToken,
44    /// The completion outcome at mark time. `mark()` rebuilds first, so this value
45    /// describes exactly the state being snapshotted; `restore` puts it back so a caller
46    /// can never observe an outcome from a discarded scope.
47    completion_outcome: Option<CompletionOutcome>,
48}
49
50pub struct EGraph<
51    Cfg: EGraphConfig,
52    L: LitVal,
53    const TRACK: bool = true,
54    const PROOFS: bool = false,
55> {
56    sorts: SortRegistry<Cfg::S, TRACK>,
57    ops: OpRegistry<Cfg::O, Cfg::S, TRACK>,
58    rules: RuleRegistry<TRACK>,
59    axioms: AxiomRegistry<Cfg::G, TRACK>,
60    lits: LitValStore<L, Cfg::V, TRACK>,
61    classes: EClasses<Cfg::G, Cfg::ClassKey, Cfg::UL, Cfg::UN, TRACK, PROOFS>,
62    nodes: NodeStore<Cfg::G, Cfg::O, Cfg::V, Cfg::C, Cfg::Ids, TRACK, PROOFS>,
63    worklist: Vec<(Cfg::UL, Cfg::G)>,
64    collisions: Vec<(Cfg::G, Cfg::G)>,
65    /// Reusable scratch for a node's child ids as bare `G` (the canonical-children buffer for
66    /// every representation except MSet). Paired with `mset_buf`, which holds the MSet variant.
67    g_buf: Vec<Cfg::G>,
68    /// Reusable scratch for MSet children, child type `C` = `(G, mult)` (the multiset
69    /// representation needs the multiplicity that bare `G` in `g_buf` cannot carry).
70    mset_buf: Vec<Cfg::C>,
71    /// Semi-naive touched log: node ids created or recanonicalized since the
72    /// last `clear_touched`. Round-local scratch (cleared on `restore`);
73    /// drives the per-round delta index. Not part of persistent state.
74    touched: Vec<Cfg::G>,
75    /// When set, every class merge also records the absorbed side's member
76    /// nodes in `touched` (see `merge_in_classes`). Only semi-naive saturation
77    /// consumes it; off everywhere else so merges pay no ring walk.
78    track_merge_members: bool,
79    /// Survivor policy for class merges (see [`UnionBy`]).
80    union_by: UnionBy,
81    /// Goal pair for goal-directed completion (the lazy-check transaction):
82    /// the completion loop polls it between passes and inside a round's apply
83    /// loops, and stops with [`CompletionOutcome::GoalMet`] as soon as the
84    /// two classes join. `None` everywhere else.
85    cc_goal: Option<(Cfg::G, Cfg::G)>,
86    /// Node count at the start of the current completion run, for the
87    /// in-round budget check (`cc_should_stop`): a single blown-up round is
88    /// stopped mid-apply instead of only between rounds.
89    cc_start_nodes: usize,
90    /// Whether `rebuild` runs the AC congruence-completion pass (superposition +
91    /// inter-reduction). **Default off** because ground AC completion is doubly
92    /// exponential in the worst case. The growth backstop is checked between rounds and
93    /// inside the apply loops, but a bounded node count does not make the algorithm cheap.
94    /// See `doc/future/ac-completion-limitations.md` section 1. Opt in with
95    /// [`set_cc`](Self::set_cc).
96    cc: bool,
97    /// Whether `rebuild` runs the AC reduced-basis invariant checks (`cc_basis_dump`:
98    /// `min_monomial` minimality, the Kapur-reduced antichain, etc., see `ac_invariants.rs`).
99    /// **Default off** and only consulted when `cc` is on: the ground-truth checks
100    /// brute-force per-class minima and multi-step normalization (superlinear), so they are
101    /// diagnostic/test-only, never on the production hot path. Seeded from the `AC_BASIS_DUMP`
102    /// env var at construction (so existing diagnostic runs keep working) and overridable via
103    /// [`set_basis_checks`](Self::set_basis_checks).
104    basis_checks: bool,
105    /// Reusable scratch for comparing two nodes' AC monomials (`monomial_cmp` on the
106    /// per-class `min_monomial`, §9a). Two buffers to hold both sides without aliasing;
107    /// cleared and refilled per comparison, never grown per merge.
108    cmp_buf_a: Vec<(Cfg::G, Cfg::M)>,
109    cmp_buf_b: Vec<(Cfg::G, Cfg::M)>,
110    /// Reusable scratch for flattening nested same-op AC children (`WF_flat`,
111    /// design §6c). Worklist of children still to expand; never grown per add.
112    flatten_buf: Vec<Cfg::G>,
113    /// Per-op identity (unit) element node, for completion ops declared with `:identity e`
114    /// (`x ∘ e = x`; the unit drops from monomials). Resolved to a real node at registration
115    /// (sortcheck has the model to parse the term and builds the node), keyed by op id. Stored
116    /// here rather than on `OpKind<S>` because a node id is `Cfg::G`, which `OpKind<S>` cannot
117    /// carry. Semi-persistent (its own token), so it rolls back with the op declarations that
118    /// created the units. Absent key = the op has no declared identity.
119    unit_node: crate::containers::SpMap<Cfg::O, Cfg::G, <Cfg::O as DenseId>::Index, TRACK>,
120    /// Per-op group inverse operator, for AC ops declared with `:inverse neg`
121    /// (`x ∘ neg(x) = e`). Resolved to a real op id at registration (sortcheck validates
122    /// the unary signature). Same persistence story as `unit_node`. Absent key = no
123    /// declared inverse. NOTE: gate-level group support — inverse-PAIR cancellation only,
124    /// not Kapur §5.4's full Abelian-group completion (no Gaussian elimination).
125    inverse_op: crate::containers::SpMap<Cfg::O, Cfg::O, <Cfg::O as DenseId>::Index, TRACK>,
126    /// Outcome of the most recent `rebuild` when `cc` is enabled. Lets callers distinguish
127    /// convergence from a growth-budget abort. `None` if completion hasn't run yet.
128    completion_outcome: Option<CompletionOutcome>,
129    /// Node-growth budget for one completion-enabled `rebuild`: if completion mints more
130    /// than this many nodes beyond where the rebuild started, it stops (sound-but-
131    /// incomplete, reported as [`CompletionOutcome::AbortedGrowthLimit`]) rather than
132    /// allowing unbounded node growth. This is NOT a termination argument or a complete
133    /// work bound; it is the resource backstop described in
134    /// `doc/future/ac-completion-limitations.md`. A config knob like
135    /// `cc`/`basis_checks`, not
136    /// semi-persistent state; default [`DEFAULT_COMPLETION_NODE_BUDGET`], overridable via
137    /// [`set_completion_node_budget`](Self::set_completion_node_budget) (tests use a tiny
138    /// budget to exercise the abort path directly).
139    completion_node_budget: usize,
140}
141
142/// Default node-growth budget for one completion-enabled `rebuild` (see
143/// [`EGraph::set_completion_node_budget`]).
144pub const DEFAULT_COMPLETION_NODE_BUDGET: usize = 50_000;
145
146/// Outcome of the AC congruence-completion pass inside `rebuild`.
147#[derive(Clone, Copy, Debug, PartialEq, Eq)]
148pub enum CompletionOutcome {
149    /// Completion was not enabled (`set_cc(false)`).
150    Disabled,
151    /// The implemented completion passes reached an unchanged full-round fixpoint.
152    ///
153    /// This is an operational stopping condition, not by itself a certificate
154    /// that the abstract AC/ACI theory is complete.
155    ///
156    /// For associative-only operators this does not claim completeness for
157    /// arbitrary asserted ground equations; that general word problem is
158    /// undecidable. See `doc/future/ac-completion-limitations.md` section 8.
159    Converged { rounds: usize },
160    /// Completion aborted because the node-growth budget was exceeded. The e-graph is
161    /// sound-but-incomplete: some AC-entailed equalities may be missing.
162    AbortedGrowthLimit { added_nodes: usize, limit: usize },
163    /// Completion stopped early because the goal pair (`set_cc_goal`) joined.
164    /// The e-graph is a valid plain-congruence-closed state; completion is
165    /// deliberately unfinished — the caller asked a question and it is
166    /// answered. Only the lazy-check transaction sets a goal.
167    GoalMet { rounds: usize },
168}
169
170/// Aggregate counts from [`EGraph::dump_all_proofs`].
171#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
172pub struct ProofDumpStats {
173    /// One proof-path record is emitted for every e-node, including representatives.
174    pub terms: usize,
175    /// Records with at least one proof edge.
176    pub nontrivial_proofs: usize,
177    /// Total proof edges written across all certificates.
178    pub steps: usize,
179}
180
181/// Survivor policy for class merges (`--union-by`). `Rank` leaves the choice
182/// to the union-find's rank heuristic (the historical default). The directed
183/// criteria absorb the cheap side, reading the verified per-class counters:
184/// `Size` compares member counts (bounds the semi-naive touched-log pushes to
185/// amortized O(n log n) — a node is absorbed at most log n times), `Uses`
186/// compares use-list lengths (bounds recanonization work the same way), and
187/// `Sum` adds the two, bounding their aggregate movement. Survivor identity is
188/// intended to be semantically irrelevant because class payloads are
189/// merge-folded (design doc §9a), and finite differential tests compare the
190/// policies. This is not an end-to-end equivalence theorem; budget-, goal-, or
191/// order-sensitive runs may follow different operational paths.
192#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
193pub enum UnionBy {
194    #[default]
195    Rank,
196    Size,
197    Uses,
198    Sum,
199}
200
201/// Shortlex order on canonical element lists: shorter first, ties broken
202/// element-wise by id. The orientation of the A-only inter-reduction rules
203/// (`a_round`); well-founded, so rewriting under it terminates.
204fn shortlex<G: crate::containers::DenseId>(a: &[G], b: &[G]) -> std::cmp::Ordering {
205    a.len().cmp(&b.len()).then_with(|| {
206        a.iter()
207            .map(|g| g.to_usize())
208            .cmp(b.iter().map(|g| g.to_usize()))
209    })
210}
211
212/// Type alias for the default 31-bit configuration.
213pub type EGraph31<L, const TRACK: bool = true, const PROOFS: bool = false> =
214    EGraph<crate::nodes::DefaultConfig, L, TRACK, PROOFS>;
215
216/// Type alias for the 63-bit configuration.
217pub type EGraph63<L, const TRACK: bool = true, const PROOFS: bool = false> =
218    EGraph<crate::nodes::Config64, L, TRACK, PROOFS>;
219
220/// Type alias for 31-bit ids with a 16-bit multiplicity ([`crate::nodes::ConfigM16`]).
221pub type EGraphM16<L, const TRACK: bool = true, const PROOFS: bool = false> =
222    EGraph<crate::nodes::ConfigM16, L, TRACK, PROOFS>;
223
224impl<Cfg: EGraphConfig, L: LitVal, const TRACK: bool, const PROOFS: bool> Default
225    for EGraph<Cfg, L, TRACK, PROOFS>
226where
227    MSetCanon: VarCanon<Cfg::G, Cfg::C>,
228{
229    fn default() -> Self {
230        Self::new()
231    }
232}
233
234impl<Cfg: EGraphConfig, L: LitVal, const TRACK: bool, const PROOFS: bool>
235    EGraph<Cfg, L, TRACK, PROOFS>
236where
237    MSetCanon: VarCanon<Cfg::G, Cfg::C>,
238{
239    pub fn new() -> Self {
240        Self {
241            sorts: SortRegistry::new(),
242            ops: OpRegistry::new(),
243            rules: RuleRegistry::new(),
244            axioms: AxiomRegistry::new(),
245            lits: LitValStore::new(),
246            classes: EClasses::new(),
247            nodes: NodeStore::new(),
248            worklist: Vec::new(),
249            collisions: Vec::new(),
250            g_buf: Vec::new(),
251            mset_buf: Vec::new(),
252            touched: Vec::new(),
253            track_merge_members: false,
254            union_by: UnionBy::Rank,
255            cc_goal: None,
256            cc_start_nodes: 0,
257            cc: false,
258            basis_checks: std::env::var_os("AC_BASIS_DUMP").is_some(),
259            cmp_buf_a: Vec::new(),
260            cmp_buf_b: Vec::new(),
261            flatten_buf: Vec::new(),
262            unit_node: crate::containers::SpMap::new(),
263            inverse_op: crate::containers::SpMap::new(),
264            completion_outcome: None,
265            completion_node_budget: DEFAULT_COMPLETION_NODE_BUDGET,
266        }
267    }
268
269    /// Outcome of the most recent `rebuild` when `cc` is enabled. `None` before the first
270    /// rebuild. Callers can use this to distinguish convergence from a growth-budget abort.
271    pub fn completion_outcome(&self) -> Option<CompletionOutcome> {
272        self.completion_outcome
273    }
274
275    /// Set the node-growth budget for one completion-enabled `rebuild` (default
276    /// [`DEFAULT_COMPLETION_NODE_BUDGET`]). Exceeding it aborts completion soundly and
277    /// records [`CompletionOutcome::AbortedGrowthLimit`]. A config knob (like
278    /// [`set_cc`](Self::set_cc)), not semi-persistent state.
279    pub fn set_completion_node_budget(&mut self, budget: usize) {
280        self.completion_node_budget = budget;
281    }
282
283    /// Enable or disable the AC congruence-completion pass in `rebuild` (default off).
284    /// See the `cc` field docs and `doc/future/ac-completion-limitations.md` §1.
285    pub fn set_cc(&mut self, enabled: bool) {
286        self.cc = enabled;
287    }
288
289    /// Select the merge survivor policy (see [`UnionBy`]).
290    pub fn set_union_by(&mut self, u: UnionBy) {
291        self.union_by = u;
292    }
293
294    /// The weight the `--union-by` criterion assigns to the class of repr `r`.
295    fn union_weight(&self, r: Cfg::G) -> usize {
296        let Some(k) = self.classes.repr_id(r) else {
297            return 0;
298        };
299        match self.union_by {
300            UnionBy::Rank => 0,
301            UnionBy::Size => self.classes.class_size(k),
302            UnionBy::Uses => self.classes.use_list_len(k),
303            UnionBy::Sum => self
304                .classes
305                .class_size(k)
306                .saturating_add(self.classes.use_list_len(k)),
307        }
308    }
309
310    /// Set or clear the completion goal pair (see the `cc_goal` field). With a
311    /// goal set, `rebuild` under completion returns
312    /// [`CompletionOutcome::GoalMet`] as soon as the pair joins, without
313    /// finishing the closure.
314    pub fn set_cc_goal(&mut self, goal: Option<(Cfg::G, Cfg::G)>) {
315        self.cc_goal = goal;
316    }
317
318    /// Goal-directed early stop for the completion loops: the goal pair
319    /// joined, or the in-round node budget is exhausted. `rebuild` sorts out
320    /// which of the two happened.
321    fn cc_should_stop(&self) -> bool {
322        if let Some((a, b)) = self.cc_goal
323            && self.classes.find_const(a) == self.classes.find_const(b)
324        {
325            return true;
326        }
327        self.node_count()
328            > self
329                .cc_start_nodes
330                .saturating_add(self.completion_node_budget)
331    }
332
333    /// Enable or disable the AC reduced-basis invariant checks in `rebuild` (default off,
334    /// seeded from the `AC_BASIS_DUMP` env var). When on (and `cc` is on), each
335    /// completion round prints `cc_basis_dump`, which runs the ground-truth checkers
336    /// (`min_monomial` minimality, Kapur-reducedness). These are superlinear brute-force checks,
337    /// so leave this off outside diagnosis and tests. See `ac_invariants.rs`.
338    pub fn set_basis_checks(&mut self, enabled: bool) {
339        self.basis_checks = enabled;
340    }
341
342    /// Create an e-graph with built-in sorts and reserved op names from a `LitModel`.
343    pub fn from_model(model: &impl crate::lit_model::LitModel<Value = L>) -> Self {
344        let mut eg = Self::new();
345        let sort_names: Vec<&str> = model.sorts().iter().map(|s| s.name).collect();
346        eg.sorts.register_builtins(&sort_names);
347        eg.ops.register_builtins(model, &eg.sorts);
348        eg
349    }
350
351    /// Create an e-graph with pre-built registries (from sortcheck).
352    pub fn with_registries(
353        sorts: SortRegistry<Cfg::S, TRACK>,
354        ops: OpRegistry<Cfg::O, Cfg::S, TRACK>,
355    ) -> Self {
356        let mut eg = Self::new();
357        eg.sorts = sorts;
358        eg.ops = ops;
359        eg
360    }
361
362    pub fn len(&self) -> usize {
363        self.nodes.len()
364    }
365    pub fn is_empty(&self) -> bool {
366        self.nodes.is_empty()
367    }
368
369    /// Every node id in the store, ascending.
370    ///
371    /// The one place a full scan should get its ids from. The obvious spelling —
372    /// `for i in 0..eg.len() { Cfg::G::from_usize(i) }` — is sound but not *locally*
373    /// justified: `Cfg::G::Index` spans twice the id space for a bit-stealing id, and
374    /// `from_usize` rejects positions outside the smaller payload range. What keeps the
375    /// routing table inside that range is that [`TypedRouting::reserve`] mints every entry
376    /// through `try_new`, three modules away. Stating that once here means a new scan
377    /// inherits the argument instead of re-deriving it.
378    ///
379    /// [`TypedRouting::reserve`]: crate::typed_routing::TypedRouting::reserve
380    pub fn node_ids(&self) -> impl Iterator<Item = Cfg::G> + '_ {
381        use crate::containers::DenseId;
382        (0..self.len()).map(Cfg::G::from_usize)
383    }
384    pub fn sorts(&self) -> &SortRegistry<Cfg::S, TRACK> {
385        &self.sorts
386    }
387    pub fn sorts_mut(&mut self) -> &mut SortRegistry<Cfg::S, TRACK> {
388        &mut self.sorts
389    }
390    pub fn ops(&self) -> &OpRegistry<Cfg::O, Cfg::S, TRACK> {
391        &self.ops
392    }
393
394    pub fn ops_mut(&mut self) -> &mut OpRegistry<Cfg::O, Cfg::S, TRACK> {
395        &mut self.ops
396    }
397    pub fn lits(&self) -> &LitValStore<L, Cfg::V, TRACK> {
398        &self.lits
399    }
400    pub fn lits_mut(&mut self) -> &mut LitValStore<L, Cfg::V, TRACK> {
401        &mut self.lits
402    }
403
404    pub fn rules(&self) -> &RuleRegistry<TRACK> {
405        &self.rules
406    }
407    pub fn register_rule(&mut self, name: &str, lhs: &str, rhs: &str) -> crate::id::RuleId {
408        self.rules.register(name, lhs, rhs)
409    }
410
411    pub fn axioms(&self) -> &AxiomRegistry<Cfg::G, TRACK> {
412        &self.axioms
413    }
414    pub fn register_axiom(&mut self, name: &str, lhs: Cfg::G, rhs: Cfg::G) -> crate::id::AxiomId {
415        self.axioms.register(name, lhs, rhs)
416    }
417
418    // Sorts
419    pub fn intern_sort(&mut self, name: &str) -> Cfg::S {
420        self.sorts.intern(name)
421    }
422    pub fn sort_name(&self, id: Cfg::S) -> &str {
423        self.sorts.name(id)
424    }
425
426    pub fn register_op0(&mut self, name: &str, ret: Cfg::S) -> Cfg::O {
427        self.ops.register(name, &[], ret)
428    }
429    pub fn register_op1(&mut self, name: &str, a: Cfg::S, ret: Cfg::S) -> Cfg::O {
430        self.ops.register(name, &[a], ret)
431    }
432    pub fn register_op2(&mut self, name: &str, a: Cfg::S, b: Cfg::S, ret: Cfg::S) -> Cfg::O {
433        self.ops.register(name, &[a, b], ret)
434    }
435    pub fn register_op3(
436        &mut self,
437        name: &str,
438        a: Cfg::S,
439        b: Cfg::S,
440        c: Cfg::S,
441        ret: Cfg::S,
442    ) -> Cfg::O {
443        self.ops.register(name, &[a, b, c], ret)
444    }
445    pub fn register_opn(&mut self, name: &str, args: &[Cfg::S], ret: Cfg::S) -> Cfg::O {
446        self.ops.register(name, args, ret)
447    }
448    pub fn register_c(&mut self, name: &str, arg_sorts: [Cfg::S; 2], ret: Cfg::S) -> Cfg::O {
449        self.ops.register_c(name, arg_sorts, ret)
450    }
451    /// Register an op from a resolved kind plus its non-algebraic metadata (constructor-ness,
452    /// `:cost`, `:unextractable`). The surface layer's single registration entry point — see
453    /// [`crate::registry::OpRegistry::register_kind_meta`].
454    pub fn register_kind_meta(
455        &mut self,
456        name: &str,
457        ret: Cfg::S,
458        kind: crate::registry::OpKind<Cfg::S>,
459        meta: crate::registry::OpMeta,
460    ) -> Cfg::O {
461        self.ops.register_kind_meta(name, ret, kind, meta)
462    }
463    pub fn register_a(
464        &mut self,
465        name: &str,
466        arg: Cfg::S,
467        ret: Cfg::S,
468        dir: crate::registry::AssocDir,
469    ) -> Cfg::O {
470        self.ops.register_a(name, arg, ret, dir)
471    }
472    pub fn register_mset(&mut self, name: &str, arg: Cfg::S, ret: Cfg::S) -> Cfg::O {
473        self.ops.register_mset(name, arg, ret)
474    }
475    pub fn register_set(&mut self, name: &str, arg: Cfg::S, ret: Cfg::S) -> Cfg::O {
476        self.ops.register_set(name, arg, ret)
477    }
478    /// Register an op from a fully-resolved `OpKind` (the property-tag resolver in `sortcheck`).
479    pub fn register_kind(&mut self, name: &str, ret: Cfg::S, kind: OpKind<Cfg::S>) -> Cfg::O {
480        self.ops.register_kind(name, ret, kind)
481    }
482    /// Record `op`'s identity (unit) element node (`x ∘ e = x`; the unit drops from monomials).
483    /// Called by the resolver in `sortcheck` after it builds the `:identity` term to a node.
484    pub fn set_unit_node(&mut self, op: Cfg::O, unit: Cfg::G) {
485        self.unit_node
486            .try_insert(op, unit)
487            .expect("unit/inverse-op map exhausted its index word");
488    }
489    /// The identity (unit) element node of `op`, or `None` if `op` has no declared identity.
490    pub fn unit_node(&self, op: Cfg::O) -> Option<Cfg::G> {
491        self.unit_node.get_by_key(&op).copied()
492    }
493    pub fn set_inverse_op(&mut self, op: Cfg::O, inv: Cfg::O) {
494        self.inverse_op
495            .try_insert(op, inv)
496            .expect("unit/inverse-op map exhausted its index word");
497    }
498    /// The group inverse operator of `op` (`:inverse neg`), or `None` if none declared.
499    pub fn inverse_op(&self, op: Cfg::O) -> Option<Cfg::O> {
500        self.inverse_op.get_by_key(&op).copied()
501    }
502
503    /// Cancel inverse pairs in a canonical monomial of an op declared `:inverse inv`
504    /// (the group law `x ∘ inv(x) = e` applied at pair level, Kapur §5.4's simplest
505    /// instance): for each summand class `x`, if the class of the EXISTING node `inv(x)`
506    /// is also a summand, matched pairs are removed; a self-inverse class
507    /// (`find(inv(x)) == x`) cancels within its own count. Lookup-only (hash-cons probe of
508    /// the inverse op's unary partition); removing a pair is sound because the pair equals
509    /// the unit, which canonical monomials do not carry (`f({}) = e`). Returns whether the
510    /// monomial changed; zeroed entries are dropped. This is NOT full group completion —
511    /// no Gaussian elimination, and pairs whose inverse node was never built are not seen.
512    /// Cancels `:inverse`-related summand pairs in place, at the configured
513    /// multiplicity width. Purely subtractive — `rem_order(2)` and pairwise
514    /// cancellation by the smaller of two counts — so no step can overflow.
515    pub(crate) fn group_cancel_pairs(&self, inv: Cfg::O, m: &mut Vec<(Cfg::G, Cfg::M)>) -> bool {
516        let zero = Cfg::M::ZERO;
517        let mut changed = false;
518        for i in 0..m.len() {
519            let (x, xc) = (m[i].0, m[i].1);
520            if xc == zero {
521                continue;
522            }
523            let Some(inv_node) = self.nodes.plain1.probe(&inv, &[x]) else {
524                continue;
525            };
526            let y = self.classes.find_const(inv_node);
527            if y == x {
528                // x is its own inverse: copies cancel pairwise (x ∘ x = e here).
529                if xc
530                    >= Cfg::M::ONE
531                        .checked_add(Cfg::M::ONE)
532                        .expect("2 fits every width")
533                {
534                    m[i].1 = xc.rem_order(2);
535                    changed = true;
536                }
537            } else if let Ok(j) = m.binary_search_by(|p| p.0.cmp(&y)) {
538                // The probe is one-directional (inv(y)'s node may not exist), so cancel
539                // eagerly on first sight; the mirrored visit then finds a zeroed side.
540                let k = m[i].1.min(m[j].1);
541                if k > zero {
542                    m[i].1 = m[i].1.saturating_sub(k);
543                    m[j].1 = m[j].1.saturating_sub(k);
544                    changed = true;
545                }
546            }
547        }
548        if changed {
549            m.retain(|p| p.1 != zero);
550        }
551        changed
552    }
553    pub fn register_lit(&mut self, name: &str, ret: Cfg::S) -> Cfg::O {
554        self.ops.register_lit(name, ret)
555    }
556    pub fn op(&self, name: &str) -> Option<Cfg::O> {
557        self.ops.id_by_name(name)
558    }
559    pub fn intern_lit(&mut self, value: L) -> Cfg::V {
560        self.lits.intern(value)
561    }
562
563    // ── Node operations ──
564
565    /// Run a compiled query plan against this e-graph.
566    pub fn run_query(
567        &self,
568        plan: &crate::schedule::QueryPlan<Cfg::O, Cfg::Index, L>,
569    ) -> Vec<crate::ematch::Match<Cfg>> {
570        let index = crate::index::IndexStore::build(self);
571        let vindex = crate::index::VariantIndex::naive(&index);
572        let empty: crate::resolve::GlobalCtx<Cfg::S, Cfg::G> = crate::resolve::GlobalCtx::new();
573        crate::ematch::run_query(plan, self, &vindex, &empty)
574    }
575
576    /// Saturate: apply rules to fixpoint or until `limit` iterations.
577    pub fn saturate<M: crate::lit_model::LitModel<Value = L>, S: crate::DenseId + Copy>(
578        &mut self,
579        rules: &[crate::apply::PreparedRule<Cfg::O, S, L>],
580        model: &M,
581        limit: usize,
582        globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
583    ) -> crate::saturate::SatResult {
584        crate::saturate::saturate(rules, self, model, limit, globals)
585    }
586
587    /// Semi-naive saturation via delta variants. The driver does not switch
588    /// wholesale to naive; rules without safe delta coverage use a full-index match.
589    pub fn saturate_semi<M: crate::lit_model::LitModel<Value = L>, S: crate::DenseId + Copy>(
590        &mut self,
591        rules: &[crate::apply::PreparedRule<Cfg::O, S, L>],
592        model: &M,
593        limit: usize,
594        globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
595    ) -> crate::saturate::SatResult {
596        crate::saturate::saturate_semi(rules, self, model, limit, globals)
597    }
598
599    /// Saturate under a full [`RunSpec`](crate::saturate::RunSpec) — budget, ruleset, and
600    /// `:until` goal. The interpreter's `(run …)` path.
601    pub fn saturate_spec<M: crate::lit_model::LitModel<Value = L>, S: crate::DenseId + Copy>(
602        &mut self,
603        rules: &[crate::apply::PreparedRule<Cfg::O, S, L>],
604        model: &M,
605        spec: &crate::saturate::RunSpec<Cfg::G>,
606        globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
607    ) -> crate::saturate::SatResult {
608        crate::saturate::saturate_spec(rules, self, model, spec, globals)
609    }
610
611    /// Semi-naive counterpart of [`saturate_spec`](Self::saturate_spec).
612    pub fn saturate_semi_spec<
613        M: crate::lit_model::LitModel<Value = L>,
614        S: crate::DenseId + Copy,
615    >(
616        &mut self,
617        rules: &[crate::apply::PreparedRule<Cfg::O, S, L>],
618        model: &M,
619        spec: &crate::saturate::RunSpec<Cfg::G>,
620        globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
621    ) -> crate::saturate::SatResult {
622        crate::saturate::saturate_semi_spec(rules, self, model, spec, globals)
623    }
624
625    /// [`saturate_spec`](Self::saturate_spec) over a caller-owned index scratch,
626    /// so its span arenas survive the call. See
627    /// [`saturate_spec_in`](crate::saturate::saturate_spec_in).
628    pub fn saturate_spec_in<M: crate::lit_model::LitModel<Value = L>, S: crate::DenseId + Copy>(
629        &mut self,
630        rules: &[crate::apply::PreparedRule<Cfg::O, S, L>],
631        model: &M,
632        spec: &crate::saturate::RunSpec<Cfg::G>,
633        globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
634        scratch: &mut crate::index::IndexScratch<Cfg>,
635    ) -> crate::saturate::SatResult {
636        crate::saturate::saturate_spec_in(rules, self, model, spec, globals, scratch)
637    }
638
639    /// Semi-naive counterpart of [`saturate_spec_in`](Self::saturate_spec_in).
640    pub fn saturate_semi_spec_in<
641        M: crate::lit_model::LitModel<Value = L>,
642        S: crate::DenseId + Copy,
643    >(
644        &mut self,
645        rules: &[crate::apply::PreparedRule<Cfg::O, S, L>],
646        model: &M,
647        spec: &crate::saturate::RunSpec<Cfg::G>,
648        globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
649        scratch: &mut crate::index::IndexScratch<Cfg>,
650    ) -> crate::saturate::SatResult {
651        // Semi-naive is the one consumer of the merge-membership delta (see
652        // `merge_in_classes`); the flag keeps the per-merge ring walks off
653        // everywhere else.
654        self.track_merge_members = true;
655        let r = crate::saturate::saturate_semi_spec_in(rules, self, model, spec, globals, scratch);
656        self.track_merge_members = false;
657        r
658    }
659
660    /// The number of distinct e-classes over the current node set. A scan, not a maintained
661    /// counter: `(print-size)` / `(print-stats)` ask for it a handful of times per program.
662    pub fn class_count(&self) -> usize {
663        let n = self.len();
664        let mut seen = vec![false; n];
665        let mut count = 0;
666        for id in self.node_ids() {
667            let r = self.find_const(id).to_usize();
668            if !seen[r] {
669                seen[r] = true;
670                count += 1;
671            }
672        }
673        count
674    }
675
676    /// Node counts per operator, indexed by op id (ops with no nodes read 0).
677    pub fn op_node_counts(&self) -> Vec<usize> {
678        let mut counts = vec![0usize; self.ops.meta_table().len()];
679        for id in self.node_ids() {
680            let op = self.node_op(id).to_usize();
681            if op < counts.len() {
682                counts[op] += 1;
683            }
684        }
685        counts
686    }
687
688    pub fn find(&mut self, x: Cfg::G) -> Cfg::G {
689        self.classes.find(x)
690    }
691
692    pub fn find_const(&self, x: Cfg::G) -> Cfg::G {
693        self.classes.find_const(x)
694    }
695
696    pub fn add(&mut self, op: Cfg::O, children: &[Cfg::G]) -> Cfg::G {
697        #[cfg(debug_assertions)]
698        {
699            let info = self.ops.info(op);
700            match &info.kind {
701                OpKind::Normal { arg_sorts } => {
702                    debug_assert_eq!(
703                        children.len(),
704                        arg_sorts.len(),
705                        "operator '{}' expects {} children, got {}",
706                        info.name,
707                        arg_sorts.len(),
708                        children.len()
709                    );
710                    for (i, (&c, &s)) in children.iter().zip(arg_sorts.iter()).enumerate() {
711                        let got = self.node_sort(c);
712                        debug_assert_eq!(
713                            got,
714                            s,
715                            "operator '{}' expected sort '{}' at position {}, got '{}'",
716                            info.name,
717                            self.sorts.name(s),
718                            i,
719                            self.sorts.name(got)
720                        );
721                    }
722                }
723                OpKind::Commutative { arg_sorts } => {
724                    debug_assert_eq!(
725                        children.len(),
726                        2,
727                        "operator '{}' (commutative) expects 2 children, got {}",
728                        info.name,
729                        children.len()
730                    );
731                    for (i, (&c, &s)) in children.iter().zip(arg_sorts.iter()).enumerate() {
732                        let got = self.node_sort(c);
733                        debug_assert_eq!(
734                            got,
735                            s,
736                            "operator '{}' expected sort '{}' at position {}, got '{}'",
737                            info.name,
738                            self.sorts.name(s),
739                            i,
740                            self.sorts.name(got)
741                        );
742                    }
743                }
744                OpKind::A { arg_sort, .. }
745                | OpKind::MSet { arg_sort, .. }
746                | OpKind::Set { arg_sort, .. } => {
747                    for (i, &c) in children.iter().enumerate() {
748                        let got = self.node_sort(c);
749                        debug_assert_eq!(
750                            got,
751                            *arg_sort,
752                            "operator '{}' expected sort '{}' at position {}, got '{}'",
753                            info.name,
754                            self.sorts.name(*arg_sort),
755                            i,
756                            self.sorts.name(got)
757                        );
758                    }
759                }
760                OpKind::Lit => {}
761            }
762        }
763        self.g_buf.clear();
764        self.g_buf
765            .extend(children.iter().map(|&c| self.classes.find(c)));
766
767        // Flatten nested same-op AC children (associativity, `WF_flat`, design §6c): splice
768        // any child whose class is a pure same-op sum, keyed on the class's canonical
769        // summand form (atomic-aware), so `+(+(a,b), c)` becomes `+(a,b,c)`. An atomic child
770        // (e.g. `c` used as `neg`'s child in §5b) is kept as a summand. BOTH completion
771        // representations flatten; otherwise `(Or (Or x y) z)` and `(Or x y z)`
772        // differ for Set (ACI) ops with completion off. See set_flatten_build.egg.
773        if matches!(
774            self.ops.info(op).kind,
775            OpKind::MSet { .. } | OpKind::Set { .. }
776        ) {
777            self.flatten_ac_children(op);
778        }
779
780        // The A-only (`Seq`) counterpart of the same law. Every associative spelling
781        // (`:assoc-left`, `:assoc-right`, and `:assoc`) currently has the same flattened
782        // sequence semantics; `AssocDir` is retained registration metadata. Only the merge
783        // step differs from AC: an order-preserving splice here, because associativity permits
784        // re-association but not reordering.
785        if matches!(self.ops.info(op).kind, OpKind::A { .. }) {
786            self.flatten_seq_children(op);
787        }
788
789        // Canonization must *establish* the op's algebraic normal form at build time (not defer
790        // it to completion): coalesce/dedup, drop the identity's unit class, apply the count clamp
791        // (nilpotent mod-n), and resolve a degenerate arity. Degeneracy is an equality, so the
792        // last step returns an *existing* class id instead of a fresh node:
793        //   - empty multiset  ⇒ the term IS the unit  (`xor(a,a) → {} = e`)
794        //   - single mult-1    ⇒ the term IS that child (`+(a, e) → {a} = a`, `and(a,a) → {a} = a`)
795        // These hold with completion off; completion only adds the cross-rule (superposition)
796        // consequences. `find_unit`/degeneracy read `unit_node`, resolved at registration.
797        // The constructor bit is stamped at creation, not written back after:
798        // `set_node_flag` would have to resolve the routing table and dispatch
799        // on the node kind again, for a node the store has just built.
800        let node_flags = if self.ops.info(op).is_constructor {
801            crate::node_types::FLAG_CONSTRUCTOR
802        } else {
803            0
804        };
805        let result = match self.ops.info(op).kind {
806            OpKind::MSet { .. } => {
807                // Only the two completion arms read the identity, and looking it
808                // up is a hash probe of the semi-persistent unit map — a cost the
809                // plain-op path used to pay on every `add`.
810                let unit = self.unit_node(op);
811                self.g_buf.sort_by_key(|id| id.to_usize());
812                self.mset_buf.clear();
813                for &id in &self.g_buf {
814                    if let Some(last) = self.mset_buf.last_mut()
815                        && Cfg::mset_child_merge(last, id)
816                    {
817                        continue;
818                    }
819                    self.mset_buf.push(Cfg::mset_child_single(id));
820                }
821                // Identity: drop the unit's class (`+(a, e) → {a}`).
822                if let Some(u) = unit {
823                    let uc = self.classes.find_const(u);
824                    self.mset_buf.retain(|c| Cfg::mset_child_id(c) != uc);
825                }
826                // Nilpotent clamp: reduce each multiplicity mod n, drop zeros (`xor(a,a) → {}`).
827                // Routed through the SINGLE source of the mod-n law, `MSetCanon::clamp_multiset`
828                // (also used by the recanonize path), so the two paths cannot drift. `Cfg::C` is
829                // concretely `(G, Multiplicity)` but opaque to generic code, so we convert the
830                // buffer through the config accessors around the shared call. Nilpotent-only, so
831                // the conversion never touches the common plain-AC / idempotent build.
832                if let crate::registry::Clamp::Nilpotent { order } = self.op_clamp_kind(op) {
833                    // prod-parity: `clamp_multiset` operates on `Pair<G, Mult>`
834                    // (was `(G, Mult)`; Verus can't impl `Tagged` for a tuple).
835                    // The pair carries `Cfg::M` directly — no narrowing round trip
836                    // through a fixed width, which is what used to truncate here.
837                    let mut tuples: Vec<crate::containers::Pair<Cfg::G, Cfg::M>> = self
838                        .mset_buf
839                        .iter()
840                        .map(|c| crate::containers::Pair {
841                            a: Cfg::mset_child_id(c),
842                            b: Cfg::mset_child_mult(c),
843                        })
844                        .collect();
845                    MSetCanon::clamp_multiset(&mut tuples, MSetClamp::Nilpotent { order });
846                    self.mset_buf.clear();
847                    self.mset_buf
848                        .extend(tuples.iter().map(|p| Cfg::mset_child_with_mult(p.a, p.b)));
849                }
850                // Group inverse-pair cancellation (`x ∘ inv(x) = e`): summand pairs related
851                // by the op's declared `:inverse` cancel at build, like the unit drop. Rare
852                // (inverse ops only), so the tuple conversion is off the common path.
853                if let Some(inv) = self.inverse_op(op) {
854                    let mut tuples: Vec<(Cfg::G, Cfg::M)> = self
855                        .mset_buf
856                        .iter()
857                        .map(|c| (Cfg::mset_child_id(c), Cfg::mset_child_mult(c)))
858                        .collect();
859                    if self.group_cancel_pairs(inv, &mut tuples) {
860                        self.mset_buf.clear();
861                        self.mset_buf.extend(
862                            tuples
863                                .iter()
864                                .map(|(g, m)| Cfg::mset_child_with_mult(*g, *m)),
865                        );
866                    }
867                }
868                // Degenerate arity ⇒ an existing class, not a fresh node. An empty monomial is the
869                // unit; a single mult-1 summand is that summand's class. Empty *without* a declared
870                // unit is an API-contract violation (the surface layer rejects it at sortcheck):
871                // the empty monomial names nothing in a semigroup, so minting a node for it would
872                // put a meaningless term in the graph — panic in ALL builds, like the other
873                // registration invariants.
874                match self.mset_buf.len() {
875                    0 => match unit {
876                        Some(u) => return u,
877                        None => panic!(
878                            "zero-child MSet term without a declared identity — \
879                             the empty monomial has no algebraic meaning for a semigroup op"
880                        ),
881                    },
882                    1 if Cfg::mset_child_mult(&self.mset_buf[0]) == Cfg::M::ONE => {
883                        return self.classes.find(Cfg::mset_child_id(&self.mset_buf[0]));
884                    }
885                    _ => self.nodes.add_mset(op, &self.mset_buf, node_flags),
886                }
887            }
888            OpKind::Set { .. } => {
889                let unit = self.unit_node(op);
890                self.g_buf.sort_by_key(|id| id.to_usize());
891                self.g_buf.dedup();
892                // Identity: drop the unit's class (`and(a, unit) → {a}`).
893                if let Some(u) = unit {
894                    let uc = self.classes.find_const(u);
895                    self.g_buf.retain(|&g| g != uc);
896                }
897                // Degenerate arity ⇒ an existing class (idempotent has no nilpotent clamp, so a
898                // Set monomial only reaches {} via identity-drop, and size-1 via dedup/drop).
899                // Empty without a declared unit is an API-contract violation — panic (see the
900                // MSet counterpart above).
901                match self.g_buf.len() {
902                    0 => match unit {
903                        Some(u) => return u,
904                        None => panic!(
905                            "zero-child Set term without a declared identity — \
906                             the empty monomial has no algebraic meaning for a semigroup op"
907                        ),
908                    },
909                    1 => return self.classes.find(self.g_buf[0]),
910                    _ => self.nodes.add_set(op, &self.g_buf, node_flags),
911                }
912            }
913            OpKind::A { .. } => {
914                // Degenerate arity ⇒ an existing class, the A-only counterpart of the MSet/Set
915                // degeneracy above: a one-element sequence IS its element (`seq(x) = x`),
916                // so return that child's class instead of minting a node for it. There is
917                // no empty case to resolve — an A-only op cannot declare `:identity` (the
918                // property resolver rejects `:identity` without `:comm`, `sortcheck.rs`),
919                // so the empty sequence names nothing in the algebra. Sortcheck already
920                // rejects a zero-argument A application; reaching here is an API-contract
921                // violation, and panics in ALL builds like the MSet/Set counterparts.
922                match self.g_buf.len() {
923                    0 => panic!(
924                        "zero-child A term — an A-only operator has no identity, so the \
925                         empty sequence has no algebraic meaning for a semigroup op"
926                    ),
927                    1 => return self.classes.find(self.g_buf[0]),
928                    _ => self.nodes.add(op, &self.g_buf, &self.ops, node_flags),
929                }
930            }
931            _ => self.nodes.add(op, &self.g_buf, &self.ops, node_flags),
932        };
933
934        let id = self.register_if_fresh(result, op);
935        if result.is_fresh() {
936            match self.ops.info(op).kind {
937                OpKind::MSet { .. } => {
938                    for c in &self.mset_buf {
939                        let child = Cfg::mset_child_id(c);
940                        if let Some(repr) = self.classes.repr_id(child) {
941                            self.classes.add_use(repr, id);
942                        }
943                    }
944                }
945                _ => {
946                    for &child in &self.g_buf {
947                        if let Some(repr) = self.classes.repr_id(child) {
948                            self.classes.add_use(repr, id);
949                        }
950                    }
951                }
952            }
953        }
954        id
955    }
956
957    pub fn add_lit(&mut self, op: Cfg::O, lit: Cfg::V) -> Cfg::G {
958        let result = self.nodes.add_lit(op, lit, 0);
959        self.register_if_fresh(result, op)
960    }
961
962    /// Build a *ground* checked term (a literal or a constructor applied to ground args) into a
963    /// node, returning its id. Mirrors the interpreter's `build_cterm` for the ground cases; it
964    /// has no access to globals, so a `CTerm::Global` is unreachable here (a unit is always
965    /// ground) and panics. Used by the property-tag resolver to materialize an op's `:identity`
966    /// unit at registration.
967    pub fn build_ground_cterm(
968        &mut self,
969        ct: &crate::sortcheck::CTerm<Cfg::O, Cfg::S, L>,
970    ) -> Cfg::G {
971        match ct {
972            crate::sortcheck::CTerm::Lit(val, sort) => {
973                let lit_op = self
974                    .ops
975                    .lit_op_for_sort(*sort)
976                    .expect("no lit op for identity's sort");
977                let vid = self.lits.intern(val.clone());
978                self.add_lit(lit_op, vid)
979            }
980            crate::sortcheck::CTerm::App { op, children, .. } => {
981                let child_ids: Vec<Cfg::G> = children
982                    .iter()
983                    .map(|c| self.build_ground_cterm(c))
984                    .collect();
985                self.add(*op, &child_ids)
986            }
987            crate::sortcheck::CTerm::Global(..) => {
988                panic!("identity unit must be a ground term, not a global reference")
989            }
990        }
991    }
992
993    /// Fill `buf` with `node`'s monomial for `monomial_cmp`: its canonical AC child
994    /// multiset if it is an AC node, else the singleton `{node}` (a non-AC node is a
995    /// size-1 monomial, §9b). Children are `find`-canonicalized and coalesced.
996    pub(crate) fn node_monomial_into(&self, node: Cfg::G, buf: &mut Vec<(Cfg::G, Cfg::M)>) {
997        buf.clear();
998        match self.node_ref(node) {
999            NodeRef::MSet(_) => {
1000                // Children find-canonicalized, then sorted + coalesced in place in the
1001                // destination (same form as MSetCanon), with no intermediate Vec.
1002                self.for_each_child(node, |g, mult| {
1003                    buf.push((self.classes.find_const(g), mult));
1004                });
1005                buf.sort_by_key(|p| p.0);
1006                let mut w = 0usize;
1007                for r in 1..buf.len() {
1008                    if buf[r].0 == buf[w].0 {
1009                        // Coalescing after find-canonicalization is the one step here
1010                        // that grows a multiplicity, so it is the one that can exceed
1011                        // the configured width. Detected, not wrapped: a wrapped sum
1012                        // would shrink the monomial — to zero at exactly the wrong
1013                        // values — and the caller's clamps would then drop the summand,
1014                        // making the e-graph assert an equality that does not hold.
1015                        buf[w].1 = buf[w].1.checked_add(buf[r].1).expect(
1016                            "monomial coalescing overflowed EGraphConfig::M; \
1017                             the configured multiplicity width is too narrow for this e-graph",
1018                        );
1019                    } else {
1020                        w += 1;
1021                        buf[w] = buf[r];
1022                    }
1023                }
1024                if !buf.is_empty() {
1025                    buf.truncate(w + 1);
1026                }
1027            }
1028            NodeRef::Set(_) => {
1029                // Set semantics: find-canonicalize, sort, DEDUP — multiplicity stays 1
1030                // (two summands whose classes merged count once, the idempotent join).
1031                // This is the ACI monomial, same form as SetCanon.
1032                self.for_each_child(node, |g, _| {
1033                    buf.push((self.classes.find_const(g), Cfg::M::ONE));
1034                });
1035                buf.sort_by_key(|p| p.0);
1036                buf.dedup_by_key(|p| p.0);
1037            }
1038            _ => {
1039                buf.push((self.classes.find_const(node), Cfg::M::ONE));
1040            }
1041        }
1042        // No clamp / unit-drop here: canonization (`add`, `recanonize_node`) already established
1043        // the op's algebraic normal form (nilpotent mod-n, identity unit-drop) in the stored node,
1044        // and `cc_round` only runs after `rebuild_congruence` recanonicalizes every node. So a
1045        // stored MSet/Set node's children are already the canonical monomial; reading them
1046        // back is enough. Unit dropping on the recanonize path is enforced by
1047        // `CanonMode.unit` plus the became-a-unit sweep in `rebuild_congruence`;
1048        // completion does not reapply canonization.
1049    }
1050
1051    /// The completion column of `node`'s op (its position in the registry `completion_ops`
1052    /// array), or `None` if `node`'s op is not a completion (MSet/Set) op.
1053    fn completion_column(&self, node: Cfg::G) -> Option<usize> {
1054        self.ops.completion_column(self.node_op(node))
1055    }
1056
1057    /// The op's registry count `Clamp` (`None` / `Idempotent` / `Nilpotent`). The build/canonize
1058    /// path reads this directly (the algebraic normal form), where `op_clamp`'s `CompletionClamp`
1059    /// projection is completion-shaped. `None` for a non-AC op.
1060    fn op_clamp_kind(&self, op: Cfg::O) -> crate::registry::Clamp {
1061        match self.ops.info(op).kind {
1062            OpKind::MSet { clamp, .. } | OpKind::Set { clamp, .. } => clamp,
1063            _ => crate::registry::Clamp::None,
1064        }
1065    }
1066
1067    /// Whether the op is declared cancelative (`:cancellative`, or implied by `:inverse` —
1068    /// groups are cancelative, Kapur §5.4). Drives the §5 cancel-closure inferences.
1069    fn op_cancellative(&self, op: Cfg::O) -> bool {
1070        match self.ops.info(op).kind {
1071            OpKind::MSet { cancellative, .. } | OpKind::Set { cancellative, .. } => cancellative,
1072            _ => false,
1073        }
1074    }
1075
1076    /// The normalization clamp for an op's completion monomials: unbounded (MSet), clamp-to-1
1077    /// (Set idempotent, ACI), or mod-n (nilpotent — stored MSet). Determines how reducts and normal forms
1078    /// are reduced (design "three independent axes").
1079    pub(crate) fn op_clamp(&self, op: Cfg::O) -> CompletionClamp {
1080        use crate::registry::Clamp;
1081        match self.ops.info(op).kind {
1082            // Nilpotent is stored MSet (keeps multiplicities); its clamp is read here.
1083            OpKind::MSet {
1084                clamp: Clamp::Nilpotent { order },
1085                ..
1086            } => CompletionClamp::Nilpotent { order },
1087            OpKind::MSet { .. } => CompletionClamp::Multiset,
1088            OpKind::Set {
1089                clamp: Clamp::Idempotent,
1090                ..
1091            } => CompletionClamp::Idempotent,
1092            // A Set with any other clamp is never constructed (resolver invariant); treat as ACI.
1093            OpKind::Set { .. } => CompletionClamp::Idempotent,
1094            _ => CompletionClamp::Multiset, // non-completion op; never reached in the round
1095        }
1096    }
1097
1098    /// Fill `buf` with the completion rule right-hand side for the class of `node`: the
1099    /// **empty monomial** if the class is `node`'s op's identity (unit) class, the size-1
1100    /// monomial `{find(node)}` if the class is `atomic` (referenced as a child), else
1101    /// the monomial of the class's stored min-monomial for `node`'s op column (§9a). Reads the
1102    /// per-class pool slot; O(1) plus the monomial read. Returns `false` if `node` has no class
1103    /// (or, in the non-atomic case, no stored monomial for its op — a genuine rule always has
1104    /// one, so this only guards the degenerate case).
1105    ///
1106    /// The unit case is Kapur's `f({}) = e` convention (§2.4) and it is load-bearing: a rule
1107    /// whose class is the identity must rewrite `f(M) → f({})`, NOT `f(M) → {e}`. With the
1108    /// atom form, every monomial built from the RHS — superposition reducts, axiom critical
1109    /// pairs, normalization steps — would carry the unit as a summand that `normalize_*`
1110    /// (which has no `f(x,e) = x` law) can never remove and that no stored node matches
1111    /// (canonization unit-drops). The empty-monomial form folds the identity law into the
1112    /// representation, so rewriting can never insert a unit anywhere.
1113    pub(crate) fn class_rhs_into(&self, node: Cfg::G, buf: &mut Vec<(Cfg::G, Cfg::M)>) -> bool {
1114        let cls = self.classes.find_const(node);
1115        let Some(repr) = self.classes.repr_id(cls) else {
1116            return false;
1117        };
1118        if self
1119            .unit_node(self.node_op(node))
1120            .is_some_and(|u| self.classes.find_const(u) == cls)
1121        {
1122            buf.clear();
1123            return true;
1124        }
1125        if self.classes.atomic(repr) {
1126            buf.clear();
1127            buf.push((cls, Cfg::M::ONE));
1128            return true;
1129        }
1130        let Some(col) = self.completion_column(node) else {
1131            return false;
1132        };
1133        let Some(min) = self.classes.min_monomial(repr, col) else {
1134            return false;
1135        };
1136        self.node_monomial_into(min, buf);
1137        true
1138    }
1139
1140    /// Lookup-only resolution of a canonical monomial to the class of an existing node of
1141    /// `op`: degenerate monomials resolve structurally (empty → the op's unit class, size-1
1142    /// mult-1 → that child's class); otherwise the op's partition is probed by hash-cons and
1143    /// the found node's class returned. `None` if no such node exists. Read-only diagnostic
1144    /// helper for the axiom-CP joinability checker (`ac_invariants`); never mutates.
1145    pub(crate) fn resolve_monomial_class(
1146        &self,
1147        op: Cfg::O,
1148        m: &[(Cfg::G, Cfg::M)],
1149    ) -> Option<Cfg::G> {
1150        if m.is_empty() {
1151            return self.unit_node(op).map(|u| self.classes.find_const(u));
1152        }
1153        if m.len() == 1 && m[0].1 == Cfg::M::ONE {
1154            return Some(self.classes.find_const(m[0].0));
1155        }
1156        let node = match self.ops.info(op).kind {
1157            OpKind::MSet { .. } => {
1158                let elems: Vec<Cfg::C> = m
1159                    .iter()
1160                    .map(|&(g, mult)| Cfg::mset_child_with_mult(g, mult))
1161                    .collect();
1162                self.nodes.mset.probe(op, &elems)
1163            }
1164            OpKind::Set { .. } => {
1165                let elems: Vec<Cfg::G> = m.iter().map(|&(g, _)| g).collect();
1166                self.nodes.set.probe(op, &elems)
1167            }
1168            _ => None,
1169        };
1170        node.map(|n| self.classes.find_const(n))
1171    }
1172
1173    /// After a merge, fold the absorbed class's per-class AC data into the survivor's,
1174    /// per completion column: keep the `monomial_cmp`-least min-monomial node for each op, and
1175    /// OR-in the `atomic` flag (§9a). O(nb_completion) columns, each O(1) plus a monomial read,
1176    /// into reusable buffers. Done here, not in `EClasses`, because the comparison needs node
1177    /// (AC-children) access and the op→column map. Best-effort under merge-cascade staleness;
1178    /// completion's read-time orientation guard makes that safe (§9b).
1179    fn fold_min_monomial(
1180        &mut self,
1181        survivor: Cfg::G,
1182        absorbed_min_row: Option<<Cfg::G as DenseId>::Index>,
1183        absorbed_atomic: bool,
1184    ) {
1185        let surv_repr = match self.classes.repr_id(self.classes.find_const(survivor)) {
1186            Some(r) => r,
1187            None => return,
1188        };
1189        if absorbed_atomic {
1190            self.classes.set_atomic(surv_repr);
1191        }
1192        let mut a = std::mem::take(&mut self.cmp_buf_a);
1193        let mut b = std::mem::take(&mut self.cmp_buf_b);
1194        for col in 0..self.classes.min_width() {
1195            let Some(absorbed_min) = self.classes.min_monomial_at_row(absorbed_min_row, col) else {
1196                continue; // absorbed class has no monomial for this op
1197            };
1198            match self.classes.min_monomial(surv_repr, col) {
1199                None => {
1200                    // survivor had no monomial for this op; take the absorbed one.
1201                    self.classes.set_min_monomial(surv_repr, col, absorbed_min);
1202                }
1203                Some(surv_min) if surv_min != absorbed_min => {
1204                    self.node_monomial_into(surv_min, &mut a);
1205                    self.node_monomial_into(absorbed_min, &mut b);
1206                    if crate::multiset::monomial_cmp(&b, &a) == std::cmp::Ordering::Less {
1207                        self.classes.set_min_monomial(surv_repr, col, absorbed_min);
1208                    }
1209                }
1210                Some(_) => {} // equal; nothing to do
1211            }
1212        }
1213        self.cmp_buf_a = a;
1214        self.cmp_buf_b = b;
1215    }
1216
1217    pub fn merge(&mut self, a: Cfg::G, b: Cfg::G) -> Option<(Cfg::G, Cfg::G)> {
1218        debug_assert_eq!(
1219            self.node_sort(a),
1220            self.node_sort(b),
1221            "cannot merge e-classes of different sorts: '{}' has sort '{}', '{}' has sort '{}'",
1222            self.node_op_name(a),
1223            self.sorts.name(self.node_sort(a)),
1224            self.node_op_name(b),
1225            self.sorts.name(self.node_sort(b))
1226        );
1227        debug_assert!(
1228            !self.sorts.is_concrete(self.node_sort(a)),
1229            "cannot merge concrete sort '{}' e-classes",
1230            self.sorts.name(self.node_sort(a))
1231        );
1232        let m = self.merge_in_classes(a, b, None)?;
1233        self.fold_min_monomial(m.survivor, m.absorbed_min_row, m.absorbed_atomic);
1234        self.worklist.push((m.absorbed_uses, m.survivor));
1235        Some((m.survivor, m.absorbed))
1236    }
1237
1238    /// Class merge, recording the absorbed side's member nodes in the
1239    /// semi-naive touched log when `track_merge_members` is set.
1240    ///
1241    /// A merge can create matches without changing any node's canonical form:
1242    /// when the surviving representative is the id the parents already store,
1243    /// nothing recanonicalizes, yet nodes of the absorbed side changed class.
1244    /// The variant decomposition's premise — every new match shows up as a new
1245    /// or re-canonicalized tuple in some atom's relation — then needs the
1246    /// membership change itself in the delta, and the absorbed members are
1247    /// exactly that change: a new match either recanonicalizes a parent
1248    /// (already touched) or connects through a node whose class assignment
1249    /// moved. Collection walks both rings before the merge splices them,
1250    /// because the survivor is not known until the union decides; the flag
1251    /// keeps the walk off outside semi-naive saturation, where nothing
1252    /// consumes the log.
1253    fn merge_in_classes(
1254        &mut self,
1255        a: Cfg::G,
1256        b: Cfg::G,
1257        just: Option<Justification<Cfg::G>>,
1258    ) -> Option<crate::classes::MergeInfo<Cfg::G, Cfg::UL>> {
1259        let ra = self.classes.find_const(a);
1260        let rb = self.classes.find_const(b);
1261        if ra == rb {
1262            return None;
1263        }
1264        // Survivor policy (--union-by): `Rank` leaves the choice to the
1265        // union-find; the directed criteria keep the heavier side, so the
1266        // absorbed side is the cheap one and is known before the union.
1267        let prefer_a = match self.union_by {
1268            UnionBy::Rank => None,
1269            _ => Some(self.union_weight(ra) >= self.union_weight(rb)),
1270        };
1271        // Semi-naive merge tracking: collect the absorbed side's members
1272        // before the splice. Under a directed policy only the (small)
1273        // absorbed ring is walked; under rank the survivor is unknown until
1274        // the union decides, so both rings are collected and the absorbed
1275        // one pushed after.
1276        let pre = if self.track_merge_members {
1277            match prefer_a {
1278                Some(pa) => {
1279                    let absorbed_repr = if pa { rb } else { ra };
1280                    let v: Vec<Cfg::G> = self.classes.iter_class(absorbed_repr).collect();
1281                    Some((absorbed_repr, v, None))
1282                }
1283                None => {
1284                    let va: Vec<Cfg::G> = self.classes.iter_class(ra).collect();
1285                    let vb: Vec<Cfg::G> = self.classes.iter_class(rb).collect();
1286                    Some((ra, va, Some(vb)))
1287                }
1288            }
1289        } else {
1290            None
1291        };
1292        let m = match (prefer_a, just) {
1293            (None, None) => self.classes.merge(a, b),
1294            (None, Some(j)) => self.classes.merge_justified(a, b, j),
1295            (Some(pa), None) => self.classes.merge_directed_with(a, b, pa),
1296            (Some(pa), Some(j)) => self.classes.merge_justified_directed_with(a, b, pa, j),
1297        }?;
1298        if let Some((r0, v0, v1)) = pre {
1299            let absorbed = match v1 {
1300                None => v0,
1301                Some(v1) => {
1302                    if m.absorbed == r0 {
1303                        v0
1304                    } else {
1305                        v1
1306                    }
1307                }
1308            };
1309            self.touched.extend(absorbed);
1310        }
1311        Some(m)
1312    }
1313
1314    pub fn merge_justified(
1315        &mut self,
1316        a: Cfg::G,
1317        b: Cfg::G,
1318        just: Justification<Cfg::G>,
1319    ) -> Option<(Cfg::G, Cfg::G)> {
1320        debug_assert_eq!(
1321            self.node_sort(a),
1322            self.node_sort(b),
1323            "cannot merge e-classes of different sorts: '{}' has sort '{}', '{}' has sort '{}'",
1324            self.node_op_name(a),
1325            self.sorts.name(self.node_sort(a)),
1326            self.node_op_name(b),
1327            self.sorts.name(self.node_sort(b))
1328        );
1329        debug_assert!(
1330            !self.sorts.is_concrete(self.node_sort(a)),
1331            "cannot merge concrete sort '{}' e-classes",
1332            self.sorts.name(self.node_sort(a))
1333        );
1334        let m = self.merge_in_classes(a, b, Some(just))?;
1335        self.fold_min_monomial(m.survivor, m.absorbed_min_row, m.absorbed_atomic);
1336        self.worklist.push((m.absorbed_uses, m.survivor));
1337        Some((m.survivor, m.absorbed))
1338    }
1339
1340    pub fn explain(&self, a: Cfg::G, b: Cfg::G, buf: &mut ProofBuf<Cfg::G>) -> bool {
1341        self.classes.explain(a, b, buf)
1342    }
1343
1344    /// Write a deterministic, line-oriented proof-path record for every e-node.
1345    ///
1346    /// Each record names the node's current operator, children, representative,
1347    /// proof-tree LCA, and every justified edge from the node to that
1348    /// representative. One Euler-tour table is built in O(n), then each LCA is
1349    /// queried in O(1); writing the proof paths costs O(number of emitted
1350    /// steps). Representative records have an empty reflexive proof.
1351    ///
1352    /// The dump is available only when `PROOFS = true`. Any successful
1353    /// justified merge or restore invalidates the table, so the complete build
1354    /// and write happen under this single immutable borrow.
1355    pub fn dump_all_proofs<W: std::io::Write>(
1356        &self,
1357        mut out: W,
1358    ) -> std::io::Result<ProofDumpStats> {
1359        if !PROOFS {
1360            return Err(std::io::Error::new(
1361                std::io::ErrorKind::InvalidInput,
1362                "proof dump requires an EGraph with PROOFS=true",
1363            ));
1364        }
1365
1366        let lca = {
1367            let parents = self.classes.proof_parent().ok_or_else(|| {
1368                std::io::Error::new(
1369                    std::io::ErrorKind::InvalidData,
1370                    "PROOFS=true e-graph has no proof-parent forest",
1371                )
1372            })?;
1373            crate::lca::LcaTable::build(parents, self.len())
1374        };
1375
1376        writeln!(out, "# semi-persistent-proof-dump v1")?;
1377        writeln!(
1378            out,
1379            "# each term record proves node == representative; ids are decimal"
1380        )?;
1381        writeln!(out, "terms {}", self.len())?;
1382
1383        let mut stats = ProofDumpStats::default();
1384        let mut buf = ProofBuf::new();
1385        let mut children = Vec::new();
1386
1387        for node in self.node_ids() {
1388            let representative = self.find_const(node);
1389            let ancestor = lca.lca(node, representative).ok_or_else(|| {
1390                std::io::Error::new(
1391                    std::io::ErrorKind::InvalidData,
1392                    format!(
1393                        "proof forest has no LCA for equivalent nodes {} and {}",
1394                        node.to_usize(),
1395                        representative.to_usize()
1396                    ),
1397                )
1398            })?;
1399
1400            buf.clear();
1401            if !self
1402                .classes
1403                .explain_with_lca(node, representative, ancestor, &mut buf)
1404            {
1405                return Err(std::io::Error::new(
1406                    std::io::ErrorKind::InvalidData,
1407                    format!(
1408                        "LCA {} is not on both proof paths for nodes {} and {}",
1409                        ancestor.to_usize(),
1410                        node.to_usize(),
1411                        representative.to_usize()
1412                    ),
1413                ));
1414            }
1415
1416            write!(
1417                out,
1418                "term {} representative {} op {:?}",
1419                node.to_usize(),
1420                representative.to_usize(),
1421                self.node_op_name(node)
1422            )?;
1423            match self.get_lit_val(node) {
1424                Some(value) => write!(out, " literal {:?}", value.to_string())?,
1425                None => write!(out, " literal -")?,
1426            }
1427            children.clear();
1428            self.for_each_child(node, |child, mult| {
1429                children.push((child, mult.to_u64()));
1430            });
1431            write!(out, " children [")?;
1432            for (i, (child, mult)) in children.iter().enumerate() {
1433                if i > 0 {
1434                    write!(out, ",")?;
1435                }
1436                write!(out, "{}:{}", child.to_usize(), mult)?;
1437            }
1438            writeln!(out, "]")?;
1439
1440            writeln!(
1441                out,
1442                "proof lca {} steps {}",
1443                ancestor.to_usize(),
1444                buf.steps.len()
1445            )?;
1446            for &(from, to, justification) in &buf.steps {
1447                write!(out, "step {} {} ", from.to_usize(), to.to_usize())?;
1448                self.write_proof_dump_justification(&mut out, justification)?;
1449                writeln!(out)?;
1450            }
1451            writeln!(out, "end")?;
1452
1453            stats.terms += 1;
1454            stats.nontrivial_proofs += usize::from(!buf.steps.is_empty());
1455            stats.steps += buf.steps.len();
1456        }
1457
1458        writeln!(
1459            out,
1460            "summary terms {} nontrivial {} steps {}",
1461            stats.terms, stats.nontrivial_proofs, stats.steps
1462        )?;
1463        Ok(stats)
1464    }
1465
1466    fn write_proof_dump_justification<W: std::io::Write>(
1467        &self,
1468        out: &mut W,
1469        justification: Justification<Cfg::G>,
1470    ) -> std::io::Result<()> {
1471        match justification {
1472            Justification::Filler => Err(std::io::Error::new(
1473                std::io::ErrorKind::InvalidData,
1474                "proof path contains a filler justification",
1475            )),
1476            Justification::Rewrite { rule_id } => {
1477                write!(out, "rewrite rule={}", rule_id.to_usize())
1478            }
1479            Justification::Congruence { node_a, node_b } => write!(
1480                out,
1481                "congruence nodes={},{}",
1482                node_a.to_usize(),
1483                node_b.to_usize()
1484            ),
1485            Justification::Axiom { axiom_id } => {
1486                write!(out, "axiom id={}", axiom_id.to_usize())
1487            }
1488            Justification::ACSuperposition { node_a, node_b } => write!(
1489                out,
1490                "ac-superposition nodes={},{}",
1491                node_a.to_usize(),
1492                node_b.to_usize()
1493            ),
1494            Justification::ACInterReduction { node_a, node_b } => write!(
1495                out,
1496                "ac-inter-reduction nodes={},{}",
1497                node_a.to_usize(),
1498                node_b.to_usize()
1499            ),
1500            Justification::ACAxiomCP { node_a, node_b } => write!(
1501                out,
1502                "ac-axiom-cp nodes={},{}",
1503                node_a.to_usize(),
1504                node_b.to_usize()
1505            ),
1506            Justification::Cancellative { node_a, node_b } => write!(
1507                out,
1508                "cancellative nodes={},{}",
1509                node_a.to_usize(),
1510                node_b.to_usize()
1511            ),
1512            Justification::InverseCancel { node_a, node_b } => write!(
1513                out,
1514                "inverse-cancel nodes={},{}",
1515                node_a.to_usize(),
1516                node_b.to_usize()
1517            ),
1518        }
1519    }
1520
1521    /// Deep explanation: expand Congruence justifications into child-pair proofs.
1522    /// Appends all steps (including recursive child explanations) to `buf.steps`.
1523    /// Uses an iterative worklist — no recursion.
1524    ///
1525    /// For C/AC/ACI nodes, children are matched by canonical representative
1526    /// (group-by-find), not by position. This avoids combinatorial search.
1527    pub fn explain_deep(&self, a: Cfg::G, b: Cfg::G, buf: &mut ProofBuf<Cfg::G>) -> bool {
1528        if !self.classes.explain(a, b, buf) {
1529            return false;
1530        }
1531
1532        let mut ac_scratch: Vec<Cfg::C> = Vec::new();
1533        let mut i = 0;
1534        while i < buf.steps.len() {
1535            if let Justification::Congruence { node_a, node_b } = buf.steps[i].2 {
1536                buf.children_a.clear();
1537                buf.children_b.clear();
1538                self.collect_original_children(node_a, &mut buf.children_a, &mut ac_scratch);
1539                self.collect_original_children(node_b, &mut buf.children_b, &mut ac_scratch);
1540
1541                let is_ordered = matches!(
1542                    self.node_ref(node_a),
1543                    NodeRef::Plain1(_)
1544                        | NodeRef::Plain2(_)
1545                        | NodeRef::Plain3(_)
1546                        | NodeRef::PlainN(_)
1547                        | NodeRef::Seq(_)
1548                );
1549
1550                if is_ordered {
1551                    let n = buf.children_a.len().min(buf.children_b.len());
1552                    for j in 0..n {
1553                        let ca = buf.children_a[j];
1554                        let cb = buf.children_b[j];
1555                        if ca != cb && self.classes.find_const(ca) == self.classes.find_const(cb) {
1556                            self.classes.explain(ca, cb, buf);
1557                        }
1558                    }
1559                } else {
1560                    self.explain_grouped(buf);
1561                }
1562            }
1563            i += 1;
1564        }
1565        true
1566    }
1567
1568    fn explain_grouped(&self, buf: &mut ProofBuf<Cfg::G>) {
1569        buf.group_a.clear();
1570        buf.group_a.extend_from_slice(&buf.children_a);
1571        buf.group_a
1572            .sort_by_key(|c| self.classes.find_const(*c).to_usize());
1573
1574        buf.group_b.clear();
1575        buf.group_b.extend_from_slice(&buf.children_b);
1576        buf.group_b
1577            .sort_by_key(|c| self.classes.find_const(*c).to_usize());
1578
1579        buf.children_a.clear();
1580        let mut ia = 0;
1581        let mut ib = 0;
1582        while ia < buf.group_a.len() && ib < buf.group_b.len() {
1583            let ra = self.classes.find_const(buf.group_a[ia]).to_usize();
1584            let rb = self.classes.find_const(buf.group_b[ib]).to_usize();
1585            if ra < rb {
1586                ia += 1;
1587            } else if ra > rb {
1588                ib += 1;
1589            } else {
1590                let ca = buf.group_a[ia];
1591                let cb = buf.group_b[ib];
1592                if ca != cb {
1593                    buf.children_a.push(ca);
1594                    buf.children_a.push(cb);
1595                }
1596                ia += 1;
1597                ib += 1;
1598            }
1599        }
1600
1601        let mut k = 0;
1602        while k < buf.children_a.len() {
1603            let ca = buf.children_a[k];
1604            let cb = buf.children_a[k + 1];
1605            self.classes.explain(ca, cb, buf);
1606            k += 2;
1607        }
1608    }
1609
1610    fn collect_original_children(
1611        &self,
1612        id: Cfg::G,
1613        out: &mut Vec<Cfg::G>,
1614        ac_scratch: &mut Vec<Cfg::C>,
1615    ) {
1616        ac_scratch.clear();
1617        if self.nodes.original_children(id, out, ac_scratch) {
1618            for c in ac_scratch.iter() {
1619                out.push(Cfg::mset_child_id(c));
1620            }
1621            return;
1622        }
1623        self.for_each_child(id, |child, _mult| out.push(child));
1624    }
1625
1626    // -----------------------------------------------------------------------
1627    // Rebuild — worklist-based congruence closure
1628    // -----------------------------------------------------------------------
1629
1630    /// Rebuild to a plain-congruence-closed state.
1631    ///
1632    /// Plain congruence closure always runs. AC/ACI completion is opt-in through
1633    /// [`set_cc`](Self::set_cc); it is disabled by default. When enabled, two
1634    /// closures are interleaved (see `doc/design/ac-congruence-completeness.md`
1635    /// section 8, rebuild = Kapur's Algorithm 3):
1636    /// - `rebuild_congruence`: ordinary worklist-driven
1637    ///   congruence closure (substitutes equal *atoms* into recanonicalized nodes);
1638    /// - `cc_round`: AC completion (substitutes
1639    ///   equal *sub-sums*), which canonization alone misses.
1640    ///
1641    /// A completion round may push new merges onto the worklist; we drain them with
1642    /// another congruence pass, then complete again, until a whole completion round
1643    /// adds nothing. Only [`CompletionOutcome::Converged`] reports that joint
1644    /// fixpoint. [`CompletionOutcome::Disabled`], [`CompletionOutcome::GoalMet`],
1645    /// and [`CompletionOutcome::AbortedGrowthLimit`] guarantee plain congruence
1646    /// closure but not complete AC/ACI congruence closure. Inspect
1647    /// [`completion_outcome`](Self::completion_outcome) after each call.
1648    pub fn rebuild(&mut self) {
1649        // Ordinary atom-level congruence closure always runs. AC completion runs only
1650        // when opted in (default off for divergence scoping — see the `cc` field docs).
1651        if !self.cc {
1652            self.rebuild_congruence();
1653            self.completion_outcome = Some(CompletionOutcome::Disabled);
1654            return;
1655        }
1656        // Multiple MSet symbols are supported: the per-class min-monomial pool stores a
1657        // separate least-monomial per completion op (step 3), and the round groups rules by op
1658        // (superposition/normalization filter on `r.op`, RHS via the node's own op column). Two
1659        // MSet ops therefore complete as independent rule sets sharing only the constant pool;
1660        // a class holding monomials of both (`a+b = a*b`) keeps each in its own column, and
1661        // union-find records the cross-op equality (Kapur's shared-constant case). Set (ACI)
1662        // completion is driven too: `completion_node_ids` yields both partitions, reducts
1663        // normalize in the op's count domain (idempotent clamp / mod-n / ℕ), and each rule
1664        // additionally superposes with its op's own axiom (Kapur §4 per-rule critical
1665        // pairs).
1666        let trace = std::env::var_os("AC_COMPLETE_TRACE").is_some();
1667        // Safety backstop against an expensive or nonterminating completion run (minting
1668        // critical-pair nodes): the configurable node-growth budget (see
1669        // `set_completion_node_budget`). If the AC node count grows past the budget beyond
1670        // where it started, we stop rather than continue materializing nodes. This is NOT a
1671        // termination argument or a work bound — it is a growth guard, and the
1672        // abort is REPORTED (`CompletionOutcome::AbortedGrowthLimit`), never silent.
1673        let budget = self.completion_node_budget;
1674        let start_nodes = self.node_count();
1675        self.cc_start_nodes = start_nodes;
1676        let basis_dump = self.basis_checks;
1677        let mut round = 0usize;
1678        // Watermark into the `touched` log: rules whose `(op, monomial)` changed since the
1679        // previous round are approximated by nodes touched (created or recanonicalized) in the
1680        // slice `touched[prev_mark..mark]`. Superposition (B) is incremental over this delta
1681        // (S3b): round 0 is a full pass (base case), each later round superposes only pairs
1682        // with ≥1 endpoint in the delta. A later full confirmation round compensates for
1683        // changes, such as a rule RHS shift, that this node-touch delta does not name.
1684        let mut prev_mark = 0usize;
1685        // Incremental rounds run until one finds nothing; then a single *full* confirmation
1686        // round checks the whole implemented rule set before reporting its operational
1687        // fixpoint. The node-touch delta misses a
1688        // pair only if a rule's RHS shifted without its node being recanonicalized (its own
1689        // class merged, not a child's); a full round closes any such pair. Convergence is
1690        // reported only when a *full* round is unchanged. This is an implementation stopping
1691        // condition, not a machine-checked completeness theorem. Full rounds run at the base
1692        // case and after an unchanged incremental round; their cost is input-dependent.
1693        let mut full = true; // round 0 is full (base case)
1694        loop {
1695            self.rebuild_congruence();
1696            // Goal-directed early stop (the lazy-check transaction): the pair
1697            // joined, so the question is answered — stop mid-closure. The
1698            // graph is plain-congruence-closed at this point, a valid state.
1699            if let Some((ga, gb)) = self.cc_goal
1700                && self.classes.find_const(ga) == self.classes.find_const(gb)
1701            {
1702                self.completion_outcome = Some(CompletionOutcome::GoalMet { rounds: round });
1703                return;
1704            }
1705            if basis_dump {
1706                self.cc_basis_dump(&format!("round {round} pre"));
1707            }
1708            let before = self.node_count();
1709            let mark = self.touched.len();
1710            let was_full = full;
1711            // `|`, not `||`: the A-only pass runs every iteration, its changes
1712            // and the AC round's alike drain through the same fixpoint.
1713            let changed = self.cc_round(full, prev_mark, mark) | self.a_round();
1714            prev_mark = mark;
1715            if trace {
1716                eprintln!(
1717                    "[ac-complete] round {round}{}: nodes {before} -> {} (+{}), changed={changed}",
1718                    if was_full { " (full)" } else { "" },
1719                    self.node_count(),
1720                    self.node_count() - before
1721                );
1722            }
1723            round += 1;
1724            if !changed {
1725                // Incremental round found nothing: confirm with a full round before exiting.
1726                // A full round that also finds nothing is the implemented fixpoint reported
1727                // by CompletionOutcome::Converged.
1728                if was_full {
1729                    self.completion_outcome = Some(CompletionOutcome::Converged { rounds: round });
1730                    return;
1731                }
1732                full = true;
1733                continue;
1734            }
1735            // Made progress: stay incremental for the next round.
1736            full = false;
1737            let added = self.node_count() - start_nodes;
1738            if added > budget {
1739                // Sound-but-incomplete stop: drain the pending congruence work so the
1740                // graph is a valid (plain-congruence-closed) state, then report the abort
1741                // through `completion_outcome` — the caller decides what to do with a
1742                // partial completion (there is deliberately NO assert here: the abort is
1743                // an expected, reported condition on pathological inputs, and tests drive
1744                // it directly with a tiny budget).
1745                self.rebuild_congruence();
1746                self.completion_outcome = Some(CompletionOutcome::AbortedGrowthLimit {
1747                    added_nodes: added,
1748                    limit: budget,
1749                });
1750                if trace {
1751                    eprintln!(
1752                        "[ac-complete] ABORT: added {added} nodes > budget {budget} \
1753                         without converging"
1754                    );
1755                }
1756                return;
1757            }
1758        }
1759    }
1760
1761    /// If a (just-recanonized) MSet/Set node has a degenerate canonical arity, return the
1762    /// equality `(node, target)` it now denotes: an empty monomial equals the op's unit, a
1763    /// single mult-1 summand equals that summand's class. Returns `None` for a well-formed
1764    /// (≥2, or size-1-with-mult>1) monomial or a non-AC node. This is canonization's
1765    /// "AC-of-nothing/one" law read off the stored form; the caller merges the pair. Mirrors
1766    /// the build-path (`add`) degeneracy resolution, for nodes that go degenerate via a child
1767    /// merge rather than at build.
1768    fn degeneracy_merge(&self, node: Cfg::G) -> Option<(Cfg::G, Cfg::G)> {
1769        // Peek the node's canonical child span length (no child read, no alloc) and act only on a
1770        // degenerate arity — the common ≥2 case returns immediately. Recanonize has already
1771        // written the coalesced/clamped children, so the span length *is* the canonical child
1772        // count. Only when arity is exactly 1 do we read that one child.
1773        match self.node_ref(node) {
1774            NodeRef::MSet(l) => {
1775                let n = self.nodes.mset.get(l);
1776                let (s, e) = n.span();
1777                match e - s {
1778                    0 => self.unit_node(self.node_op(node)).map(|u| (node, u)),
1779                    1 => {
1780                        let c = self.nodes.mset.pool_get(s);
1781                        // Size-1 collapses to the child only at multiplicity 1 (`{a:2}` is not a
1782                        // degenerate `a`; for a nilpotent op it would already have clamped to `{}`).
1783                        (Cfg::mset_child_mult(&c) == Cfg::M::ONE)
1784                            .then(|| (node, Cfg::mset_child_id(&c)))
1785                    }
1786                    _ => None,
1787                }
1788            }
1789            NodeRef::Set(l) => {
1790                let n = self.nodes.set.get(l);
1791                let (s, e) = n.span();
1792                match e - s {
1793                    0 => self.unit_node(self.node_op(node)).map(|u| (node, u)),
1794                    1 => Some((node, self.nodes.set.pool_get(s))),
1795                    _ => None,
1796                }
1797            }
1798            _ => None,
1799        }
1800    }
1801
1802    /// Recanonize one parent node — find-canonicalize its children and apply the op's
1803    /// algebraic canonization laws (count clamp, identity unit-drop) — and record any
1804    /// resulting hash-cons collision or degenerate-arity merge into `self.collisions`.
1805    /// Shared by the absorbed-uses sweep and the became-a-unit sweep in
1806    /// [`rebuild_congruence`](Self::rebuild_congruence).
1807    fn recanonize_parent(&mut self, parent: Cfg::G) {
1808        let find = |g: Cfg::G| self.classes.find_const(g);
1809        // The op's identity as a *class* under the current union-find: recanonize drops it
1810        // from MSet/Set children (`f(x,e) = x`), so a summand that merged into the unit's
1811        // class after the node was built is dropped exactly as it would have been at build
1812        // (Kapur Lemma 4.3's normalization assumption). Field-precise captures keep the
1813        // borrows disjoint from `self.nodes`.
1814        let units = &self.unit_node;
1815        let classes = &self.classes;
1816        let unit_of = |op: Cfg::O| {
1817            units
1818                .get_by_key(&op)
1819                .copied()
1820                .map(|u| classes.find_const(u))
1821        };
1822        self.nodes.recanonize_node(
1823            parent,
1824            find,
1825            unit_of,
1826            &mut self.g_buf,
1827            &mut self.mset_buf,
1828            &mut self.collisions,
1829            &mut self.touched,
1830            &self.ops,
1831        );
1832        // Canonization can shrink an MSet/Set node to a degenerate arity (a child merge
1833        // pushes a nilpotent count to 0, or coalesces/drops to a single summand): the node
1834        // then *equals* an existing class — empty ⇒ the unit, size-1 mult-1 ⇒ that child.
1835        // Recanonize (representation) can't express that equality, so record it as a merge
1836        // here (the congruence layer), alongside the hash-cons collisions. `and(a,b)` after
1837        // `a=b` becomes `{a}` = `a`; `xor(a,b)` after `a=b` becomes `{}` = the unit.
1838        if let Some(pair) = self.degeneracy_merge(parent) {
1839            self.collisions.push(pair);
1840        }
1841    }
1842
1843    /// Ordinary worklist-driven congruence closure: drain the merge worklist,
1844    /// recanonicalizing the parents of each absorbed class and merging the
1845    /// resulting hash-cons collisions, to a fixpoint.
1846    fn rebuild_congruence(&mut self) {
1847        while let Some((absorbed_uses, survivor)) = self.worklist.pop() {
1848            self.collisions.clear();
1849            // Hot path: iterate the absorbed use list directly (no allocation). The body
1850            // mirrors `recanonize_parent` — it cannot be a method call here because the
1851            // use-list iterator holds `self.classes` for the whole loop, and only inline
1852            // field-disjoint borrows split around it.
1853            for parent in self.classes.uses().iter(absorbed_uses) {
1854                let find = |g: Cfg::G| self.classes.find_const(g);
1855                let units = &self.unit_node;
1856                let classes = &self.classes;
1857                let unit_of = |op: Cfg::O| {
1858                    units
1859                        .get_by_key(&op)
1860                        .copied()
1861                        .map(|u| classes.find_const(u))
1862                };
1863                self.nodes.recanonize_node(
1864                    parent,
1865                    find,
1866                    unit_of,
1867                    &mut self.g_buf,
1868                    &mut self.mset_buf,
1869                    &mut self.collisions,
1870                    &mut self.touched,
1871                    &self.ops,
1872                );
1873                if let Some(pair) = self.degeneracy_merge(parent) {
1874                    self.collisions.push(pair);
1875                }
1876            }
1877
1878            let current_surv = self.classes.find_const(survivor);
1879            let surv_repr = self.classes.repr_id(current_surv).unwrap();
1880            let surv_list = self.classes.use_list_id(surv_repr);
1881            self.classes.splice_uses(surv_list, absorbed_uses);
1882
1883            // If this merge made the merged class an op's identity (unit) class, the
1884            // unit-drop law now applies to EVERY parent holding this class as a summand —
1885            // including parents on the *surviving* side, which the absorbed-uses sweep
1886            // never visits (their children's `find` did not change; their canonization
1887            // mode did). Sweep the full spliced use list; parents that are already
1888            // canonical early-return inside recanonize. Rare path (a class becomes a unit
1889            // class at most once per op), so the scratch collection is acceptable.
1890            let merged_is_unit = {
1891                let units = &self.unit_node;
1892                let classes = &self.classes;
1893                self.ops.mset_ops().chain(self.ops.set_ops()).any(|op| {
1894                    units
1895                        .get_by_key(&op)
1896                        .copied()
1897                        .is_some_and(|u| classes.find_const(u) == current_surv)
1898                })
1899            };
1900            if merged_is_unit {
1901                let parents: Vec<Cfg::G> = self.classes.uses().iter(surv_list).collect();
1902                for parent in parents {
1903                    self.recanonize_parent(parent);
1904                }
1905            }
1906
1907            for i in 0..self.collisions.len() {
1908                let (a, b) = self.collisions[i];
1909                let m = if PROOFS {
1910                    self.merge_in_classes(
1911                        a,
1912                        b,
1913                        Some(Justification::Congruence {
1914                            node_a: a,
1915                            node_b: b,
1916                        }),
1917                    )
1918                } else {
1919                    self.merge_in_classes(a, b, None)
1920                };
1921                if let Some(m) = m {
1922                    self.fold_min_monomial(m.survivor, m.absorbed_min_row, m.absorbed_atomic);
1923                    self.worklist.push((m.absorbed_uses, m.survivor));
1924                }
1925            }
1926        }
1927    }
1928
1929    /// One A-only (`Seq`) inter-reduction round: the transfer of the AC
1930    /// repair to associativity-only operators, run inside the same completion
1931    /// loop (so only when completion is enabled — plain mode is untouched and
1932    /// its node counts stand).
1933    ///
1934    /// The gap it closes: build-time flattening splices a pure-`op`-sequence
1935    /// child into its parents, erasing the class reference, and a class can
1936    /// never *become* pure late (merges only add members, and an atom member
1937    /// never leaves) — so the one way an A-equation escapes congruence is two
1938    /// pure-sequence classes merging. That class then holds two distinct
1939    /// `op`-sequence spellings: a ground string equation `seq_1 = seq_2` that
1940    /// parents which spliced different spellings cannot see. Each such
1941    /// equation is oriented shortlex (longer to shorter, ties by element ids)
1942    /// and contiguous occurrences of the larger spelling inside other
1943    /// `op`-sequences are rewritten: the rewritten sequence is added and
1944    /// merged with its source, justification `ACInterReduction` (the same
1945    /// sub-term-for-class substitution shape as the AC case).
1946    ///
1947    /// Every rewrite is shortlex-decreasing, so a round terminates, and the
1948    /// loop above drains rounds to a joint fixpoint under the same budget and
1949    /// goal polls as the AC pass. **Deliberately no critical-pair chase**:
1950    /// completing a ground string system is Knuth-Bendix on a semi-Thue
1951    /// system, and the word problem for finitely presented monoids is
1952    /// undecidable — unlike the AC side, where Dickson's Lemma bounds the
1953    /// basis, there is no completeness theorem to aim for. This pass closes
1954    /// the single-substitution gap (the erased-reference case above) and
1955    /// stops; what it derives is sound, what it misses is documented.
1956    fn a_round(&mut self) -> bool {
1957        use crate::containers::DenseId;
1958        use crate::typed_routing::NodeIds;
1959        let n_seq = self.nodes.seq.len().to_usize();
1960        if n_seq == 0 {
1961            return false;
1962        }
1963        // (op, class) -> the class's `op`-sequence spellings.
1964        let mut groups: std::collections::HashMap<(Cfg::O, Cfg::G), Vec<Cfg::G>> =
1965            std::collections::HashMap::new();
1966        for i in 0..n_seq {
1967            let l = <Cfg::Ids as NodeIds>::LSeq::from_usize(i);
1968            let g = self.nodes.seq.get(l).global_id();
1969            let cls = self.classes.find_const(g);
1970            groups.entry((self.node_op(g), cls)).or_default().push(g);
1971        }
1972        // Oriented rules: larger spelling -> the class's shortlex-least one.
1973        let mut rules: Vec<(Cfg::O, Vec<Cfg::G>, Vec<Cfg::G>)> = Vec::new();
1974        let mut buf: Vec<Cfg::G> = Vec::new();
1975        for ((op, _cls), nodes) in groups.iter().filter(|(_, v)| v.len() > 1) {
1976            let mut spellings: Vec<Vec<Cfg::G>> = Vec::with_capacity(nodes.len());
1977            for &n in nodes {
1978                self.seq_children(n, &mut buf);
1979                for e in buf.iter_mut() {
1980                    *e = self.classes.find_const(*e);
1981                }
1982                spellings.push(buf.clone());
1983            }
1984            let least = spellings
1985                .iter()
1986                .min_by(|a, b| shortlex(a, b))
1987                .expect("non-empty spelling group")
1988                .clone();
1989            for elems in spellings {
1990                if shortlex(&elems, &least) == std::cmp::Ordering::Greater {
1991                    rules.push((*op, elems, least.clone()));
1992                }
1993            }
1994        }
1995        if rules.is_empty() {
1996            return false;
1997        }
1998        // Rewrite pass over the round-start sequences (nodes added below are
1999        // visited next round). One rewrite per node per round: the fixpoint
2000        // loop supplies the iteration.
2001        let mut changed = false;
2002        let mut new_children: Vec<Cfg::G> = Vec::new();
2003        for i in 0..n_seq {
2004            if self.cc_should_stop() {
2005                break;
2006            }
2007            let l = <Cfg::Ids as NodeIds>::LSeq::from_usize(i);
2008            let g = self.nodes.seq.get(l).global_id();
2009            let g_op = self.node_op(g);
2010            self.seq_children(g, &mut buf);
2011            for e in buf.iter_mut() {
2012                *e = self.classes.find_const(*e);
2013            }
2014            for (op, lhs, rhs) in &rules {
2015                if *op != g_op || lhs.len() > buf.len() {
2016                    continue;
2017                }
2018                let Some(s) =
2019                    (0..=buf.len() - lhs.len()).find(|&s| &buf[s..s + lhs.len()] == lhs.as_slice())
2020                else {
2021                    continue;
2022                };
2023                new_children.clear();
2024                new_children.extend_from_slice(&buf[..s]);
2025                new_children.extend_from_slice(rhs);
2026                new_children.extend_from_slice(&buf[s + lhs.len()..]);
2027                let nid = self.add(*op, &new_children);
2028                if self.classes.find_const(nid) != self.classes.find_const(g) {
2029                    let m = if PROOFS {
2030                        self.merge_justified(
2031                            g,
2032                            nid,
2033                            Justification::ACInterReduction {
2034                                node_a: g,
2035                                node_b: nid,
2036                            },
2037                        )
2038                    } else {
2039                        self.merge(g, nid)
2040                    };
2041                    changed |= m.is_some();
2042                }
2043                break;
2044            }
2045        }
2046        changed
2047    }
2048
2049    /// One AC congruence-completion round (Kapur FSCD 2021 Algorithm 1, the steps our
2050    /// rebuild otherwise omits). Returns `true` if it scheduled any new merge.
2051    ///
2052    /// Reading each non-subsumed AC node `+M = d` as a ground rule `+M → d`,
2053    /// for each pair of partners found through the class use-lists (same op,
2054    /// sharing ≥1 child class):
2055    ///
2056    /// - **(A) inter-reduction + Collapse** — if `A ⊊ M`, the sub-sum `+A` equals `a`,
2057    ///   so the residual `(M − A) ⊎ {a}`, **normalized to a fixpoint**, equals `d`:
2058    ///   merge, then **mark `+M` subsumed** so it leaves the active set. The collapse
2059    ///   is intended to maintain the active-rule antichain required by the conditional
2060    ///   Dickson argument (design doc §6b).
2061    /// - **(B) superposition** — if `A` and `M` overlap but neither contains the other,
2062    ///   build the lcm `AB`, **normalize both reducts** `(AB−M)⊎{d}` and `(AB−A)⊎{a}`
2063    ///   to normal form, and merge if they still differ (design doc §4b, §6 (B)).
2064    ///
2065    /// Disjoint partners are skipped (trivial critical pair). The crucial corrections
2066    /// over a naïve materialize-and-merge (design §6b): every reduct is reduced to
2067    /// **normal form before** being materialized (a raw reduct can be a superset of an
2068    /// existing rule's LHS, hence itself reducible, and would persist as a runaway
2069    /// superposition source), and reducible source rules are **collapsed** (subsumed).
2070    ///
2071    /// Completion collapse is the non-deletable form of Kapur/Conchon's rule retirement:
2072    /// the node and the equality it established stay in the DAG, but completion's
2073    /// active-rule projection skips it, so it is no longer a completion partner.
2074    /// `FLAG_AC_COLLAPSED` does not remove the node from matching; user-level
2075    /// `FLAG_SUBSUMED` does.
2076    /// One AC completion round. Superposition (B) is incremental (S3b): when `full` is
2077    /// false, only critical pairs with ≥1 endpoint among the *delta rules* (nodes touched
2078    /// in `self.touched[delta_lo..delta_hi]`, i.e. created or recanonicalized since the
2079    /// previous round) are generated. A later full round rechecks every pair, including
2080    /// old×old pairs whose effective RHS changed without touching their node. `full`
2081    /// generates every pair. The (A′)
2082    /// collapse/normalize pass and the antichain `reducible` check stay full scans: a small
2083    /// new rule must still be able to collapse a large old one.
2084    fn cc_round(&mut self, full: bool, delta_lo: usize, delta_hi: usize) -> bool {
2085        use crate::multiset::{
2086            NfIndex, NfRuleRef, NfRules, multiset_disjoint, multiset_lcm_into, multiset_subset,
2087            multiset_subtract_into, multiset_union, normalize_ms_into, normalize_nilpotent_into,
2088            normalize_set_into,
2089        };
2090
2091        // Canonical monomial of a completion node as sorted (class-repr, mult): coalesced
2092        // multiplicities for an MSet op, deduped set (all mult 1) for a Set (ACI) op.
2093        // Delegates to `node_monomial_into`, which dispatches on the node's representation.
2094        let multiset_of = |eg: &Self, id: Cfg::G| -> Vec<(Cfg::G, Cfg::M)> {
2095            let mut out = Vec::new();
2096            eg.node_monomial_into(id, &mut out);
2097            out
2098        };
2099
2100        use crate::multiset::monomial_cmp;
2101        use crate::node_types::{FLAG_AC_COLLAPSED, FLAG_SUBSUMED};
2102
2103        // Completion's active set excludes nodes that are user-subsumed (not matchable)
2104        // OR AC-collapsed (reducible by a smaller rule). Either way they are not rules.
2105        let inactive = FLAG_SUBSUMED | FLAG_AC_COLLAPSED;
2106
2107        // Each active AC node is a candidate rule `+M → rhs(class)`, where the RHS comes
2108        // from the per-class slot (`class_rhs_into`: `{class}` if atomic, else the stored
2109        // `min_monomial` monomial, §9a) — not recomputed per round. The orientation guard keeps
2110        // only nodes whose own monomial `M` is strictly `≫_f`-greater than that RHS: those
2111        // are the currently oriented rules (a node equal to the maintained class candidate
2112        // is no rule, and a
2113        // mis-oriented `M ≺ rhs` is dropped, §9b axis-2a). `node` lets us collapse it.
2114        struct Rule<G, O, M> {
2115            /// The typed op id, not a widened `usize` copy of one. Storing the id itself
2116            /// keeps the row at the config's op width and — more to the point — leaves
2117            /// nothing to re-mint: the round used to spend a masking
2118            /// `Cfg::O::from_usize` per rule to undo a `to_usize` performed a few lines
2119            /// above, and only the op's own registration bound kept that honest.
2120            op: O,
2121            lhs: Vec<(G, M)>,
2122            rhs: Vec<(G, M)>,
2123            node: G,
2124        }
2125        let mut rules: Vec<Rule<Cfg::G, Cfg::O, Cfg::M>> = Vec::new();
2126        let mut rhs_buf: Vec<(Cfg::G, Cfg::M)> = Vec::new();
2127        // Iterate the AC node partition directly (ascending global id), not all nodes: the
2128        // `is_mset` filter is implicit and the non-AC majority is never visited.
2129        for gid in self.completion_node_ids() {
2130            if self.node_flags(gid) & inactive != 0 {
2131                continue;
2132            }
2133            let op = self.node_op(gid);
2134            let lhs = multiset_of(self, gid);
2135            if !self.class_rhs_into(gid, &mut rhs_buf) {
2136                continue;
2137            }
2138            // Read-time orientation guard (§9b): only `M ≫ rhs` is a rule.
2139            if monomial_cmp(&lhs, &rhs_buf) == std::cmp::Ordering::Greater {
2140                rules.push(Rule {
2141                    op,
2142                    lhs,
2143                    rhs: rhs_buf.clone(),
2144                    node: gid,
2145                });
2146            }
2147        }
2148        // Dedup the reducer/superposition set by (op, LHS). Congruent AC nodes can
2149        // recanonicalize to the same monomial after a child merge without being hash-consed
2150        // into one node, so the same rule `+M → r` appears as several nodes. Kapur step 2
2151        // discards a duplicate equation and keeps one; here we keep the lowest-node-id copy
2152        // as the canonical rule and drop the rest from `rules`. This is what makes the active
2153        // set Kapur-*reduced* (no LHS reducible by another's), not merely a strict-containment
2154        // antichain: identical-LHS copies were the whole measured gap between `reducible_pairs`
2155        // and the ground-truth `kapur_lhs_reducible` (ac_invariants). The dropped copies are
2156        // NOT lost: they remain in `targets`, so (A′) still collapses each (its monomial
2157        // reduces to the shared RHS via the kept rule) and still merges any differing-RHS copy
2158        // (the implied equality fires through `targets`, not `rules`). Without the dedup, every
2159        // copy reduces every other copy, so they mutually collapse and the rule vanishes
2160        // entirely (the §6b "merge before mark" / self-reduction hazard, at the set level).
2161        // Clone-free: sort by (op, lhs, node) with borrowed
2162        // comparisons, drop adjacent (op, lhs) duplicates keeping the first (= lowest node
2163        // id), then restore node order for the (B) binary search.
2164        rules.sort_unstable_by(|x, y| {
2165            x.op.cmp(&y.op)
2166                .then_with(|| x.lhs.cmp(&y.lhs))
2167                .then_with(|| x.node.cmp(&y.node))
2168        });
2169        rules.dedup_by(|later, earlier| later.op == earlier.op && later.lhs == earlier.lhs);
2170
2171        // The (B) partner search binary-searches `rules` by global node id, so it must be
2172        // sorted by `node`. Distinct nodes ⇒ strictly sorted.
2173        rules.sort_unstable_by_key(|r| r.node);
2174        debug_assert!(rules.windows(2).all(|w| w[0].node < w[1].node));
2175
2176        // Delta rule-node set for incremental (B): sorted, dedup'd node ids touched since
2177        // the previous round. `touched` may contain duplicates; sort+dedup once, then test
2178        // a rule's membership by binary search (mirrors the `rules` binary-search idiom).
2179        let delta: Vec<Cfg::G> = if full {
2180            Vec::new()
2181        } else {
2182            let mut d: Vec<Cfg::G> = self.touched[delta_lo..delta_hi].to_vec();
2183            d.sort_unstable();
2184            d.dedup();
2185            d
2186        };
2187        let in_delta = |n: Cfg::G| -> bool { full || delta.binary_search(&n).is_ok() };
2188
2189        // Reducibility flag per rule: a rule whose LHS strictly contains another rule's LHS
2190        // (same op) is reducible by it, so collapse will retire it. Kapur superposes only
2191        // over the inter-reduced *antichain*, never over a reducible rule (FSCD'21 Algo 1:
2192        // collapse before superpose). The batch round collapses these only on the *next*
2193        // round, so excluding them as (B) sources/partners here is what keeps the active
2194        // set an antichain within the round and stops the critical-pair blowup.
2195        // O(rules²) over the small active set; acceptable while the worklist rewrite (S3b)
2196        // is pending.
2197        let phase_time = std::env::var_os("AC_PHASE_TIME").is_some();
2198        let t_reducible = std::time::Instant::now();
2199        let reducible: Vec<bool> = (0..rules.len())
2200            .map(|i| {
2201                rules.iter().enumerate().any(|(j, rj)| {
2202                    j != i
2203                        && rj.op == rules[i].op
2204                        && rj.lhs != rules[i].lhs
2205                        && multiset_subset(&rj.lhs, &rules[i].lhs)
2206                })
2207            })
2208            .collect();
2209        let dt_reducible = t_reducible.elapsed();
2210
2211        // Expand a multiset to a flat child list into a reused scratch; `add` re-sorts and
2212        // re-coalesces. The expansion (O(total count), not O(distinct summands)) stays for
2213        // now: `add`'s whole canonize pipeline — flatten, unit-drop, clamp, degeneracy —
2214        // operates on child lists, and counts are bounded by the lcm of existing monomials.
2215        // A pair-based `add` entry could multiply multiplicities through the splice
2216        // without materializing repeated children.
2217        let mut mat_buf: Vec<Cfg::G> = Vec::new();
2218        let materialize =
2219            |eg: &mut Self, op: Cfg::O, ms: &[(Cfg::G, Cfg::M)], buf: &mut Vec<Cfg::G>| {
2220                buf.clear();
2221                for (g, mult) in ms {
2222                    for _ in 0..mult.to_usize() {
2223                        buf.push(*g);
2224                    }
2225                }
2226                eg.add(op, buf)
2227            };
2228        let do_merge = |eg: &mut Self, x: Cfg::G, y: Cfg::G, just: Justification<Cfg::G>| -> bool {
2229            if eg.classes.find_const(x) == eg.classes.find_const(y) {
2230                return false;
2231            }
2232            let m = if PROOFS {
2233                eg.merge_in_classes(x, y, Some(just))
2234            } else {
2235                eg.merge_in_classes(x, y, None)
2236            };
2237            match m {
2238                Some(m) => {
2239                    eg.fold_min_monomial(m.survivor, m.absorbed_min_row, m.absorbed_atomic);
2240                    eg.worklist.push((m.absorbed_uses, m.survivor));
2241                    true
2242                }
2243                None => false,
2244            }
2245        };
2246
2247        // Collect work over pairs of rules (same op), then apply (so the rule set we
2248        // normalize against does not shift mid-scan). Superposition (B) and collapse (A)
2249        // both range over *rules*: Kapur superposes/inter-reduces rule left sides, and a
2250        // class's minimal monomial (a normal form) is never a rule, so it cannot be a
2251        // source or a collapse target. The search ranges over the `rules` Vec directly
2252        // (already the small active set), via an all-pairs loop.
2253        //   targets — (A): collapse a node's class into its residual's normal form.
2254        //   crit    — (B): merge the normal forms of the two lcm reducts.
2255        // Each critical pair carries its ORIGIN so the close-time merge records the
2256        // faithful proof justification (pairwise superposition vs. per-rule semantic
2257        // axiom CP vs. cancelative closure) instead of a catch-all label.
2258        #[derive(Clone, Copy)]
2259        enum CpOrigin {
2260            Superposition,
2261            AxiomCp,
2262            Cancellative,
2263        }
2264        let mut crit: Vec<(
2265            Cfg::O,
2266            CpOrigin,
2267            Vec<(Cfg::G, Cfg::M)>,
2268            Vec<(Cfg::G, Cfg::M)>,
2269        )> = Vec::new();
2270
2271        // (A′) Normalize every active monomial node against the rules and merge its
2272        // normal form back in (Kapur Algo 2 step 2, "normalize Sf"). This subsumes plain
2273        // inter-reduction (A): a node +{a,b,neg(c)} with rule +{a,b}→{c} reduces to
2274        // +{c,neg(c)}, which is *materialized* so the ordinary matcher reaches it
2275        // (design §5b). `(op, monomial, class, node, is_rule)`: a node that was itself a
2276        // rule (its own LHS reducible) is collapsed/subsumed after the merge (design §6b).
2277        let t_gen = std::time::Instant::now();
2278        let mut targets: Vec<(Cfg::O, Vec<(Cfg::G, Cfg::M)>, Cfg::G, Cfg::G, bool)> = Vec::new();
2279        // AC partition only, same as the rules scan (no full-graph walk, no `is_mset` filter).
2280        for gid in self.completion_node_ids() {
2281            if self.node_flags(gid) & inactive != 0 {
2282                continue;
2283            }
2284            let op = self.node_op(gid);
2285            targets.push((
2286                op,
2287                multiset_of(self, gid),
2288                self.classes.find_const(gid),
2289                gid,
2290                rules.iter().any(|r| r.node == gid),
2291            ));
2292        }
2293
2294        // (B) Superposition critical pairs over pairs of *rules* sharing ≥1 child class,
2295        // neither containing the other (overlap). Partners are found via the use-lists
2296        // (`iter_uses`), not an O(rules²) all-pairs scan: a partner of rule `+M` must
2297        // share a child with `M`, so it appears in some `iter_uses(x)` for `x ∈ M`. `rules`
2298        // is built in node-id order, so it is sorted by `node`; look a partner's rule up by
2299        // binary search (no map, no per-round allocation). Each unordered pair is processed
2300        // once (`ti.node < partner.node`). Both reducts are normalized before merge.
2301        let mut partner_buf: Vec<Cfg::G> = Vec::new();
2302        // Reusable temporaries for the (B) reduct arithmetic: the
2303        // lcm and residual are per-pair scratch; only the stored reducts (`crit` entries)
2304        // allocate. Grown once, reused across every pair.
2305        let mut ab_buf: Vec<(Cfg::G, Cfg::M)> = Vec::new();
2306        let mut sub_buf: Vec<(Cfg::G, Cfg::M)> = Vec::new();
2307        let mut delta_skipped = 0usize;
2308        let delta_in_rules = rules.iter().filter(|r| in_delta(r.node)).count();
2309        for ti in 0..rules.len() {
2310            // A reducible rule is not a member of the antichain: collapse will retire it,
2311            // so it must not seed critical pairs.
2312            if reducible[ti] {
2313                continue;
2314            }
2315            let op = rules[ti].op;
2316            let m_node = rules[ti].node;
2317
2318            // Per-rule axiom critical pairs (Kapur §4): superpose the rule with
2319            // the op's own semantic axiom. The count clamp canonizes counts
2320            // *within* a monomial but cannot produce these cross-rule consequences — e.g.
2321            // or(a,b)=c ⟹ or(a,c)=c, and xor(a,b)=c ⟹ xor(a,c)=b — so without these
2322            // pairs completion is incomplete (Lemmas 4.1(ii), 4.2(ii)/4.5). Generated for
2323            // antichain members only (like (B) sources), when the rule is in the delta;
2324            // the full confirmation round is the completeness net, as for (B).
2325            if in_delta(m_node) {
2326                match self.op_clamp(op) {
2327                    CompletionClamp::Idempotent => {
2328                        // x∘x = x: for each a ∈ M, the pair (N ⊎ {a}, N). Since M → N by
2329                        // the rule itself, joinability of Kapur's (f(M), f(N∪{a})) reduces
2330                        // to exactly this pair. a ∈ N clamps to N — trivial, skip early.
2331                        for &(a, _) in &rules[ti].lhs {
2332                            let mut r1 = crate::multiset::multiset_union(
2333                                &rules[ti].rhs,
2334                                &[(a, Cfg::M::ONE)],
2335                            );
2336                            crate::multiset::clamp_idempotent(&mut r1);
2337                            if r1 != rules[ti].rhs {
2338                                crit.push((op, CpOrigin::AxiomCp, r1, rules[ti].rhs.clone()));
2339                            }
2340                        }
2341                    }
2342                    CompletionClamp::Nilpotent { order } => {
2343                        // xⁿ = e: for a with multiplicity m in M, superpose M with aⁿ → e
2344                        // on the lcm M ⊎ {a: n−m}. The rule reduct is N ⊎ {a: n−m}; the
2345                        // axiom reduct is (M − {a: m}) ⊎ {e}, whose unit drops (stored
2346                        // monomials never carry the unit). At n=2, m=1 this is literally
2347                        // Kapur's (f(N ∪ {a}), f((M − {a}) ∪ {e})).
2348                        for &(a, m) in &rules[ti].lhs {
2349                            // `order` is a `u8`, so the deficit is below 256 and
2350                            // representable at every supported multiplicity width.
2351                            let ord = Cfg::M::try_from_u64(u64::from(order))
2352                                .expect("a u8 nilpotent order fits every multiplicity width");
2353                            let k = ord.saturating_sub(m);
2354                            if k == Cfg::M::ZERO {
2355                                continue; // m ≡ 0 (mod n) never stored; defensive
2356                            }
2357                            let mut r1 = crate::multiset::multiset_union(&rules[ti].rhs, &[(a, k)]);
2358                            crate::multiset::clamp_nilpotent(&mut r1, order);
2359                            let r2 = crate::multiset::multiset_subtract(&rules[ti].lhs, &[(a, m)]);
2360                            crit.push((op, CpOrigin::AxiomCp, r1, r2));
2361                        }
2362                    }
2363                    CompletionClamp::Multiset => {} // plain AC / identity-only: none (Lemma 4.3)
2364                }
2365            }
2366
2367            // Gather candidate partner nodes from the use-lists of M's distinct children.
2368            partner_buf.clear();
2369            for &(x, _) in &rules[ti].lhs {
2370                if let Some(x_repr) = self.classes.repr_id(self.classes.find_const(x)) {
2371                    for p in self.classes.iter_uses(x_repr) {
2372                        partner_buf.push(p);
2373                    }
2374                }
2375            }
2376            partner_buf.sort_unstable();
2377            partner_buf.dedup();
2378
2379            for k in 0..partner_buf.len() {
2380                let p_node = partner_buf[k];
2381                // Process each unordered pair once; skip self.
2382                if p_node <= m_node {
2383                    continue;
2384                }
2385                if self.node_flags(p_node) & inactive != 0 || self.node_op(p_node) != op {
2386                    continue;
2387                }
2388                // The partner must itself be a rule: binary-search the sorted `rules`.
2389                let Ok(pi) = rules.binary_search_by(|r| r.node.cmp(&p_node)) else {
2390                    continue;
2391                };
2392                // ...and a member of the antichain (a reducible partner will be collapsed).
2393                if reducible[pi] {
2394                    continue;
2395                }
2396                // Incremental (B): an unordered pair is a *new* critical pair only if at
2397                // least one of its rules changed since the previous round (S3b). When
2398                // neither endpoint is in the delta the pair was closed in an earlier round
2399                // and stays closed; skip it. `full` (round 0) makes `in_delta` always true.
2400                if !in_delta(m_node) && !in_delta(p_node) {
2401                    delta_skipped += 1;
2402                    continue;
2403                }
2404                let m = &rules[ti].lhs;
2405                let a = &rules[pi].lhs;
2406                // Shared by construction; skip the non-overlap / containment cases
2407                // (containment is handled by the (A′) normalize pass).
2408                debug_assert!(!multiset_disjoint(a, m));
2409                if multiset_subset(a, m) || multiset_subset(m, a) {
2410                    continue;
2411                }
2412                multiset_lcm_into(&mut ab_buf, m, a);
2413                multiset_subtract_into(&mut sub_buf, &ab_buf, m);
2414                let mut r1 = multiset_union(&sub_buf, &rules[ti].rhs);
2415                multiset_subtract_into(&mut sub_buf, &ab_buf, a);
2416                let mut r2 = multiset_union(&sub_buf, &rules[pi].rhs);
2417                // Clamp the reducts to the op's normal-form count domain before the pair is
2418                // closed: idempotent → {0,1} (ACI union), nilpotent → mod-n (symmetric
2419                // difference). Multiset (plain AC) keeps ℕ counts, no clamp.
2420                match self.op_clamp(op) {
2421                    CompletionClamp::Idempotent => {
2422                        crate::multiset::clamp_idempotent(&mut r1);
2423                        crate::multiset::clamp_idempotent(&mut r2);
2424                    }
2425                    CompletionClamp::Nilpotent { order } => {
2426                        crate::multiset::clamp_nilpotent(&mut r1, order);
2427                        crate::multiset::clamp_nilpotent(&mut r2, order);
2428                    }
2429                    CompletionClamp::Multiset => {}
2430                }
2431                crit.push((op, CpOrigin::Superposition, r1, r2));
2432            }
2433        }
2434
2435        // ── Cancelative facet (Kapur §5) ──
2436        // (C1) Cancel-close every antichain rule of a cancelative op (§5.2): a rule
2437        // f(M) → f(R) is an equation; canceling the common part C = M ∩ R entails
2438        // f(M−C) = f(R−C). (C2) Cancelative disjoint superposition (§5.3): for two rules
2439        // of the same cancelative op, the disjoint join f(M₁⊎M₂) = f(R₁⊎R₂) may not be
2440        // cancelatively closed; its cancel-closure yields further critical pairs (Kapur's
2441        // SC2/SC3 examples — without these, orienting the input equations is canonical but
2442        // NOT a cancelative congruence closure, Thm 5.1/5.2).
2443        //
2444        // Empty-side policy after canceling: with a declared identity the empty side IS
2445        // the unit (f({}) = e) and the pair closes against it. Without one, Kapur's
2446        // §5.2(iii)(b) applies: an equation f(A) = f(B) whose cancelation empties one side
2447        // entails f((A−B) ∪ {c}) = f({c}) for EVERY constant c (his SC2 derives
2448        // f(a,a,b) = a this way). Kapur's constant set C is fixed by purification; ours is
2449        // incremental, so the closure is generated over the op's CURRENT summand pool (the
2450        // distinct classes appearing in its active monomials) — a class that appears later
2451        // is covered by the full confirmation round that sees it, the same net that covers
2452        // every other delta miss.
2453        let cancel_close = |a: &[(Cfg::G, Cfg::M)],
2454                            b: &[(Cfg::G, Cfg::M)]|
2455         -> Option<(Vec<(Cfg::G, Cfg::M)>, Vec<(Cfg::G, Cfg::M)>)> {
2456            let c = crate::multiset::multiset_intersect(a, b);
2457            if c.is_empty() {
2458                return None;
2459            }
2460            Some((
2461                crate::multiset::multiset_subtract(a, &c),
2462                crate::multiset::multiset_subtract(b, &c),
2463            ))
2464        };
2465        // The op's summand pool, for the per-constant closure (computed only when an
2466        // empty-side cancelation actually occurs — rare).
2467        let summand_pool = |targets: &[(Cfg::O, Vec<(Cfg::G, Cfg::M)>, Cfg::G, Cfg::G, bool)],
2468                            want: Cfg::O|
2469         -> Vec<Cfg::G> {
2470            let mut pool: Vec<Cfg::G> = targets
2471                .iter()
2472                .filter(|t| t.0 == want)
2473                .flat_map(|t| t.1.iter().map(|p| p.0))
2474                .collect();
2475            pool.sort_unstable();
2476            pool.dedup();
2477            pool
2478        };
2479        let push_cancel = |crit: &mut Vec<(
2480            Cfg::O,
2481            CpOrigin,
2482            Vec<(Cfg::G, Cfg::M)>,
2483            Vec<(Cfg::G, Cfg::M)>,
2484        )>,
2485                           op: Cfg::O,
2486                           has_unit: bool,
2487                           pool: &[Cfg::G],
2488                           m: Vec<(Cfg::G, Cfg::M)>,
2489                           r: Vec<(Cfg::G, Cfg::M)>| {
2490            if (!m.is_empty() && !r.is_empty()) || has_unit {
2491                crit.push((op, CpOrigin::Cancellative, m, r));
2492            } else {
2493                // §5.2(iii)(b): f(ne ∪ {c}) = f({c}) for every constant c in the pool.
2494                let ne = if m.is_empty() { r } else { m };
2495                for &g in pool {
2496                    let one = [(g, Cfg::M::ONE)];
2497                    crit.push((
2498                        op,
2499                        CpOrigin::Cancellative,
2500                        crate::multiset::multiset_union(&ne, &one),
2501                        one.to_vec(),
2502                    ));
2503                }
2504            }
2505        };
2506        for ti in 0..rules.len() {
2507            if reducible[ti] {
2508                continue;
2509            }
2510            let op = rules[ti].op;
2511            if !self.op_cancellative(op) {
2512                continue;
2513            }
2514            let has_unit = self.unit_node(op).is_some();
2515            // Lazily computed at most once per rule that needs it; empty-side cases are rare.
2516            let mut pool: Option<Vec<Cfg::G>> = None;
2517            let pool_ref = |pool: &mut Option<Vec<Cfg::G>>| -> Vec<Cfg::G> {
2518                pool.get_or_insert_with(|| summand_pool(&targets, op))
2519                    .clone()
2520            };
2521            // (C1) — regenerated when the rule is in the delta; the full confirmation
2522            // round is the completeness net, as for (B) and the axiom pairs.
2523            if in_delta(rules[ti].node)
2524                && let Some((m, r)) = cancel_close(&rules[ti].lhs, &rules[ti].rhs)
2525            {
2526                let needs_pool = (m.is_empty() || r.is_empty()) && !has_unit;
2527                let pl = if needs_pool {
2528                    pool_ref(&mut pool)
2529                } else {
2530                    Vec::new()
2531                };
2532                push_cancel(&mut crit, op, has_unit, &pl, m, r);
2533            }
2534            // (C2) cancelative disjoint superposition — each unordered same-op antichain
2535            // pair once. O(rules²) but only over the (rare) cancelative ops' rules.
2536            for pj in ti + 1..rules.len() {
2537                if reducible[pj] || rules[pj].op != rules[ti].op {
2538                    continue;
2539                }
2540                if !in_delta(rules[ti].node) && !in_delta(rules[pj].node) {
2541                    continue;
2542                }
2543                let u1 = crate::multiset::multiset_union(&rules[ti].lhs, &rules[pj].lhs);
2544                let u2 = crate::multiset::multiset_union(&rules[ti].rhs, &rules[pj].rhs);
2545                if let Some((m, r)) = cancel_close(&u1, &u2) {
2546                    let needs_pool = (m.is_empty() || r.is_empty()) && !has_unit;
2547                    let pl = if needs_pool {
2548                        pool_ref(&mut pool)
2549                    } else {
2550                        Vec::new()
2551                    };
2552                    push_cancel(&mut crit, op, has_unit, &pl, m, r);
2553                }
2554            }
2555        }
2556
2557        // Critical-pair reducts are normalized to multisets (each step strictly lowers the
2558        // multiset in degree-lex order against the rule set, so it terminates), then only a
2559        // genuinely-divergent pair is materialized — this is what stops the runaway
2560        // (design §6b). See the (B) close loop below.
2561
2562        if std::env::var_os("AC_COMPLETE_TRACE").is_some() {
2563            eprintln!(
2564                "[ac-complete]   active(rules)={} targets(A′)={} crit(B)={}",
2565                rules.len(),
2566                targets.len(),
2567                crit.len()
2568            );
2569        }
2570
2571        let dt_gen = t_gen.elapsed();
2572        let mut changed = false;
2573        let t_aprime = std::time::Instant::now();
2574        // (A′) normalize each monomial; materialize+merge its normal form; collapse rules.
2575        // A node is normalized by all OTHER rules, never by its own node-rule (a rule's
2576        // LHS is in normal form w.r.t. itself; reducing it by itself would subsume the
2577        // rule before it can superpose — the §4b regression). So a node is collapsed only
2578        // when a *different*, strictly-contained rule reduces it (genuine inter-reduction).
2579        // Borrowed rule views plus reused normalize buffers:
2580        // the per-target rule set is a `clear`+`extend` refill of `Copy` views into the
2581        // round's rule table — no deep clones — and the normal form lands in a reused
2582        // destination buffer. Zero steady-state allocation per target.
2583        let mut nf_refs: Vec<NfRuleRef<'_, Cfg::G, Cfg::M>> = Vec::with_capacity(rules.len());
2584        let mut nf_out: Vec<(Cfg::G, Cfg::M)> = Vec::new();
2585        let mut nf_ping: Vec<(Cfg::G, Cfg::M)> = Vec::new();
2586        for (op, mset, class, node, _is_rule) in targets {
2587            // In-round stop: the goal pair joined, or this round's minting
2588            // blew the node budget — bail mid-apply instead of burning the
2589            // rest of the round. `rebuild` reads which outcome occurred.
2590            if self.cc_should_stop() {
2591                break;
2592            }
2593            nf_refs.clear();
2594            nf_refs.extend(
2595                rules
2596                    .iter()
2597                    .filter(|r| r.op == op && r.node != node)
2598                    .map(|r| NfRuleRef {
2599                        lhs: &r.lhs,
2600                        rhs: &r.rhs,
2601                    }),
2602            );
2603            // Normalize in the op's count domain: idempotent → set (clamp to 1); nilpotent →
2604            // mod-n; plain AC (MSet) → ℕ.
2605            // Linear, not indexed: this rule slice is refilled per target (each target is
2606            // normalized by every rule but its own), so there is no reuse to amortize an
2607            // index over. Any relative phase cost is workload-dependent and belongs in the
2608            // Criterion completion benchmark, not in this correctness comment.
2609            let nf = NfRules::linear(&nf_refs);
2610            match self.op_clamp(op) {
2611                CompletionClamp::Idempotent => {
2612                    normalize_set_into(&mut nf_out, &mut nf_ping, &mset, nf)
2613                }
2614                CompletionClamp::Nilpotent { order } => {
2615                    normalize_nilpotent_into(&mut nf_out, &mut nf_ping, &mset, nf, order)
2616                }
2617                CompletionClamp::Multiset => {
2618                    normalize_ms_into(&mut nf_out, &mut nf_ping, &mset, nf)
2619                }
2620            }
2621            // Inverse-pair cancellation on the normal form (group ops): normalization can
2622            // bring x and inv(x) together in one monomial; cancel before comparing. Track
2623            // whether it fired: a merge produced by pair cancellation is a group-law
2624            // inference (`x ∘ inv(x) = e`), not plain rule inter-reduction, and the proof
2625            // label must say so.
2626            let mut inverse_cancelled = false;
2627            if let Some(inv) = self.inverse_op(op) {
2628                inverse_cancelled = self.group_cancel_pairs(inv, &mut nf_out);
2629            }
2630            let normal = &nf_out;
2631            // If normalization by the other rules changed the monomial, materialize the normal
2632            // form and merge. `materialize` calls `add`, which now resolves a degenerate result
2633            // itself: an emptied monomial (`a ⊕ a → {}`, or `+(a,e)`-style cancellation) becomes
2634            // the unit, and a single mult-1 summand (`a ⊕ a ⊕ b → {b}`) becomes that class — so
2635            // this one branch covers the empty/size-1 cases too (a completion target always has
2636            // `mset.len() ≥ 2`, canonization never stores a degenerate node, so any empty/size-1
2637            // `normal` differs from `mset` and lands here).
2638            if *normal != mset {
2639                let c_prime = materialize(self, op, normal, &mut mat_buf);
2640                let just = if inverse_cancelled {
2641                    Justification::InverseCancel {
2642                        node_a: c_prime,
2643                        node_b: node,
2644                    }
2645                } else {
2646                    Justification::ACInterReduction {
2647                        node_a: c_prime,
2648                        node_b: node,
2649                    }
2650                };
2651                changed |= do_merge(self, c_prime, class, just);
2652                // Collapse: the node was reducible by another rule (proper containment),
2653                // so retire it from the active AC rule set (design §6b). FLAG_AC_COLLAPSED,
2654                // NOT subsume — the node stays matchable and a legal child; only
2655                // completion's active set excludes it. Merge first, mark second.
2656                self.set_cc_collapsed(node);
2657            }
2658        }
2659        let dt_aprime = t_aprime.elapsed();
2660        let t_bclose = std::time::Instant::now();
2661        // (B) close each critical pair by merging the normal forms of its two reducts.
2662        // Normalize BOTH reducts to multisets first; if they coincide the pair is already
2663        // joinable (a trivial critical pair) — skip it, minting no node and no merge.
2664        // Materializing trivial pairs was a second blowup source: each spurious node became
2665        // a fresh rule that fed the next round. Only genuinely divergent pairs
2666        // are materialized and merged.
2667        let mut trivial = 0usize;
2668        let mut nontrivial = 0usize;
2669        let mut trivial_after_nf = 0usize; // trivial pairs that needed full normalize to see it
2670        // The rule set used to normalize a reduct is the same for every pair of a given op, so
2671        // build the per-op rule sets ONCE (outside the loop), not per pair — the `Bclose` hoist
2672        // (perf doc §2). A reduct of op X must normalize ONLY against op-X rules: a different
2673        // op's LHS is a set of class ids that could spuriously match inside X's monomial. So
2674        // group `nf_rules` by op. Keyed by the typed op id (not a widened copy of one);
2675        // lookup is a small linear scan (few ops).
2676        let mut nf_by_op: Vec<(Cfg::O, Vec<NfRuleRef<'_, Cfg::G, Cfg::M>>)> = Vec::new();
2677        for r in &rules {
2678            let entry = match nf_by_op.iter_mut().find(|(o, _)| *o == r.op) {
2679                Some(e) => &mut e.1,
2680                None => {
2681                    nf_by_op.push((r.op, Vec::new()));
2682                    &mut nf_by_op.last_mut().unwrap().1
2683                }
2684            };
2685            entry.push(NfRuleRef {
2686                lhs: &r.lhs,
2687                rhs: &r.rhs,
2688            });
2689        }
2690        // Index each op's table by LHS-minimum class, hoisted with the table itself. This
2691        // The index is amortized over all reduct normalizations for the op. Its performance
2692        // effect is tracked by the Criterion completion benchmark.
2693        let nf_index_by_op: Vec<NfIndex<Cfg::G>> =
2694            nf_by_op.iter().map(|(_, v)| NfIndex::build(v)).collect();
2695        let empty_nf: Vec<NfRuleRef<'_, Cfg::G, Cfg::M>> = Vec::new();
2696        let crit_generated = crit.len();
2697        let mut n1_buf: Vec<(Cfg::G, Cfg::M)> = Vec::new();
2698        let mut n2_buf: Vec<(Cfg::G, Cfg::M)> = Vec::new();
2699        for (op, origin, r1, r2) in crit {
2700            // Same in-round stop as the (A′) loop above.
2701            if self.cc_should_stop() {
2702                break;
2703            }
2704            // Cheap raw-equality reject: most critical pairs are trivial (the two reducts
2705            // already coincide as multisets), so skip the two full normalizations entirely
2706            // when r1 == r2 already.
2707            if r1 == r2 {
2708                trivial += 1;
2709                continue;
2710            }
2711            let nf_rules = match nf_by_op.iter().position(|(o, _)| *o == op) {
2712                Some(i) => NfRules::indexed(&nf_by_op[i].1, &nf_index_by_op[i]),
2713                None => NfRules::linear(&empty_nf),
2714            };
2715            // Normalize both reducts in the op's count domain (idempotent → set, nilpotent →
2716            // mod-n, plain AC → ℕ) before comparing/merging.
2717            match self.op_clamp(op) {
2718                CompletionClamp::Idempotent => {
2719                    normalize_set_into(&mut n1_buf, &mut nf_ping, &r1, nf_rules);
2720                    normalize_set_into(&mut n2_buf, &mut nf_ping, &r2, nf_rules);
2721                }
2722                CompletionClamp::Nilpotent { order } => {
2723                    normalize_nilpotent_into(&mut n1_buf, &mut nf_ping, &r1, nf_rules, order);
2724                    normalize_nilpotent_into(&mut n2_buf, &mut nf_ping, &r2, nf_rules, order);
2725                }
2726                CompletionClamp::Multiset => {
2727                    normalize_ms_into(&mut n1_buf, &mut nf_ping, &r1, nf_rules);
2728                    normalize_ms_into(&mut n2_buf, &mut nf_ping, &r2, nf_rules);
2729                }
2730            }
2731            if let Some(inv) = self.inverse_op(op) {
2732                self.group_cancel_pairs(inv, &mut n1_buf);
2733                self.group_cancel_pairs(inv, &mut n2_buf);
2734            }
2735            let (n1, n2) = (&n1_buf, &n2_buf);
2736            if n1 == n2 {
2737                trivial += 1;
2738                trivial_after_nf += 1;
2739                continue;
2740            }
2741            nontrivial += 1;
2742            // `materialize` calls `add`, which resolves a degenerate reduct itself: an emptied
2743            // reduct (nilpotent cancellation / identity drop) becomes the unit, a single mult-1
2744            // summand becomes that class. So no empty/size-1 special-casing is needed here.
2745            let c1 = materialize(self, op, n1, &mut mat_buf);
2746            let c2 = materialize(self, op, n2, &mut mat_buf);
2747            // The proof label reflects the pair's ORIGIN: pairwise rule superposition
2748            // (Kapur Def 3.2), the op's own semantic-axiom CP (§4), or cancelative
2749            // closure (§5.2/§5.3).
2750            let just = match origin {
2751                CpOrigin::Superposition => Justification::ACSuperposition {
2752                    node_a: c1,
2753                    node_b: c2,
2754                },
2755                CpOrigin::AxiomCp => Justification::ACAxiomCP {
2756                    node_a: c1,
2757                    node_b: c2,
2758                },
2759                CpOrigin::Cancellative => Justification::Cancellative {
2760                    node_a: c1,
2761                    node_b: c2,
2762                },
2763            };
2764            changed |= do_merge(self, c1, c2, just);
2765        }
2766        if std::env::var_os("AC_COMPLETE_TRACE").is_some() {
2767            eprintln!(
2768                "[ac-complete]   crit(B) trivial={trivial} (raw-eq={}, after-nf={trivial_after_nf}) nontrivial={nontrivial}",
2769                trivial - trivial_after_nf
2770            );
2771            eprintln!(
2772                "[ac-complete]   full={full} rules={} delta_in_rules={delta_in_rules} delta_skipped_pairs={delta_skipped} crit_generated={crit_generated}",
2773                rules.len(),
2774            );
2775        }
2776        if phase_time {
2777            let dt_bclose = t_bclose.elapsed();
2778            eprintln!(
2779                "[ac-phase] rules={} reducible={:.1}ms gen+targets={:.1}ms A'={:.1}ms Bclose={:.1}ms",
2780                rules.len(),
2781                dt_reducible.as_secs_f64() * 1e3,
2782                dt_gen.as_secs_f64() * 1e3,
2783                dt_aprime.as_secs_f64() * 1e3,
2784                dt_bclose.as_secs_f64() * 1e3,
2785            );
2786        }
2787        changed
2788    }
2789
2790    pub fn mark(&mut self, shrink: ShrinkPolicy) -> EGraphToken {
2791        self.rebuild();
2792        EGraphToken {
2793            classes: self.classes.mark(shrink),
2794            nodes: self.nodes.mark(shrink),
2795            sorts: self.sorts.mark(shrink),
2796            ops: self.ops.mark(shrink),
2797            rules: self.rules.mark(shrink),
2798            axioms: self.axioms.mark(shrink),
2799            lits: self.lits.mark(shrink),
2800            unit_node: self
2801                .unit_node
2802                .try_mark(shrink)
2803                .expect("mark: frame depth is bounded by the saturation driver"),
2804            inverse_op: self
2805                .inverse_op
2806                .try_mark(shrink)
2807                .expect("mark: frame depth is bounded by the saturation driver"),
2808            completion_outcome: self.completion_outcome,
2809        }
2810    }
2811
2812    pub fn restore(&mut self, token: EGraphToken) {
2813        self.classes.restore(token.classes);
2814        self.nodes.restore(token.nodes);
2815        self.sorts.restore(token.sorts);
2816        self.ops.restore(token.ops);
2817        self.rules.restore(token.rules);
2818        self.axioms.restore(token.axioms);
2819        self.lits.restore(token.lits);
2820        self.unit_node
2821            .try_restore(token.unit_node)
2822            .expect("restore: token minted by this container's own mark");
2823        self.inverse_op
2824            .try_restore(token.inverse_op)
2825            .expect("restore: token minted by this container's own mark");
2826        // Roll the outcome back with the graph: the mark-time value describes exactly the
2827        // restored state (mark() rebuilds first), so a post-restore reader never sees an
2828        // outcome computed for the discarded scope.
2829        self.completion_outcome = token.completion_outcome;
2830        self.worklist.clear();
2831        self.collisions.clear();
2832        self.touched.clear();
2833    }
2834
2835    fn register_if_fresh(&mut self, result: Added<Cfg::G>, op: Cfg::O) -> Cfg::G {
2836        if result.is_fresh() {
2837            let id = result.id();
2838            let repr = self.classes.add_singleton(id);
2839            // Seed the per-class min-monomial pool. A completion node (MSet or Set) is its
2840            // class's only monomial for its own op, so seed that op's column to itself. A
2841            // non-completion node instead makes its class `atomic`: the class has a member
2842            // that is not a monomial, so the size-1 monomial `{class}` is its normal-form
2843            // representative (the completion rule RHS, §9a). Completion nodes are not atomic
2844            // by themselves; they become atomic only when referenced as a child (`add_use`).
2845            match self.ops.completion_column(op) {
2846                Some(col) => {
2847                    // Fix the pool row width to nb_completion on first completion-node seed.
2848                    // Ops are declared before terms (declare-before-build), so the count is
2849                    // stable here; `set_min_width` is idempotent when unchanged and rejects a
2850                    // change once rows exist.
2851                    self.classes.set_min_width(self.ops.completion_op_count());
2852                    self.classes.set_min_monomial(repr, col, id);
2853                }
2854                None => self.classes.set_atomic(repr),
2855            }
2856            self.touched.push(id);
2857        }
2858        result.id()
2859    }
2860
2861    /// Semi-naive: node ids created or recanonicalized since the last
2862    /// `clear_touched` (or `restore`). May contain duplicates; the delta
2863    /// index builder deduplicates. Superset of all genuinely-changed nodes.
2864    pub fn touched(&self) -> &[Cfg::G] {
2865        &self.touched
2866    }
2867
2868    /// Clear the touched log (call at a semi-naive round boundary, after the
2869    /// delta index for the round has been built).
2870    pub fn clear_touched(&mut self) {
2871        self.touched.clear();
2872    }
2873
2874    // -----------------------------------------------------------------------
2875    // Read-only inspection
2876    // -----------------------------------------------------------------------
2877
2878    pub fn node_count(&self) -> usize {
2879        self.nodes.routing().len()
2880    }
2881
2882    pub fn class_repr(&self, id: Cfg::G) -> Cfg::G {
2883        self.classes.find_const(id)
2884    }
2885
2886    /// The minimum-monomial node stored for `id`'s class in `id`'s op column (the completion
2887    /// rule RHS, §9a). Maintained on merge by `fold_min_monomial`. Returns `None` if `id` has
2888    /// no class or its op has no stored monomial for that class. Read by tests only.
2889    #[allow(dead_code)]
2890    pub(crate) fn class_min_monomial(&self, id: Cfg::G) -> Option<Cfg::G> {
2891        let repr = self.classes.repr_id(self.classes.find_const(id))?;
2892        let col = self.completion_column(id)?;
2893        self.classes.min_monomial(repr, col)
2894    }
2895
2896    /// Whether `id`'s class is `atomic` (referenced as a child / has a non-AC node, so
2897    /// `{class}` is its canonical summand form, §9a). `None` if `id` has no class.
2898    #[allow(dead_code)]
2899    pub(crate) fn class_atomic(&self, id: Cfg::G) -> Option<bool> {
2900        let repr = self.classes.repr_id(self.classes.find_const(id))?;
2901        Some(self.classes.atomic(repr))
2902    }
2903
2904    pub fn node_ref(&self, id: Cfg::G) -> NodeRef<Cfg::Ids> {
2905        self.nodes.routing().get(id)
2906    }
2907
2908    pub fn node_op(&self, id: Cfg::G) -> Cfg::O {
2909        match self.node_ref(id) {
2910            NodeRef::Plain0(l) => self.nodes.plain0.get(l).op(),
2911            NodeRef::Plain1(l) => self.nodes.plain1.get(l).op(),
2912            NodeRef::Plain2(l) => self.nodes.plain2.get(l).op(),
2913            NodeRef::Plain3(l) => self.nodes.plain3.get(l).op(),
2914            NodeRef::SPair(l) => self.nodes.spair.get(l).op(),
2915            NodeRef::PlainN(l) => self.nodes.plain_n.get(l).op(),
2916            NodeRef::Seq(l) => self.nodes.seq.get(l).op(),
2917            NodeRef::MSet(l) => self.nodes.mset.get(l).op(),
2918            NodeRef::Set(l) => self.nodes.set.get(l).op(),
2919            NodeRef::Lit(l) => self.nodes.lit.get(l).op(),
2920        }
2921    }
2922
2923    pub fn node_op_name(&self, id: Cfg::G) -> &str {
2924        &self.ops.info(self.node_op(id)).name
2925    }
2926
2927    /// Global ids of every AC e-node, ascending (the AC partition is append-only, so local
2928    /// id order is global-id order). The completion round iterates this instead of all
2929    /// `node_count()` nodes: it visits only AC nodes, never the non-AC majority (leaves,
2930    /// `Plain`/`Lit`/other-op nodes). On AC-dense stress graphs this is ~neutral, but on a
2931    /// general e-graph (mostly non-AC structure) the AC nodes are a small fraction, so the
2932    /// per-round scan drops from O(total nodes) to O(AC nodes). Includes collapsed/subsumed
2933    /// AC nodes; the caller filters by flag.
2934    fn completion_node_ids(&self) -> impl Iterator<Item = Cfg::G> + '_ {
2935        use crate::containers::DenseId;
2936        use crate::typed_routing::NodeIds;
2937        // Both completion partitions: MSet (plain AC or nilpotent) and Set (idempotent/ACI).
2938        //
2939        // The bare `from_usize` mints below need no bound check, unlike the global-id scans
2940        // (see [`node_ids`](Self::node_ids)): these arenas are indexed *by* the local id, so
2941        // the container's own capacity guard IS the id bound — `IndexLike::max_nat()` for a
2942        // dense id is its `id_bound()`. A position the arena can hold therefore always has a
2943        // local id, and `len()` hands one back typed rather than as a raw count.
2944        let n_mset = self.nodes.mset.len().to_usize();
2945        let n_set = self.nodes.set.len().to_usize();
2946        let mset = (0..n_mset).map(move |i| {
2947            let l = <Cfg::Ids as NodeIds>::LMSet::from_usize(i);
2948            self.nodes.mset.get(l).global_id()
2949        });
2950        let set = (0..n_set).map(move |i| {
2951            let l = <Cfg::Ids as NodeIds>::LSet::from_usize(i);
2952            self.nodes.set.get(l).global_id()
2953        });
2954        mset.chain(set)
2955    }
2956
2957    pub fn node_flags(&self, id: Cfg::G) -> u8 {
2958        match self.node_ref(id) {
2959            NodeRef::Plain0(l) => self.nodes.plain0.get(l).flags,
2960            NodeRef::Plain1(l) => self.nodes.plain1.get(l).flags,
2961            NodeRef::Plain2(l) => self.nodes.plain2.get(l).flags,
2962            NodeRef::Plain3(l) => self.nodes.plain3.get(l).flags,
2963            NodeRef::SPair(l) => self.nodes.spair.get(l).flags,
2964            NodeRef::PlainN(l) => self.nodes.plain_n.get(l).flags,
2965            NodeRef::Seq(l) => self.nodes.seq.get(l).flags,
2966            NodeRef::MSet(l) => self.nodes.mset.get(l).flags,
2967            NodeRef::Set(l) => self.nodes.set.get(l).flags,
2968            NodeRef::Lit(l) => self.nodes.lit.get(l).flags,
2969        }
2970    }
2971
2972    /// Set one of the per-node control flags ([`FLAG_SUBSUMED`](crate::node_types::FLAG_SUBSUMED),
2973    /// [`FLAG_AC_COLLAPSED`](crate::node_types::FLAG_AC_COLLAPSED)) on `id`'s node.
2974    fn set_node_flag(&mut self, id: Cfg::G, flag: u8) {
2975        macro_rules! flag {
2976            ($store:expr, $l:expr) => {{
2977                let mut n = $store.get($l);
2978                n.flags |= flag;
2979                $store.set($l, n);
2980            }};
2981        }
2982        match self.node_ref(id) {
2983            NodeRef::Plain0(l) => flag!(self.nodes.plain0, l),
2984            NodeRef::Plain1(l) => flag!(self.nodes.plain1, l),
2985            NodeRef::Plain2(l) => flag!(self.nodes.plain2, l),
2986            NodeRef::Plain3(l) => flag!(self.nodes.plain3, l),
2987            NodeRef::SPair(l) => flag!(self.nodes.spair, l),
2988            NodeRef::PlainN(l) => flag!(self.nodes.plain_n, l),
2989            NodeRef::Seq(l) => flag!(self.nodes.seq, l),
2990            NodeRef::MSet(l) => flag!(self.nodes.mset, l),
2991            NodeRef::Set(l) => flag!(self.nodes.set, l),
2992            NodeRef::Lit(l) => flag!(self.nodes.lit, l),
2993        }
2994    }
2995
2996    /// User-level subsumption: exclude `id` from future pattern matching (the matcher's
2997    /// indices skip `FLAG_SUBSUMED`). Distinct from AC-collapse — see `FLAG_AC_COLLAPSED`.
2998    pub fn subsume(&mut self, id: Cfg::G) {
2999        self.set_node_flag(id, crate::node_types::FLAG_SUBSUMED);
3000    }
3001
3002    /// AC-completion collapse: retire `id` from the active AC rule set (its child
3003    /// multiset is reducible by a smaller AC rule, so it is no longer a superposition or
3004    /// inter-reduction source). The node stays **matchable** and a legal child; only
3005    /// completion's active set excludes it (design §6b). Distinct from `subsume`.
3006    pub(crate) fn set_cc_collapsed(&mut self, id: Cfg::G) {
3007        debug_assert!(
3008            matches!(self.node_ref(id), NodeRef::MSet(_) | NodeRef::Set(_)),
3009            "set_cc_collapsed on a non-completion node"
3010        );
3011        self.set_node_flag(id, crate::node_types::FLAG_AC_COLLAPSED);
3012    }
3013
3014    /// If `id` is a literal node, return its interned value. Otherwise `None`.
3015    pub fn get_lit_val(&self, id: Cfg::G) -> Option<&L> {
3016        if let NodeRef::Lit(l) = self.node_ref(id) {
3017            Some(self.lits.get(self.nodes.lit.get(l).lit))
3018        } else {
3019            None
3020        }
3021    }
3022
3023    /// If `id` is a literal node, return its interned LitValId.
3024    pub fn get_lit_val_id(&self, id: Cfg::G) -> Option<Cfg::V> {
3025        if let NodeRef::Lit(l) = self.node_ref(id) {
3026            Some(self.nodes.lit.get(l).lit)
3027        } else {
3028            None
3029        }
3030    }
3031
3032    /// Return sort of a node (from its operator's signature).
3033    pub fn node_sort(&self, id: Cfg::G) -> Cfg::S {
3034        self.ops.info(self.node_op(id)).return_sort
3035    }
3036
3037    /// Debug: verify all nodes in each e-class have the same sort.
3038    /// Panics on violation. Only useful in tests / debug builds.
3039    pub fn debug_check_sort_invariant(&self) {
3040        use std::collections::HashMap;
3041        let mut class_sort: HashMap<Cfg::G, Cfg::S> = HashMap::new();
3042        for gid in self.node_ids() {
3043            let repr = self.find_const(gid);
3044            let sort = self.node_sort(gid);
3045            if let Some(&existing) = class_sort.get(&repr) {
3046                assert_eq!(
3047                    existing,
3048                    sort,
3049                    "sort invariant violated: e-class of '{}' has sort {:?}, but '{}' has sort {:?}",
3050                    self.node_op_name(repr),
3051                    existing,
3052                    self.node_op_name(gid),
3053                    sort
3054                );
3055            } else {
3056                class_sort.insert(repr, sort);
3057            }
3058        }
3059    }
3060
3061    pub fn for_each_child(&self, id: Cfg::G, mut f: impl FnMut(Cfg::G, Cfg::M)) -> usize {
3062        match self.node_ref(id) {
3063            NodeRef::Plain0(_) => 0,
3064            NodeRef::Plain1(l) => {
3065                for &c in &self.nodes.plain1.get(l).children {
3066                    f(c, Cfg::M::ONE);
3067                }
3068                1
3069            }
3070            NodeRef::Plain2(l) => {
3071                for &c in &self.nodes.plain2.get(l).children {
3072                    f(c, Cfg::M::ONE);
3073                }
3074                2
3075            }
3076            NodeRef::Plain3(l) => {
3077                for &c in &self.nodes.plain3.get(l).children {
3078                    f(c, Cfg::M::ONE);
3079                }
3080                3
3081            }
3082            NodeRef::SPair(l) => {
3083                for &c in &self.nodes.spair.get(l).children {
3084                    f(c, Cfg::M::ONE);
3085                }
3086                2
3087            }
3088            NodeRef::PlainN(l) => {
3089                let n = self.nodes.plain_n.get(l);
3090                let (s, e) = n.span();
3091                for i in s..e {
3092                    f(self.nodes.plain_n.pool_get(i), Cfg::M::ONE);
3093                }
3094                e - s
3095            }
3096            NodeRef::Seq(l) => {
3097                let n = self.nodes.seq.get(l);
3098                let (s, e) = n.span();
3099                for i in s..e {
3100                    f(self.nodes.seq.pool_get(i), Cfg::M::ONE);
3101                }
3102                e - s
3103            }
3104            NodeRef::MSet(l) => {
3105                let n = self.nodes.mset.get(l);
3106                let (s, e) = n.span();
3107                for i in s..e {
3108                    let c = self.nodes.mset.pool_get(i);
3109                    f(Cfg::mset_child_id(&c), Cfg::mset_child_mult(&c));
3110                }
3111                e - s
3112            }
3113            NodeRef::Set(l) => {
3114                let n = self.nodes.set.get(l);
3115                let (s, e) = n.span();
3116                for i in s..e {
3117                    f(self.nodes.set.pool_get(i), Cfg::M::ONE);
3118                }
3119                e - s
3120            }
3121            NodeRef::Lit(_) => 0,
3122        }
3123    }
3124
3125    /// Read the child at position `pos` from a fixed-arity node. O(1).
3126    /// Panics if `pos` is out of range or node is variadic/lit.
3127    pub fn child_at(&self, id: Cfg::G, pos: Cfg::Index) -> Cfg::G {
3128        // `Cfg::Index`-wide: a position offsets into the node's span in the child pool,
3129        // which is sized by that word (see `IndexStore::by_child_pos`). `as_usize` is
3130        // exact for every `IndexLike`, so no check is needed on the way in; an
3131        // out-of-range position still lands on the arm's bounds check or the `panic!`.
3132        let p = pos.as_usize();
3133        match self.node_ref(id) {
3134            NodeRef::Plain1(l) => self.nodes.plain1.get(l).children[p],
3135            NodeRef::Plain2(l) => self.nodes.plain2.get(l).children[p],
3136            NodeRef::Plain3(l) => self.nodes.plain3.get(l).children[p],
3137            NodeRef::SPair(l) => self.nodes.spair.get(l).children[p],
3138            NodeRef::PlainN(l) => {
3139                let n = self.nodes.plain_n.get(l);
3140                let (s, _) = n.span();
3141                self.nodes.plain_n.pool_get(s + p)
3142            }
3143            NodeRef::Seq(l) => {
3144                let n = self.nodes.seq.get(l);
3145                let (s, _) = n.span();
3146                self.nodes.seq.pool_get(s + p)
3147            }
3148            _ => panic!("child_at: not a plain/sequence node or pos out of range"),
3149        }
3150    }
3151
3152    /// Read AC children as `(id, multiplicity)` pairs into `buf`.
3153    pub fn mset_children(&self, id: Cfg::G, buf: &mut Vec<(Cfg::G, Cfg::M)>) {
3154        buf.clear();
3155        match self.node_ref(id) {
3156            NodeRef::MSet(l) => {
3157                let n = self.nodes.mset.get(l);
3158                let (s, e) = n.span();
3159                for i in s..e {
3160                    let c = self.nodes.mset.pool_get(i);
3161                    buf.push((Cfg::mset_child_id(&c), Cfg::mset_child_mult(&c)));
3162                }
3163            }
3164            _ => panic!("mset_children: not an MSet node"),
3165        }
3166    }
3167
3168    /// Flatten nested same-op AC children of `op` in `self.g_buf`, to a fixpoint
3169    /// (`WF_flat`, design §6c). Each element is examined by its class's *canonical summand
3170    /// form* (`summand_form`, §9a), NOT by its union-find representative (which depends on
3171    /// merge order and is therefore non-canonical):
3172    ///
3173    /// - if the child's class is **non-`atomic`** (a pure `op`-sum), splice in that class's
3174    ///   `min_monomial` children (each by multiplicity), recursively;
3175    /// - otherwise (the class is `atomic`: referenced as a child, or has a non-AC node) the
3176    ///   single atom `{class}` is its canonical summand form, so keep the child as a summand.
3177    ///
3178    /// `g_buf` already holds `find`'d ids. Preserves §5b: `+{a,b}` used as `neg`'s child is
3179    /// `atomic`, so it is kept, not flattened. The semantic invariants make recursive
3180    /// expansion well-founded; a work/output budget is nevertheless enforced in every build
3181    /// profile so corrupted cyclic state is refused instead of looping or returning a
3182    /// partially flattened node.
3183    fn flatten_ac_children(&mut self, op: Cfg::O) {
3184        // Move the buffers out to satisfy the borrow checker while reading `self`.
3185        let mut work = std::mem::take(&mut self.flatten_buf);
3186        let mut out = std::mem::take(&mut self.g_buf);
3187        // Seed the worklist with the current children (reverse, so popping preserves
3188        // a stable order — order doesn't matter for AC but keeps traces readable).
3189        work.clear();
3190        work.extend(out.iter().rev().copied());
3191        out.clear();
3192
3193        // Safety cap on the children *splicing adds*, which is the only unbounded
3194        // quantity here. Each splice replaces a child by a strictly smaller monomial, so
3195        // a well-formed graph drains well under this bound; the cap only guards a
3196        // degenerate cyclic class, which we must not loop on.
3197        //
3198        // Measured from the caller's own child count, not from zero: the seeded children
3199        // are given, not generated, and a monomial may legitimately be far wider than the
3200        // graph is deep. Anchoring at zero made a plain `f(a, a, …)` with more children
3201        // than `1 + 64 * node_count()` trip the assertion below — a large-but-well-formed
3202        // input diagnosed as a cyclic class.
3203        let cap = work
3204            .len()
3205            .saturating_add(1)
3206            .saturating_add(64usize.saturating_mul(self.node_count()));
3207        let op_col = self.ops.completion_column(op);
3208        let mut expansions = 0usize;
3209        while let Some(g) = work.pop() {
3210            let cls = self.classes.find_const(g);
3211            // A child is a pure `op`-sum to splice iff its class is non-atomic AND its
3212            // canonical summand for `op`'s column (`min_monomial`) is an AC node of this same
3213            // `op`. Both reads are representative-independent (per-class pool), never
3214            // `find`-keyed.
3215            let mut spliced = false;
3216            if let Some(col) = op_col
3217                && let Some(repr) = self.classes.repr_id(cls)
3218                && !self.classes.atomic(repr)
3219                && let Some(min_node) = self.classes.min_monomial(repr, col)
3220                && self.node_op(min_node) == op
3221                && matches!(self.node_ref(min_node), NodeRef::MSet(_) | NodeRef::Set(_))
3222            {
3223                assert!(
3224                    expansions < cap && out.len() <= cap,
3225                    "flatten_ac_children exceeded work cap (degenerate cyclic AC class?)"
3226                );
3227                expansions += 1;
3228                // Expand the canonical summand form; `for_each_child` yields (class, count)
3229                // for either representation (a Set member counts once).
3230                self.for_each_child(min_node, |cg, times| {
3231                    for _ in 0..times.to_usize() {
3232                        work.push(cg);
3233                    }
3234                });
3235                spliced = true;
3236            }
3237            if !spliced {
3238                out.push(g);
3239            }
3240        }
3241        assert!(
3242            out.len() <= cap,
3243            "flatten_ac_children exceeded cap (degenerate cyclic AC class?)"
3244        );
3245
3246        self.g_buf = out;
3247        self.flatten_buf = work;
3248    }
3249
3250    /// The canonical same-`op` sequence node of `g`'s class, or `None` if the class is not a
3251    /// **pure `op`-sequence** — i.e. if any member is something other than an `op` `Seq` node.
3252    ///
3253    /// This is the A-only counterpart of the AC `summand_form` predicate
3254    /// (`ac-congruence-completeness.md` §6c) and it is chosen for the same reason: the answer
3255    /// must be a function of the class's *membership*, not of whichever node the union-find
3256    /// picked as representative (a representative-keyed test flattens or not depending on
3257    /// merge order, so it is not canonical — §6c's representative trap). Two consequences,
3258    /// both deliberate:
3259    ///
3260    /// - **Purity, not AC's `atomic`.** `atomic` cannot serve here: `register_if_fresh` sets
3261    ///   it on every class without a completion column, which includes every `Seq` class, so
3262    ///   for A-only ops it is constantly true. Purity plays the same role — a class holding
3263    ///   only `op`-sequences has no standalone atom form, so spelling it out is forced — and
3264    ///   it is what keeps a class that is *also* an atom from being spliced. That case is not
3265    ///   hypothetical: once a rule proves `gmul(b, inv(b)) = I`, `I`'s class holds a `Seq`
3266    ///   node, and splicing it into every later sequence would rewrite uphill and grow terms
3267    ///   without bound.
3268    /// - **The `op`-least member.** A class may hold several distinct `op`-sequences that were
3269    ///   merged; picking the least node id makes the choice a function of the class, and node
3270    ///   ids are assigned at creation and never renumbered, so this is merge-order independent.
3271    ///   Every spelling of the child therefore splices to the same sequence and the parents
3272    ///   land in one class.
3273    ///
3274    /// Cost is one class-ring walk, with an early exit on the first non-`op` member — so an
3275    /// ordinary atom child (a leaf, a constructor) costs its class's first member, and the
3276    /// full walk is paid only by classes that really are pure sequences.
3277    fn pure_seq_node(&self, g: Cfg::G, op: Cfg::O) -> Option<Cfg::G> {
3278        let cls = self.classes.find_const(g);
3279        let mut best: Option<Cfg::G> = None;
3280        for n in self.classes.iter_class(cls) {
3281            if self.node_op(n) != op || !matches!(self.node_ref(n), NodeRef::Seq(_)) {
3282                return None;
3283            }
3284            if best.is_none_or(|b| n.to_usize() < b.to_usize()) {
3285                best = Some(n);
3286            }
3287        }
3288        best
3289    }
3290
3291    /// Flatten nested same-op children of an A-only (`Seq`) op in `self.g_buf`, to a fixpoint,
3292    /// **preserving order**: associativity licenses re-association, not reordering, so a
3293    /// spliced child's elements take the child's position in the parent's sequence.
3294    ///
3295    /// A child is spliced iff [`pure_seq_node`](Self::pure_seq_node) names an `op`-sequence
3296    /// for its class; otherwise it is kept as one element. Splicing recurses, because a
3297    /// spliced sequence's own elements may since have been merged into pure `op`-sequence
3298    /// classes.
3299    ///
3300    /// `g_buf` already holds `find`'d ids. The least-node choice makes expansion
3301    /// well-founded for a valid append-only graph. The same work/output budget as
3302    /// `flatten_ac_children` is still enforced in every build profile: malformed state such
3303    /// as `X = {seq(X)}` is refused rather than looping or producing a partial normal form.
3304    fn flatten_seq_children(&mut self, op: Cfg::O) {
3305        // Move the buffers out to satisfy the borrow checker while reading `self`.
3306        let mut work = std::mem::take(&mut self.flatten_buf);
3307        let mut out = std::mem::take(&mut self.g_buf);
3308        // Seed the worklist reversed, so popping yields the children in sequence order — for
3309        // A this is load-bearing, not cosmetic as in the AC counterpart.
3310        work.clear();
3311        work.extend(out.iter().rev().copied());
3312        out.clear();
3313        let cap = work
3314            .len()
3315            .saturating_add(1)
3316            .saturating_add(64usize.saturating_mul(self.node_count()));
3317        let mut expansions = 0usize;
3318        while let Some(g) = work.pop() {
3319            let mut spliced = false;
3320            if let Some(inner) = self.pure_seq_node(g, op)
3321                && let NodeRef::Seq(l) = self.node_ref(inner)
3322            {
3323                assert!(
3324                    expansions < cap && out.len() <= cap,
3325                    "flatten_seq_children exceeded work cap (degenerate cyclic A class?)"
3326                );
3327                expansions += 1;
3328                let (s, e) = self.nodes.seq.get(l).span();
3329                // Reversed again, so the elements pop back in their stored order.
3330                for i in (s..e).rev() {
3331                    work.push(self.nodes.seq.pool_get(i));
3332                }
3333                spliced = true;
3334            }
3335            if !spliced {
3336                out.push(g);
3337            }
3338        }
3339        assert!(
3340            out.len() <= cap,
3341            "flatten_seq_children exceeded cap (degenerate cyclic A class?)"
3342        );
3343
3344        self.g_buf = out;
3345        self.flatten_buf = work;
3346    }
3347
3348    /// Read ACI children (ids only, no multiplicities) into `buf`.
3349    pub fn set_children(&self, id: Cfg::G, buf: &mut Vec<Cfg::G>) {
3350        buf.clear();
3351        match self.node_ref(id) {
3352            NodeRef::Set(l) => {
3353                let n = self.nodes.set.get(l);
3354                let (s, e) = n.span();
3355                for i in s..e {
3356                    buf.push(self.nodes.set.pool_get(i));
3357                }
3358            }
3359            _ => panic!("set_children: not a Set node"),
3360        }
3361    }
3362
3363    /// Read A/PlainN children into `buf` in sequence order.
3364    pub fn seq_children(&self, id: Cfg::G, buf: &mut Vec<Cfg::G>) {
3365        buf.clear();
3366        match self.node_ref(id) {
3367            NodeRef::PlainN(l) => {
3368                let n = self.nodes.plain_n.get(l);
3369                let (s, e) = n.span();
3370                for i in s..e {
3371                    buf.push(self.nodes.plain_n.pool_get(i));
3372                }
3373            }
3374            NodeRef::Seq(l) => {
3375                let n = self.nodes.seq.get(l);
3376                let (s, e) = n.span();
3377                for i in s..e {
3378                    buf.push(self.nodes.seq.pool_get(i));
3379                }
3380            }
3381            _ => panic!("seq_children: not a sequence node"),
3382        }
3383    }
3384
3385    pub fn node_lit(&self, id: Cfg::G) -> Option<Cfg::V> {
3386        match self.node_ref(id) {
3387            NodeRef::Lit(l) => Some(self.nodes.lit.get(l).lit),
3388            _ => None,
3389        }
3390    }
3391}
3392
3393#[cfg(test)]
3394mod tests {
3395    use super::*;
3396    use crate::id::{OpId, SortId};
3397    use crate::lit_model::LitModel;
3398    use crate::literal::NiraLitVal;
3399
3400    struct Th {
3401        int: SortId,
3402        x: OpId,
3403        y: OpId,
3404        z: OpId,
3405        w: OpId,
3406        f: OpId,
3407        g: OpId,
3408        h: OpId,
3409        eq: OpId,
3410        plus: OpId,
3411        and: OpId,
3412        sub: OpId,
3413        f4: OpId,
3414    }
3415
3416    fn eg<const T: bool, const P: bool>() -> (EGraph31<NiraLitVal, T, P>, Th) {
3417        let mut eg = EGraph31::new();
3418        let int = eg.intern_sort("Int");
3419        let th = Th {
3420            int,
3421            x: eg.register_op0("x", int),
3422            y: eg.register_op0("y", int),
3423            z: eg.register_op0("z", int),
3424            w: eg.register_op0("w", int),
3425            f: eg.register_op1("f", int, int),
3426            g: eg.register_op2("g", int, int, int),
3427            h: eg.register_op3("h", int, int, int, int),
3428            eq: eg.register_c("eq", [int, int], int),
3429            plus: eg.register_mset("plus", int, int),
3430            and: eg.register_set("and", int, int),
3431            sub: eg.register_a("sub", int, int, crate::registry::AssocDir::Left),
3432            f4: eg.register_opn("f4", &[int, int, int, int], int),
3433        };
3434        (eg, th)
3435    }
3436
3437    /// Randomized canonization coverage for the AC count-clamp / identity-drop / degenerate-arity
3438    /// normal form, with completion OFF (these are canonization facts, not completion — see the
3439    /// design doc "Canonization, not completion"). The oracle is an *independent* reference
3440    /// normalizer (`ref_normal`), so `add` is checked against a from-scratch computation of what
3441    /// the canonical class should be, over random inputs — the coverage the hand-written fixtures
3442    /// lack. Exercises plain AC, nilpotent order 2 AND order 3, idempotent, and identity, and both
3443    /// the build path (`add`) and the recanonize path (build distinct, then merge children).
3444    mod canonize_prop {
3445        use super::*;
3446        use crate::registry::{Clamp, OpKind};
3447        use proptest::prelude::*;
3448        use std::collections::BTreeMap;
3449
3450        type Cfg31G = crate::id::ENodeId;
3451
3452        /// Which AC op a random term uses; each is a distinct registered op sharing one sort.
3453        #[derive(Clone, Copy, Debug)]
3454        enum Kind {
3455            PlainAc,      // + : ℕ counts, no unit
3456            Nilpotent2,   // xor : count mod 2, unit e
3457            Nilpotent3,   // nz  : count mod 3, unit e
3458            Idempotent,   // and : count → 1
3459            IdentityPlus, // ip  : ℕ counts, unit e dropped
3460        }
3461
3462        struct Env {
3463            eg: EGraph31<NiraLitVal, false, false>,
3464            atoms: Vec<Cfg31G>, // the 4 leaf classes usable as children
3465            unit: Cfg31G,       // the declared unit `e`
3466            plain: OpId,
3467            nil2: OpId,
3468            nil3: OpId,
3469            idem: OpId,
3470            ident: OpId,
3471        }
3472
3473        fn op_of(env: &Env, k: Kind) -> OpId {
3474            match k {
3475                Kind::PlainAc => env.plain,
3476                Kind::Nilpotent2 => env.nil2,
3477                Kind::Nilpotent3 => env.nil3,
3478                Kind::Idempotent => env.idem,
3479                Kind::IdentityPlus => env.ident,
3480            }
3481        }
3482
3483        fn make_env() -> Env {
3484            let mut eg = EGraph31::<NiraLitVal, false, false>::new();
3485            let s = eg.intern_sort("E");
3486            let e_op = eg.register_op0("e", s);
3487            let unit = eg.add(e_op, &[]);
3488            // The descriptor's `identity: UnitRef` is only read by the sortcheck resolver; the
3489            // egraph resolves the unit via `set_unit_node` (below), so pass `None` here. The clamp
3490            // field is what canonization reads.
3491            let mk = |eg: &mut EGraph31<NiraLitVal, false, false>, name: &str, clamp: Clamp| {
3492                eg.register_kind(
3493                    name,
3494                    s,
3495                    OpKind::MSet {
3496                        arg_sort: s,
3497                        clamp,
3498                        identity: None,
3499                        cancellative: false,
3500                    },
3501                )
3502            };
3503            let plain = mk(&mut eg, "plus", Clamp::None);
3504            let nil2 = mk(&mut eg, "xr2", Clamp::Nilpotent { order: 2 });
3505            let nil3 = mk(&mut eg, "xr3", Clamp::Nilpotent { order: 3 });
3506            let idem = eg.register_kind(
3507                "andop",
3508                s,
3509                OpKind::Set {
3510                    arg_sort: s,
3511                    clamp: Clamp::Idempotent,
3512                    identity: None,
3513                    cancellative: false,
3514                },
3515            );
3516            let ident = mk(&mut eg, "ip", Clamp::None);
3517            eg.set_unit_node(nil2, unit);
3518            eg.set_unit_node(nil3, unit);
3519            eg.set_unit_node(ident, unit);
3520            let a = eg.register_op0("a", s);
3521            let b = eg.register_op0("b", s);
3522            let c = eg.register_op0("c", s);
3523            let d = eg.register_op0("d", s);
3524            let atoms = vec![
3525                eg.add(a, &[]),
3526                eg.add(b, &[]),
3527                eg.add(c, &[]),
3528                eg.add(d, &[]),
3529            ];
3530            Env {
3531                eg,
3532                atoms,
3533                unit,
3534                plain,
3535                nil2,
3536                nil3,
3537                idem,
3538                ident,
3539            }
3540        }
3541
3542        /// Independent reference: the canonical class a well-formed AC term over `children` (given
3543        /// as current class ids) should land in, computed from scratch — the oracle. Mirrors the
3544        /// *spec*: coalesce by class → drop unit (ops with an identity) → clamp counts → resolve
3545        /// degeneracy (empty ⇒ unit, single mult-1 ⇒ that child, else a built node).
3546        fn ref_normal(env: &mut Env, k: Kind, children: &[Cfg31G]) -> Cfg31G {
3547            let has_unit = matches!(k, Kind::Nilpotent2 | Kind::Nilpotent3 | Kind::IdentityPlus);
3548            let unit_cls = env.eg.find(env.unit);
3549            let mut counts: BTreeMap<u32, u32> = BTreeMap::new();
3550            for &g in children {
3551                *counts.entry(env.eg.find(g).raw()).or_insert(0) += 1;
3552            }
3553            if has_unit {
3554                counts.remove(&unit_cls.raw());
3555            }
3556            match k {
3557                Kind::Idempotent => {
3558                    for v in counts.values_mut() {
3559                        *v = 1;
3560                    }
3561                }
3562                Kind::Nilpotent2 => counts.retain(|_, v| {
3563                    *v %= 2;
3564                    *v != 0
3565                }),
3566                Kind::Nilpotent3 => counts.retain(|_, v| {
3567                    *v %= 3;
3568                    *v != 0
3569                }),
3570                Kind::PlainAc | Kind::IdentityPlus => {}
3571            }
3572            let total: u32 = counts.values().sum();
3573            if total == 0 {
3574                return env.eg.find(env.unit);
3575            }
3576            if counts.len() == 1 && *counts.values().next().unwrap() == 1 {
3577                return env
3578                    .eg
3579                    .find(crate::id::ENodeId::new(*counts.keys().next().unwrap()));
3580            }
3581            let mut flat: Vec<Cfg31G> = Vec::new();
3582            for (cls, cnt) in &counts {
3583                for _ in 0..*cnt {
3584                    flat.push(crate::id::ENodeId::new(*cls));
3585                }
3586            }
3587            let op = op_of(env, k);
3588            env.eg.add(op, &flat)
3589        }
3590
3591        fn all_kinds() -> impl Strategy<Value = Kind> {
3592            prop_oneof![
3593                Just(Kind::PlainAc),
3594                Just(Kind::Nilpotent2),
3595                Just(Kind::Nilpotent3),
3596                Just(Kind::Idempotent),
3597                Just(Kind::IdentityPlus),
3598            ]
3599        }
3600
3601        proptest! {
3602            #![proptest_config(ProptestConfig::with_cases(400))]
3603
3604            /// `add` must agree with the independent reference normalizer, and be permutation-
3605            /// invariant (AC). Child index 4 selects the unit, so unit-drop is exercised.
3606            /// Completion is OFF: this is pure canonization.
3607            #[test]
3608            fn add_matches_reference(
3609                k in all_kinds(),
3610                idxs in proptest::collection::vec(0usize..5, 1..8),
3611                perm_seed in any::<u64>(),
3612            ) {
3613                let mut env = make_env();
3614                let pick = |i: usize, env: &Env| if i < 4 { env.atoms[i] } else { env.unit };
3615                let children: Vec<Cfg31G> = idxs.iter().map(|&i| pick(i, &env)).collect();
3616
3617                let op = op_of(&env, k);
3618                let built = env.eg.add(op, &children);
3619                let expected = ref_normal(&mut env, k, &children);
3620                prop_assert_eq!(
3621                    env.eg.find(built),
3622                    env.eg.find(expected),
3623                    "add vs reference: kind={:?} idxs={:?}", k, idxs
3624                );
3625
3626                let mut shuffled = children.clone();
3627                let n = shuffled.len();
3628                for i in 0..n {
3629                    let j = ((perm_seed.wrapping_mul(6364136223846793005).wrapping_add(i as u64))
3630                        as usize) % n;
3631                    shuffled.swap(i, j);
3632                }
3633                let built2 = env.eg.add(op, &shuffled);
3634                prop_assert_eq!(env.eg.find(built), env.eg.find(built2), "permutation invariance");
3635            }
3636
3637            /// Recanonize path: build a node with distinct children, merge a pair of children,
3638            /// rebuild (completion OFF → congruence + canonization only). The node's class must
3639            /// match the reference recomputed with the merge applied.
3640            #[test]
3641            fn recanonize_matches_reference(
3642                k in all_kinds(),
3643                idxs in proptest::collection::vec(0usize..4, 2..6),
3644                mi in 0usize..4,
3645                mj in 0usize..4,
3646            ) {
3647                prop_assume!(mi != mj);
3648                let mut env = make_env();
3649                let children: Vec<Cfg31G> = idxs.iter().map(|&i| env.atoms[i]).collect();
3650                let op = op_of(&env, k);
3651                let node = env.eg.add(op, &children);
3652
3653                env.eg.merge(env.atoms[mi], env.atoms[mj]);
3654                env.eg.rebuild();
3655
3656                let expected = ref_normal(&mut env, k, &children);
3657                prop_assert_eq!(
3658                    env.eg.find(node),
3659                    env.eg.find(expected),
3660                    "recanonize vs reference: kind={:?} idxs={:?} merge {}->{}", k, idxs, mi, mj
3661                );
3662            }
3663        }
3664    }
3665
3666    #[test]
3667    fn congruence_plain() {
3668        let (ref mut eg, th) = eg::<false, false>();
3669        let x = eg.add(th.x, &[]);
3670        let y = eg.add(th.y, &[]);
3671        let fx = eg.add(th.f, &[x]);
3672        let fy = eg.add(th.f, &[y]);
3673        assert_ne!(eg.find(fx), eg.find(fy));
3674        eg.merge(x, y);
3675        eg.rebuild();
3676        assert_eq!(eg.find(fx), eg.find(fy));
3677    }
3678
3679    #[test]
3680    fn commutative_dedup() {
3681        let (ref mut eg, th) = eg::<false, false>();
3682        let x = eg.add(th.x, &[]);
3683        let y = eg.add(th.y, &[]);
3684        assert_eq!(eg.add(th.eq, &[x, y]), eg.add(th.eq, &[y, x]));
3685    }
3686
3687    // The per-class min-monomial pool column for the `plus` op tracks the degree-lex-least
3688    // `plus`-monomial across merges, and rolls back with the e-graph token. A leaf constant is
3689    // NOT a `plus`-monomial (it has no `plus` column); merging it in makes the class `atomic`
3690    // rather than lowering the `plus` column. See design §9a and the pool design in
3691    // `doc/design/ac-algebraic-properties.md`.
3692    #[test]
3693    fn min_monomial_tracks_least_and_rolls_back() {
3694        let (ref mut eg, th) = eg::<true, false>();
3695        let x = eg.add(th.x, &[]);
3696        let y = eg.add(th.y, &[]);
3697        let z = eg.add(th.z, &[]);
3698        let c = eg.add(th.w, &[]); // a leaf constant, to merge a sum into
3699        let s_xy = eg.add(th.plus, &[x, y]); // +{x,y}, size 2
3700        let s_xyz = eg.add(th.plus, &[x, y, z]); // +{x,y,z}, size 3
3701
3702        // A fresh `plus` node's class holds itself in the `plus` column; a non-completion
3703        // constant has no completion column at all.
3704        assert_eq!(eg.class_min_monomial(s_xy), Some(s_xy));
3705        assert_eq!(eg.class_min_monomial(c), None);
3706
3707        // Merge the two sums: the smaller monomial (+{x,y}, size 2) wins over +{x,y,z}.
3708        eg.merge(s_xy, s_xyz);
3709        let repr_min = eg.class_min_monomial(s_xy).unwrap();
3710        assert_eq!(eg.class_repr(repr_min), eg.class_repr(s_xy));
3711        assert_eq!(repr_min, s_xy, "min_monomial should pick the smaller sum");
3712
3713        // Snapshot, then merge the leaf constant c in: the class becomes `atomic` (a constant
3714        // is its normal-form representative), while the `plus` column still holds the sum.
3715        let token = eg.mark(ShrinkPolicy::Never);
3716        eg.merge(c, s_xy);
3717        assert_eq!(
3718            eg.class_atomic(c),
3719            Some(true),
3720            "merging a constant in makes the class atomic"
3721        );
3722        assert_eq!(
3723            eg.class_min_monomial(s_xy),
3724            Some(s_xy),
3725            "the plus column keeps the least sum after the constant merge"
3726        );
3727
3728        // Restore: the post-token merge is undone, atomicity reverts.
3729        eg.restore(token);
3730        assert_eq!(
3731            eg.class_min_monomial(s_xy),
3732            Some(s_xy),
3733            "min_monomial must roll back with the e-graph token"
3734        );
3735        assert_eq!(
3736            eg.class_atomic(s_xy),
3737            Some(false),
3738            "atomicity must roll back with the e-graph token"
3739        );
3740    }
3741
3742    #[test]
3743    fn congruence_undone_by_restore() {
3744        let (ref mut eg, th) = eg::<true, false>();
3745        let x = eg.add(th.x, &[]);
3746        let y = eg.add(th.y, &[]);
3747        let fx = eg.add(th.f, &[x]);
3748        let fy = eg.add(th.f, &[y]);
3749        let token = eg.mark(ShrinkPolicy::Never);
3750        eg.merge(x, y);
3751        eg.rebuild();
3752        assert_eq!(eg.find(fx), eg.find(fy));
3753        eg.restore(token);
3754        assert_ne!(eg.find(fx), eg.find(fy));
3755    }
3756
3757    #[test]
3758    fn cascading_congruence() {
3759        let (ref mut eg, th) = eg::<false, false>();
3760        let x = eg.add(th.x, &[]);
3761        let y = eg.add(th.y, &[]);
3762        let fx = eg.add(th.f, &[x]);
3763        let fy = eg.add(th.f, &[y]);
3764        let ffx = eg.add(th.f, &[fx]);
3765        let ffy = eg.add(th.f, &[fy]);
3766        eg.merge(x, y);
3767        eg.rebuild();
3768        assert_eq!(eg.find(ffx), eg.find(ffy));
3769    }
3770
3771    #[test]
3772    fn ac_congruence() {
3773        let (ref mut eg, th) = eg::<false, false>();
3774        let (a, b, c) = (eg.add(th.x, &[]), eg.add(th.y, &[]), eg.add(th.z, &[]));
3775        let n1 = eg.add(th.plus, &[a, b]);
3776        let n2 = eg.add(th.plus, &[a, c]);
3777        eg.merge(b, c);
3778        eg.rebuild();
3779        assert_eq!(eg.find(n1), eg.find(n2));
3780    }
3781
3782    #[test]
3783    fn aci_congruence() {
3784        let (ref mut eg, th) = eg::<false, false>();
3785        let (a, b, c) = (eg.add(th.x, &[]), eg.add(th.y, &[]), eg.add(th.z, &[]));
3786        let n1 = eg.add(th.and, &[a, b]);
3787        let n2 = eg.add(th.and, &[a, c]);
3788        eg.merge(b, c);
3789        eg.rebuild();
3790        assert_eq!(eg.find(n1), eg.find(n2));
3791    }
3792
3793    #[test]
3794    fn aci_dedup_after_merge() {
3795        let (ref mut eg, th) = eg::<false, false>();
3796        let a = eg.add(th.x, &[]);
3797        let b = eg.add(th.y, &[]);
3798        let ab = eg.add(th.and, &[a, b]);
3799        let aa = eg.add(th.and, &[a]);
3800        eg.merge(a, b);
3801        eg.rebuild();
3802        assert_eq!(eg.find(ab), eg.find(aa));
3803    }
3804
3805    #[test]
3806    fn hashcons_dedup() {
3807        let (ref mut eg, th) = eg::<false, false>();
3808        let x = eg.add(th.x, &[]);
3809        assert_eq!(eg.add(th.f, &[x]), eg.add(th.f, &[x]));
3810        assert_eq!(eg.len(), 2);
3811    }
3812
3813    #[test]
3814    fn add_canonicalizes() {
3815        let (ref mut eg, th) = eg::<false, false>();
3816        let x = eg.add(th.x, &[]);
3817        let y = eg.add(th.y, &[]);
3818        let fx = eg.add(th.f, &[x]);
3819        eg.merge(x, y);
3820        assert_eq!(fx, eg.add(th.f, &[y]));
3821    }
3822
3823    #[test]
3824    fn rebuild_empty() {
3825        let (ref mut eg, _) = eg::<false, false>();
3826        eg.rebuild();
3827    }
3828
3829    #[test]
3830    fn add_after_restore() {
3831        let (ref mut eg, th) = eg::<true, false>();
3832        let x = eg.add(th.x, &[]);
3833        let token = eg.mark(ShrinkPolicy::Never);
3834        eg.add(th.f, &[x]);
3835        assert_eq!(eg.len(), 2);
3836        eg.restore(token);
3837        assert_eq!(eg.len(), 1);
3838        let gxx = eg.add(th.g, &[x, x]);
3839        assert_eq!(gxx, eg.add(th.g, &[x, x]));
3840    }
3841
3842    #[test]
3843    fn rebuild_after_restore() {
3844        let (ref mut eg, th) = eg::<true, false>();
3845        let (x, y, z) = (eg.add(th.x, &[]), eg.add(th.y, &[]), eg.add(th.z, &[]));
3846        let (fx, fy, fz) = (eg.add(th.f, &[x]), eg.add(th.f, &[y]), eg.add(th.f, &[z]));
3847        let token = eg.mark(ShrinkPolicy::Never);
3848        eg.merge(x, y);
3849        eg.rebuild();
3850        assert_eq!(eg.find(fx), eg.find(fy));
3851        eg.restore(token);
3852        assert_ne!(eg.find(fx), eg.find(fy));
3853        eg.merge(x, z);
3854        eg.rebuild();
3855        assert_eq!(eg.find(fx), eg.find(fz));
3856        assert_ne!(eg.find(fx), eg.find(fy));
3857    }
3858
3859    // -- Proofs --
3860
3861    #[test]
3862    fn explain_non_equivalent() {
3863        let (ref mut eg, th) = eg::<false, true>();
3864        let x = eg.add(th.x, &[]);
3865        let y = eg.add(th.y, &[]);
3866        let mut buf = ProofBuf::new();
3867        assert!(!eg.explain(x, y, &mut buf));
3868    }
3869
3870    #[test]
3871    fn explain_axiom() {
3872        let (ref mut eg, th) = eg::<false, true>();
3873        let x = eg.add(th.x, &[]);
3874        let y = eg.add(th.y, &[]);
3875        eg.merge_justified(
3876            x,
3877            y,
3878            Justification::Axiom {
3879                axiom_id: crate::id::AxiomId::new(42),
3880            },
3881        );
3882        let mut buf = ProofBuf::new();
3883        eg.explain(x, y, &mut buf);
3884        assert!(buf.steps.iter().any(|&(_, _, j)| j
3885            == Justification::Axiom {
3886                axiom_id: crate::id::AxiomId::new(42)
3887            }));
3888    }
3889
3890    #[test]
3891    fn explain_chain() {
3892        let (ref mut eg, th) = eg::<false, true>();
3893        let x = eg.add(th.x, &[]);
3894        let y = eg.add(th.y, &[]);
3895        let z = eg.add(th.z, &[]);
3896        eg.merge_justified(
3897            x,
3898            y,
3899            Justification::Axiom {
3900                axiom_id: crate::id::AxiomId::new(1),
3901            },
3902        );
3903        eg.merge_justified(
3904            y,
3905            z,
3906            Justification::Axiom {
3907                axiom_id: crate::id::AxiomId::new(2),
3908            },
3909        );
3910        let mut buf = ProofBuf::new();
3911        eg.explain(x, z, &mut buf);
3912        for (from, to, just) in &buf.steps {
3913            eprintln!("  {:?} ≡ {:?}  by {:?}", from, to, just);
3914        }
3915        assert!(buf.steps.len() >= 2);
3916    }
3917
3918    #[test]
3919    fn lca_batch_explanations_match_regular_explanations() {
3920        let (ref mut eg, th) = eg::<false, true>();
3921        let nodes = [
3922            eg.add(th.x, &[]),
3923            eg.add(th.y, &[]),
3924            eg.add(th.z, &[]),
3925            eg.add(th.w, &[]),
3926        ];
3927        for (i, &(a, b)) in [
3928            (nodes[0], nodes[1]),
3929            (nodes[2], nodes[3]),
3930            (nodes[1], nodes[2]),
3931        ]
3932        .iter()
3933        .enumerate()
3934        {
3935            eg.merge_justified(
3936                a,
3937                b,
3938                Justification::Axiom {
3939                    axiom_id: crate::id::AxiomId::new(i as u16),
3940                },
3941            );
3942        }
3943
3944        let table = crate::lca::LcaTable::build(
3945            eg.classes
3946                .proof_parent()
3947                .expect("PROOFS=true has a proof forest"),
3948            eg.len(),
3949        );
3950        for node in nodes {
3951            let representative = eg.find_const(node);
3952            let lca = table
3953                .lca(node, representative)
3954                .expect("equivalent nodes share a proof tree");
3955            let mut ordinary = ProofBuf::new();
3956            let mut indexed = ProofBuf::new();
3957            assert!(eg.explain(node, representative, &mut ordinary));
3958            assert!(
3959                eg.classes
3960                    .explain_with_lca(node, representative, lca, &mut indexed)
3961            );
3962            assert_eq!(indexed.steps, ordinary.steps);
3963        }
3964    }
3965
3966    #[test]
3967    fn dump_all_proofs_covers_every_node() {
3968        let (ref mut eg, th) = eg::<false, true>();
3969        let x = eg.add(th.x, &[]);
3970        let y = eg.add(th.y, &[]);
3971        let z = eg.add(th.z, &[]);
3972        eg.merge_justified(
3973            x,
3974            y,
3975            Justification::Axiom {
3976                axiom_id: crate::id::AxiomId::new(7),
3977            },
3978        );
3979        eg.merge_justified(
3980            y,
3981            z,
3982            Justification::Axiom {
3983                axiom_id: crate::id::AxiomId::new(8),
3984            },
3985        );
3986
3987        let mut dump = Vec::new();
3988        let stats = eg.dump_all_proofs(&mut dump).expect("proof dump");
3989        assert_eq!(stats.terms, eg.len());
3990        assert_eq!(stats.nontrivial_proofs, 2);
3991        assert!(stats.steps >= 2);
3992
3993        let text = String::from_utf8(dump).expect("UTF-8 proof dump");
3994        assert!(text.starts_with("# semi-persistent-proof-dump v1\n"));
3995        assert_eq!(
3996            text.lines()
3997                .filter(|line| line.starts_with("term "))
3998                .count(),
3999            3
4000        );
4001        assert!(text.contains("axiom id=7"));
4002        assert!(text.contains("axiom id=8"));
4003        assert!(text.contains("summary terms 3 nontrivial 2"));
4004    }
4005
4006    #[test]
4007    fn dump_all_proofs_rejects_proof_disabled_graph() {
4008        let (ref mut eg, th) = eg::<false, false>();
4009        eg.add(th.x, &[]);
4010        let err = eg
4011            .dump_all_proofs(Vec::new())
4012            .expect_err("PROOFS=false must reject proof dumps");
4013        assert_eq!(err.kind(), std::io::ErrorKind::InvalidInput);
4014    }
4015
4016    #[test]
4017    fn explain_after_restore() {
4018        let (ref mut eg, th) = eg::<true, true>();
4019        let x = eg.add(th.x, &[]);
4020        let y = eg.add(th.y, &[]);
4021        let token = eg.mark(ShrinkPolicy::Never);
4022        eg.merge_justified(
4023            x,
4024            y,
4025            Justification::Axiom {
4026                axiom_id: crate::id::AxiomId::new(0),
4027            },
4028        );
4029        let mut buf = ProofBuf::new();
4030        assert!(eg.explain(x, y, &mut buf));
4031        eg.restore(token);
4032        buf.clear();
4033        assert!(!eg.explain(x, y, &mut buf));
4034    }
4035
4036    /// Regression: `union()` on a PROOFS=true UF must panic, not silently
4037    /// leave a stale justification.
4038    #[test]
4039    #[should_panic(expected = "union() called on a PROOFS=true UnionFind")]
4040    fn union_without_justification_panics_on_proofs() {
4041        let (ref mut eg, th) = eg::<false, true>();
4042        let x = eg.add(th.x, &[]);
4043        let y = eg.add(th.y, &[]);
4044        eg.merge(x, y); // must panic
4045    }
4046
4047    /// Every step returned by `explain()` must carry the justification that
4048    /// was explicitly provided via `merge_justified`, never a stale default.
4049    #[test]
4050    fn explain_no_stale_justifications() {
4051        let (ref mut eg, th) = eg::<false, true>();
4052        let x = eg.add(th.x, &[]);
4053        let y = eg.add(th.y, &[]);
4054        let z = eg.add(th.z, &[]);
4055        let ax1 = crate::id::AxiomId::new(10);
4056        let ax2 = crate::id::AxiomId::new(20);
4057        eg.merge_justified(x, y, Justification::Axiom { axiom_id: ax1 });
4058        eg.merge_justified(y, z, Justification::Axiom { axiom_id: ax2 });
4059        let mut buf = ProofBuf::new();
4060        eg.explain(x, z, &mut buf);
4061        for &(_, _, just) in &buf.steps {
4062            match just {
4063                Justification::Axiom { axiom_id } => {
4064                    assert!(
4065                        axiom_id == ax1 || axiom_id == ax2,
4066                        "unexpected axiom_id {axiom_id:?} in proof step"
4067                    );
4068                }
4069                Justification::Congruence { .. } => {}
4070                Justification::Rewrite { .. } => {}
4071                Justification::Filler => unreachable!("filler is never a real proof step"),
4072                Justification::ACSuperposition { .. }
4073                | Justification::ACInterReduction { .. }
4074                | Justification::ACAxiomCP { .. }
4075                | Justification::Cancellative { .. }
4076                | Justification::InverseCancel { .. } => {
4077                    panic!("algebraic justification in a non-completion test")
4078                }
4079            }
4080        }
4081    }
4082
4083    // -- Rebuild coverage ---------------------------------------------------
4084
4085    /// Plain3 congruence: h(x,y,z) ≡ h(w,y,z) after merge(x,w)
4086    #[test]
4087    fn congruence_plain3() {
4088        let (ref mut eg, th) = eg::<false, false>();
4089        let (x, y, z, w) = (
4090            eg.add(th.x, &[]),
4091            eg.add(th.y, &[]),
4092            eg.add(th.z, &[]),
4093            eg.add(th.w, &[]),
4094        );
4095        let n1 = eg.add(th.h, &[x, y, z]);
4096        let n2 = eg.add(th.h, &[w, y, z]);
4097        eg.merge(x, w);
4098        eg.rebuild();
4099        assert_eq!(eg.find(n1), eg.find(n2));
4100    }
4101
4102    /// C-node congruence: eq(a,b) and eq(w,c) collide after merge(a,w), merge(b,c)
4103    #[test]
4104    fn commutative_congruence() {
4105        let (ref mut eg, th) = eg::<false, false>();
4106        let (a, b, c, w) = (
4107            eg.add(th.x, &[]),
4108            eg.add(th.y, &[]),
4109            eg.add(th.z, &[]),
4110            eg.add(th.w, &[]),
4111        );
4112        let e1 = eg.add(th.eq, &[a, b]);
4113        let e2 = eg.add(th.eq, &[w, c]);
4114        eg.merge(a, w);
4115        eg.merge(b, c);
4116        eg.rebuild();
4117        assert_eq!(eg.find(e1), eg.find(e2));
4118    }
4119
4120    /// C-node: find changes order but no collision (just reindex)
4121    #[test]
4122    fn commutative_reorder_no_collision() {
4123        let (ref mut eg, th) = eg::<false, false>();
4124        let (a, b) = (eg.add(th.x, &[]), eg.add(th.y, &[]));
4125        let e = eg.add(th.eq, &[a, b]);
4126        eg.merge(a, b);
4127        eg.rebuild();
4128        let _ = eg.find(e);
4129    }
4130
4131    /// PlainN congruence: f4(a,b,c,d) ≡ f4(a,e,c,d) after merge(b,e)
4132    #[test]
4133    fn plain_n_congruence() {
4134        let (ref mut eg, th) = eg::<false, false>();
4135        let a = eg.add(th.x, &[]);
4136        let b = eg.add(th.y, &[]);
4137        let c = eg.add(th.z, &[]);
4138        let d = eg.add(th.w, &[]);
4139        let e_op = eg.register_op0("e", th.int);
4140        let e = eg.add(e_op, &[]);
4141        let n1 = eg.add(th.f4, &[a, b, c, d]);
4142        let n2 = eg.add(th.f4, &[a, e, c, d]);
4143        eg.merge(b, e);
4144        eg.rebuild();
4145        assert_eq!(eg.find(n1), eg.find(n2));
4146    }
4147
4148    /// A-node congruence (associative, ordered)
4149    #[test]
4150    fn a_congruence() {
4151        let (ref mut eg, th) = eg::<false, false>();
4152        let (a, b, c) = (eg.add(th.x, &[]), eg.add(th.y, &[]), eg.add(th.z, &[]));
4153        let n1 = eg.add(th.sub, &[a, b]);
4154        let n2 = eg.add(th.sub, &[a, c]);
4155        eg.merge(b, c);
4156        eg.rebuild();
4157        assert_eq!(eg.find(n1), eg.find(n2));
4158    }
4159
4160    /// The flattening guard must count expansion work, not only emitted output.
4161    /// A malformed self-expansion emits nothing, so the former `out.len()` guard
4162    /// never advanced and this call looped forever. Production construction cannot
4163    /// create this state; mutating the private child pool models defensive handling
4164    /// of corrupted data at the exact boundary the guard protects.
4165    #[test]
4166    #[should_panic(expected = "flatten_seq_children exceeded work cap")]
4167    fn associative_flatten_refuses_nonprogressing_cycle() {
4168        let (ref mut eg, th) = eg::<false, false>();
4169        let a = eg.add(th.x, &[]);
4170        let seq = eg.add(th.sub, &[a, a]);
4171        let NodeRef::Seq(local) = eg.node_ref(seq) else {
4172            panic!("associative node must use the Seq partition");
4173        };
4174        let (start, end) = eg.nodes.seq.get(local).span();
4175        assert_eq!(end - start, 2);
4176        eg.nodes.seq.pool_set(start, seq);
4177        eg.nodes.seq.pool_set(start + 1, seq);
4178
4179        eg.g_buf.clear();
4180        eg.g_buf.push(seq);
4181        eg.flatten_seq_children(th.sub);
4182    }
4183
4184    /// AC: different multiplicities after merge → no false collision
4185    #[test]
4186    fn ac_multiplicity_no_false_collision() {
4187        let (ref mut eg, th) = eg::<false, false>();
4188        let (a, b, c, d) = (
4189            eg.add(th.x, &[]),
4190            eg.add(th.y, &[]),
4191            eg.add(th.z, &[]),
4192            eg.add(th.w, &[]),
4193        );
4194        let n1 = eg.add(th.plus, &[a, b, c]); // plus(a,b,c)
4195        let n2 = eg.add(th.plus, &[a, d]); // plus(a,d)
4196        eg.merge(b, d);
4197        eg.merge(c, d);
4198        eg.rebuild();
4199        // n1 → plus(a,2*repr_d), n2 → plus(a,repr_d) — NOT equal
4200        assert_ne!(eg.find(n1), eg.find(n2));
4201    }
4202
4203    /// AC shrink: plus(a,a,b) after merge(a,b) → plus((repr,3))
4204    #[test]
4205    fn ac_shrink_after_merge() {
4206        let (ref mut eg, th) = eg::<false, false>();
4207        let a = eg.add(th.x, &[]);
4208        let b = eg.add(th.y, &[]);
4209        let n1 = eg.add(th.plus, &[a, a, b]); // plus((a,2),(b,1))
4210        let n2 = eg.add(th.plus, &[a, a, a]); // plus((a,3))
4211        eg.merge(a, b);
4212        eg.rebuild();
4213        assert_eq!(eg.find(n1), eg.find(n2));
4214    }
4215
4216    /// Multiple merges before rebuild: worklist starts with >1 entry
4217    #[test]
4218    fn multiple_merges_before_rebuild() {
4219        let (ref mut eg, th) = eg::<false, false>();
4220        let (a, b, c, d) = (
4221            eg.add(th.x, &[]),
4222            eg.add(th.y, &[]),
4223            eg.add(th.z, &[]),
4224            eg.add(th.w, &[]),
4225        );
4226        let fa = eg.add(th.f, &[a]);
4227        let fb = eg.add(th.f, &[b]);
4228        let fc = eg.add(th.f, &[c]);
4229        let fd = eg.add(th.f, &[d]);
4230        eg.merge(a, b);
4231        eg.merge(c, d);
4232        eg.rebuild();
4233        assert_eq!(eg.find(fa), eg.find(fb));
4234        assert_eq!(eg.find(fc), eg.find(fd));
4235        assert_ne!(eg.find(fa), eg.find(fc));
4236    }
4237
4238    /// Diamond: g(a,b) uses both a and b; merge a and b
4239    #[test]
4240    fn diamond_fan_in() {
4241        let (ref mut eg, th) = eg::<false, false>();
4242        let (a, b) = (eg.add(th.x, &[]), eg.add(th.y, &[]));
4243        let gab = eg.add(th.g, &[a, b]);
4244        eg.merge(a, b);
4245        eg.rebuild();
4246        let _ = eg.find(gab);
4247    }
4248
4249    /// Fan-out: many parents of different kinds share the same child
4250    #[test]
4251    fn fan_out_many_parents() {
4252        let (ref mut eg, th) = eg::<false, false>();
4253        let a = eg.add(th.x, &[]);
4254        let b = eg.add(th.y, &[]);
4255        let p0 = eg.add(th.f, &[a]);
4256        let p1 = eg.add(th.g, &[a, a]);
4257        let p2 = eg.add(th.eq, &[a, a]);
4258        let p3 = eg.add(th.plus, &[a, b]);
4259        let p4 = eg.add(th.and, &[a, b]);
4260        eg.merge(a, b);
4261        eg.rebuild();
4262        for &p in &[p0, p1, p2, p3, p4] {
4263            let _ = eg.find(p);
4264        }
4265    }
4266
4267    /// Deep cascade: merge at leaf propagates through 4 levels
4268    #[test]
4269    fn deep_cascade_4_levels() {
4270        let (ref mut eg, th) = eg::<false, false>();
4271        let (a, b) = (eg.add(th.x, &[]), eg.add(th.y, &[]));
4272        let fa = eg.add(th.f, &[a]);
4273        let fb = eg.add(th.f, &[b]);
4274        let ffa = eg.add(th.f, &[fa]);
4275        let ffb = eg.add(th.f, &[fb]);
4276        let fffa = eg.add(th.f, &[ffa]);
4277        let fffb = eg.add(th.f, &[ffb]);
4278        let ffffa = eg.add(th.f, &[fffa]);
4279        let ffffb = eg.add(th.f, &[fffb]);
4280        eg.merge(a, b);
4281        eg.rebuild();
4282        assert_eq!(eg.find(ffffa), eg.find(ffffb));
4283    }
4284
4285    #[test]
4286    fn egraph63_smoke() {
4287        let mut eg = EGraph63::<NiraLitVal, false, false>::new();
4288        let int = eg.intern_sort("Int");
4289        let f = eg.register_op1("f", int, int);
4290        let x_op = eg.register_op0("x", int);
4291        let y_op = eg.register_op0("y", int);
4292        let x = eg.add(x_op, &[]);
4293        let y = eg.add(y_op, &[]);
4294        let fx = eg.add(f, &[x]);
4295        let fy = eg.add(f, &[y]);
4296        eg.merge(x, y);
4297        eg.rebuild();
4298        assert_eq!(eg.find(fx), eg.find(fy));
4299    }
4300
4301    #[test]
4302    fn from_model_registers_builtins() {
4303        use crate::literal::NiraModel;
4304        let model = NiraModel;
4305        let eg = EGraph31::<NiraLitVal, false, false>::from_model(&model);
4306        for sort_desc in model.sorts() {
4307            let id = eg.sorts().id_by_name(sort_desc.name).unwrap();
4308            assert!(
4309                eg.sorts().is_builtin(id),
4310                "sort '{}' should be builtin",
4311                sort_desc.name
4312            );
4313        }
4314        for op_desc in model.ops() {
4315            let id = eg.ops().id_by_name(op_desc.name).unwrap();
4316            assert!(
4317                eg.ops().is_builtin(id),
4318                "op '{}' should be builtin",
4319                op_desc.name
4320            );
4321        }
4322    }
4323
4324    #[test]
4325    #[should_panic(expected = "already registered")]
4326    fn from_model_rejects_op_collision() {
4327        use crate::literal::NiraModel;
4328        let mut eg = EGraph31::<NiraLitVal, false, false>::from_model(&NiraModel);
4329        let int = eg.intern_sort("Int");
4330        // "+" is a builtin op from NiraModel, registering again should panic
4331        eg.register_op2("+", int, int, int);
4332    }
4333
4334    // Multiple MSet symbols are now supported (per-op min-monomial pool, step 4): rebuild with
4335    // two AC ops registered no longer panics. (End-to-end independence is checked by the
4336    // `ac_complete_multi_mset.egg` fixture.)
4337    #[test]
4338    fn cc_allows_two_mset_symbols() {
4339        let mut eg = EGraph31::<NiraLitVal, false, false>::new();
4340        let int = eg.intern_sort("Int");
4341        let _plus = eg.register_mset("plus", int, int);
4342        let _times = eg.register_mset("times", int, int);
4343        eg.set_cc(true);
4344        eg.rebuild(); // two MSet ops => allowed, completes each independently
4345    }
4346
4347    // One MSet op plus a Set (ACI) op is fine.
4348    #[test]
4349    fn cc_allows_one_mset_symbol() {
4350        let mut eg = EGraph31::<NiraLitVal, false, false>::new();
4351        let int = eg.intern_sort("Int");
4352        let _plus = eg.register_mset("plus", int, int);
4353        let _and = eg.register_set("and", int, int);
4354        eg.set_cc(true);
4355        eg.rebuild();
4356    }
4357}
4358
4359/// Run all core e-graph tests with both 31-bit and 63-bit configs.
4360#[cfg(test)]
4361mod dual_config_tests {
4362    use crate::canon::{MSetCanon, VarCanon};
4363    use crate::config::EGraphConfig;
4364    use crate::containers::ShrinkPolicy;
4365    use crate::egraph::EGraph;
4366    use crate::literal::NiraLitVal;
4367    use crate::union_find::{Justification, ProofBuf};
4368
4369    struct Th<Cfg: EGraphConfig> {
4370        x: Cfg::O,
4371        y: Cfg::O,
4372        z: Cfg::O,
4373        w: Cfg::O,
4374        f: Cfg::O,
4375        h: Cfg::O,
4376        eq: Cfg::O,
4377        plus: Cfg::O,
4378        and: Cfg::O,
4379        sub: Cfg::O,
4380        f4: Cfg::O,
4381        lit_op: Cfg::O,
4382    }
4383
4384    fn setup<Cfg: EGraphConfig, const T: bool, const P: bool>()
4385    -> (EGraph<Cfg, NiraLitVal, T, P>, Th<Cfg>)
4386    where
4387        MSetCanon: VarCanon<Cfg::G, Cfg::C>,
4388    {
4389        let mut eg = EGraph::new();
4390        let int = eg.intern_sort("Int");
4391        let th = Th {
4392            x: eg.register_op0("x", int),
4393            y: eg.register_op0("y", int),
4394            z: eg.register_op0("z", int),
4395            w: eg.register_op0("w", int),
4396            f: eg.register_op1("f", int, int),
4397            h: eg.register_op3("h", int, int, int, int),
4398            eq: eg.register_c("eq", [int, int], int),
4399            plus: eg.register_mset("plus", int, int),
4400            and: eg.register_set("and", int, int),
4401            sub: eg.register_a("sub", int, int, crate::registry::AssocDir::Left),
4402            f4: eg.register_opn("f4", &[int, int, int, int], int),
4403            lit_op: eg.register_lit("lit", int),
4404        };
4405        (eg, th)
4406    }
4407
4408    macro_rules! dual {
4409        ($(fn $name:ident<$Cfg:ident>() $body:block)*) => {$(
4410            mod $name {
4411                use super::*;
4412                fn run<$Cfg: EGraphConfig>() where MSetCanon: VarCanon<$Cfg::G, $Cfg::C> $body
4413                #[test] fn bits31() { run::<crate::nodes::DefaultConfig>(); }
4414                #[test] fn bits63() { run::<crate::nodes::Config64>(); }
4415            }
4416        )*};
4417    }
4418
4419    dual! {
4420        fn congruence_plain<Cfg>() {
4421            let (ref mut eg, th) = setup::<Cfg, false, false>();
4422            let x = eg.add(th.x, &[]);
4423            let y = eg.add(th.y, &[]);
4424            let fx = eg.add(th.f, &[x]);
4425            let fy = eg.add(th.f, &[y]);
4426            eg.merge(x, y);
4427            eg.rebuild();
4428            assert_eq!(eg.find(fx), eg.find(fy));
4429        }
4430
4431        fn commutative_dedup<Cfg>() {
4432            let (ref mut eg, th) = setup::<Cfg, false, false>();
4433            let x = eg.add(th.x, &[]);
4434            let y = eg.add(th.y, &[]);
4435            assert_eq!(eg.add(th.eq, &[x, y]), eg.add(th.eq, &[y, x]));
4436        }
4437
4438        fn cascading_congruence<Cfg>() {
4439            let (ref mut eg, th) = setup::<Cfg, false, false>();
4440            let x = eg.add(th.x, &[]);
4441            let y = eg.add(th.y, &[]);
4442            let fx = eg.add(th.f, &[x]);
4443            let fy = eg.add(th.f, &[y]);
4444            let ffx = eg.add(th.f, &[fx]);
4445            let ffy = eg.add(th.f, &[fy]);
4446            eg.merge(x, y);
4447            eg.rebuild();
4448            assert_eq!(eg.find(ffx), eg.find(ffy));
4449        }
4450
4451        fn ac_congruence<Cfg>() {
4452            let (ref mut eg, th) = setup::<Cfg, false, false>();
4453            let (a, b, c) = (eg.add(th.x, &[]), eg.add(th.y, &[]), eg.add(th.z, &[]));
4454            let n1 = eg.add(th.plus, &[a, b]);
4455            let n2 = eg.add(th.plus, &[a, c]);
4456            eg.merge(b, c);
4457            eg.rebuild();
4458            assert_eq!(eg.find(n1), eg.find(n2));
4459        }
4460
4461        fn aci_congruence<Cfg>() {
4462            let (ref mut eg, th) = setup::<Cfg, false, false>();
4463            let (a, b, c) = (eg.add(th.x, &[]), eg.add(th.y, &[]), eg.add(th.z, &[]));
4464            let n1 = eg.add(th.and, &[a, b]);
4465            let n2 = eg.add(th.and, &[a, c]);
4466            eg.merge(b, c);
4467            eg.rebuild();
4468            assert_eq!(eg.find(n1), eg.find(n2));
4469        }
4470
4471        fn aci_dedup_after_merge<Cfg>() {
4472            let (ref mut eg, th) = setup::<Cfg, false, false>();
4473            let a = eg.add(th.x, &[]);
4474            let b = eg.add(th.y, &[]);
4475            let ab = eg.add(th.and, &[a, b]);
4476            let aa = eg.add(th.and, &[a]);
4477            eg.merge(a, b);
4478            eg.rebuild();
4479            assert_eq!(eg.find(ab), eg.find(aa));
4480        }
4481
4482        fn hashcons_dedup<Cfg>() {
4483            let (ref mut eg, th) = setup::<Cfg, false, false>();
4484            let x = eg.add(th.x, &[]);
4485            assert_eq!(eg.add(th.f, &[x]), eg.add(th.f, &[x]));
4486            assert_eq!(eg.len(), 2);
4487        }
4488
4489        fn add_canonicalizes<Cfg>() {
4490            let (ref mut eg, th) = setup::<Cfg, false, false>();
4491            let x = eg.add(th.x, &[]);
4492            let y = eg.add(th.y, &[]);
4493            let fx = eg.add(th.f, &[x]);
4494            eg.merge(x, y);
4495            assert_eq!(fx, eg.add(th.f, &[y]));
4496        }
4497
4498        fn congruence_undone_by_restore<Cfg>() {
4499            let (ref mut eg, th) = setup::<Cfg, true, false>();
4500            let x = eg.add(th.x, &[]);
4501            let y = eg.add(th.y, &[]);
4502            let fx = eg.add(th.f, &[x]);
4503            let fy = eg.add(th.f, &[y]);
4504            let token = eg.mark(ShrinkPolicy::Never);
4505            eg.merge(x, y);
4506            eg.rebuild();
4507            assert_eq!(eg.find(fx), eg.find(fy));
4508            eg.restore(token);
4509            assert_ne!(eg.find(fx), eg.find(fy));
4510        }
4511
4512        fn rebuild_after_restore<Cfg>() {
4513            let (ref mut eg, th) = setup::<Cfg, true, false>();
4514            let (x, y, z) = (eg.add(th.x, &[]), eg.add(th.y, &[]), eg.add(th.z, &[]));
4515            let (fx, fy, fz) = (eg.add(th.f, &[x]), eg.add(th.f, &[y]), eg.add(th.f, &[z]));
4516            let token = eg.mark(ShrinkPolicy::Never);
4517            eg.merge(x, y);
4518            eg.rebuild();
4519            assert_eq!(eg.find(fx), eg.find(fy));
4520            eg.restore(token);
4521            assert_ne!(eg.find(fx), eg.find(fy));
4522            eg.merge(x, z);
4523            eg.rebuild();
4524            assert_eq!(eg.find(fx), eg.find(fz));
4525            assert_ne!(eg.find(fx), eg.find(fy));
4526        }
4527
4528        fn congruence_plain3<Cfg>() {
4529            let (ref mut eg, th) = setup::<Cfg, false, false>();
4530            let (x, y, z, w) = (eg.add(th.x, &[]), eg.add(th.y, &[]), eg.add(th.z, &[]), eg.add(th.w, &[]));
4531            let n1 = eg.add(th.h, &[x, y, z]);
4532            let n2 = eg.add(th.h, &[w, y, z]);
4533            eg.merge(x, w);
4534            eg.rebuild();
4535            assert_eq!(eg.find(n1), eg.find(n2));
4536        }
4537
4538        fn commutative_congruence<Cfg>() {
4539            let (ref mut eg, th) = setup::<Cfg, false, false>();
4540            let (a, b, c, w) = (eg.add(th.x, &[]), eg.add(th.y, &[]), eg.add(th.z, &[]), eg.add(th.w, &[]));
4541            let e1 = eg.add(th.eq, &[a, b]);
4542            let e2 = eg.add(th.eq, &[w, c]);
4543            eg.merge(a, w);
4544            eg.merge(b, c);
4545            eg.rebuild();
4546            assert_eq!(eg.find(e1), eg.find(e2));
4547        }
4548
4549        fn a_congruence<Cfg>() {
4550            let (ref mut eg, th) = setup::<Cfg, false, false>();
4551            let (a, b, c) = (eg.add(th.x, &[]), eg.add(th.y, &[]), eg.add(th.z, &[]));
4552            let n1 = eg.add(th.sub, &[a, b]);
4553            let n2 = eg.add(th.sub, &[a, c]);
4554            eg.merge(b, c);
4555            eg.rebuild();
4556            assert_eq!(eg.find(n1), eg.find(n2));
4557        }
4558
4559        fn ac_shrink_after_merge<Cfg>() {
4560            let (ref mut eg, th) = setup::<Cfg, false, false>();
4561            let a = eg.add(th.x, &[]);
4562            let b = eg.add(th.y, &[]);
4563            let n1 = eg.add(th.plus, &[a, a, b]);
4564            let n2 = eg.add(th.plus, &[a, a, a]);
4565            eg.merge(a, b);
4566            eg.rebuild();
4567            assert_eq!(eg.find(n1), eg.find(n2));
4568        }
4569
4570        fn deep_cascade_4_levels<Cfg>() {
4571            let (ref mut eg, th) = setup::<Cfg, false, false>();
4572            let (a, b) = (eg.add(th.x, &[]), eg.add(th.y, &[]));
4573            let fa = eg.add(th.f, &[a]);
4574            let fb = eg.add(th.f, &[b]);
4575            let ffa = eg.add(th.f, &[fa]);
4576            let ffb = eg.add(th.f, &[fb]);
4577            let fffa = eg.add(th.f, &[ffa]);
4578            let fffb = eg.add(th.f, &[ffb]);
4579            let ffffa = eg.add(th.f, &[fffa]);
4580            let ffffb = eg.add(th.f, &[fffb]);
4581            eg.merge(a, b);
4582            eg.rebuild();
4583            assert_eq!(eg.find(ffffa), eg.find(ffffb));
4584        }
4585
4586        fn multiple_merges_before_rebuild<Cfg>() {
4587            let (ref mut eg, th) = setup::<Cfg, false, false>();
4588            let (a, b, c, d) = (eg.add(th.x, &[]), eg.add(th.y, &[]), eg.add(th.z, &[]), eg.add(th.w, &[]));
4589            let fa = eg.add(th.f, &[a]);
4590            let fb = eg.add(th.f, &[b]);
4591            let fc = eg.add(th.f, &[c]);
4592            let fd = eg.add(th.f, &[d]);
4593            eg.merge(a, b);
4594            eg.merge(c, d);
4595            eg.rebuild();
4596            assert_eq!(eg.find(fa), eg.find(fb));
4597            assert_eq!(eg.find(fc), eg.find(fd));
4598            assert_ne!(eg.find(fa), eg.find(fc));
4599        }
4600
4601        fn explain_proof<Cfg>() {
4602            let (ref mut eg, th) = setup::<Cfg, false, true>();
4603            let x = eg.add(th.x, &[]);
4604            let y = eg.add(th.y, &[]);
4605            let z = eg.add(th.z, &[]);
4606            eg.merge_justified(x, y, Justification::Axiom { axiom_id: crate::id::AxiomId::new(1) });
4607            eg.merge_justified(y, z, Justification::Axiom { axiom_id: crate::id::AxiomId::new(2) });
4608            let mut buf = ProofBuf::new();
4609            eg.explain(x, z, &mut buf);
4610            assert!(buf.steps.len() >= 2);
4611        }
4612
4613        fn explain_deep_congruence<Cfg>() {
4614            let (ref mut eg, th) = setup::<Cfg, false, true>();
4615            let x = eg.add(th.x, &[]);
4616            let y = eg.add(th.y, &[]);
4617            let fx = eg.add(th.f, &[x]);
4618            let fy = eg.add(th.f, &[y]);
4619            eg.merge_justified(x, y, Justification::Axiom { axiom_id: crate::id::AxiomId::new(10) });
4620            eg.rebuild();
4621            assert_eq!(eg.find(fx), eg.find(fy));
4622            let mut buf = ProofBuf::new();
4623            assert!(eg.explain_deep(fx, fy, &mut buf));
4624            assert!(buf.steps.iter().any(|(_, _, j)| matches!(j, Justification::Congruence { .. })));
4625            assert!(buf.steps.iter().any(|(_, _, j)| *j == Justification::Axiom { axiom_id: crate::id::AxiomId::new(10) }));
4626        }
4627
4628        fn plain_n_congruence<Cfg>() {
4629            let (ref mut eg, th) = setup::<Cfg, false, false>();
4630            let (x, y, z, w) = (eg.add(th.x, &[]), eg.add(th.y, &[]), eg.add(th.z, &[]), eg.add(th.w, &[]));
4631            let n1 = eg.add(th.f4, &[x, y, z, w]);
4632            let n2 = eg.add(th.f4, &[x, y, z, x]);
4633            eg.merge(w, x);
4634            eg.rebuild();
4635            assert_eq!(eg.find(n1), eg.find(n2));
4636        }
4637
4638        fn a_not_commutative<Cfg>() {
4639            let (ref mut eg, th) = setup::<Cfg, false, false>();
4640            let (a, b) = (eg.add(th.x, &[]), eg.add(th.y, &[]));
4641            let ab = eg.add(th.sub, &[a, b]);
4642            let ba = eg.add(th.sub, &[b, a]);
4643            assert_ne!(eg.find(ab), eg.find(ba));
4644        }
4645
4646        fn lit_node<Cfg>() {
4647            let (ref mut eg, th) = setup::<Cfg, false, false>();
4648            use crate::literal::NiraLitVal;
4649            use num_bigint::BigInt;
4650            let v1 = eg.intern_lit(NiraLitVal::Int(BigInt::from(42)));
4651            let v2 = eg.intern_lit(NiraLitVal::Int(BigInt::from(42)));
4652            assert_eq!(v1, v2);
4653            let n1 = eg.add_lit(th.lit_op, v1);
4654            let n2 = eg.add_lit(th.lit_op, v1);
4655            assert_eq!(n1, n2);
4656            let v3 = eg.intern_lit(NiraLitVal::Int(BigInt::from(99)));
4657            let n3 = eg.add_lit(th.lit_op, v3);
4658            assert_ne!(n1, n3);
4659        }
4660
4661        fn is_empty_check<Cfg>() {
4662            let (ref mut eg, th) = setup::<Cfg, false, false>();
4663            // setup registers ops which add nodes, but is_empty checks node count
4664            let before = eg.len();
4665            let x = eg.add(th.x, &[]);
4666            assert_eq!(eg.len(), before + 1);
4667            let _ = x;
4668        }
4669
4670        fn nested_mark_restore<Cfg>() {
4671            let (ref mut eg, th) = setup::<Cfg, true, false>();
4672            let x = eg.add(th.x, &[]);
4673            let y = eg.add(th.y, &[]);
4674            let z = eg.add(th.z, &[]);
4675            let fx = eg.add(th.f, &[x]);
4676            let fy = eg.add(th.f, &[y]);
4677            let fz = eg.add(th.f, &[z]);
4678            let t1 = eg.mark(ShrinkPolicy::Never);
4679            eg.merge(x, y);
4680            eg.rebuild();
4681            assert_eq!(eg.find(fx), eg.find(fy));
4682            let t2 = eg.mark(ShrinkPolicy::Never);
4683            eg.merge(x, z);
4684            eg.rebuild();
4685            assert_eq!(eg.find(fx), eg.find(fz));
4686            eg.restore(t2);
4687            assert_eq!(eg.find(fx), eg.find(fy));
4688            assert_ne!(eg.find(fx), eg.find(fz));
4689            eg.restore(t1);
4690            assert_ne!(eg.find(fx), eg.find(fy));
4691            assert_ne!(eg.find(fx), eg.find(fz));
4692        }
4693    }
4694}