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