semi_persistent_egraph/multiset.rs
1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// SPDX-License-Identifier: Apache-2.0
3//! Multiset algebra over canonical AC child slices.
4//!
5//! These are the search-and-arithmetic primitives for AC congruence completion
6//! (superposition / inter-reduction). See `doc/design/ac-completion-spec.md`
7//! and `doc/design/ac-congruence-completeness.md` §6–§7.
8//!
9//! All functions operate on the *canonical* AC child form produced by
10//! [`crate::canon::MSetCanon`]: a slice `&[(G, M)]` that is
11//!
12//! - **sorted ascending by `G`**,
13//! - **duplicate-free in `G`** (multiplicities of equal `G` already summed), and
14//! - **positive** (every multiplicity is `>= 1`; zero entries never appear).
15//!
16//! Inputs are assumed canonical; outputs are canonical by construction. The
17//! invariant is checked under `debug_assert!`. Every function is a single
18//! sorted-merge walk, `O(|a| + |b|)`.
19//!
20//! ## Width
21//!
22//! The multiplicity type `M` is the caller's — in practice
23//! [`EGraphConfig::M`](crate::config::EGraphConfig::M) — not a fixed `u32`, so
24//! these operations neither cap nor narrow the configured width. Of the per-class
25//! combinators only [`multiset_union_into`] increases a multiplicity; the rest
26//! take a max, min, or clamped difference and so cannot overflow. That one, and
27//! the cross-class sum in [`multiset_size`], are checked.
28
29use crate::multiplicity::MultiplicityLike;
30
31/// Raised where a multiset operation would exceed the caller's multiplicity
32/// width. The positivity invariant above makes wrapping actively dangerous: a sum
33/// that wraps to zero produces an entry the canonical form says cannot exist, and
34/// the `retain`-based clamps would then silently delete the summand — turning an
35/// overflow into a wrong equality rather than a failure.
36const SUM_OVERFLOW: &str = "AC multiset multiplicity overflowed its configured width";
37
38/// An AC child: a class id paired with its multiplicity in the multiset.
39type Pair<G, M> = (G, M);
40
41/// Debug-only check that a slice is in canonical AC child form.
42#[inline]
43fn debug_assert_canonical<G: Copy + Ord, M: MultiplicityLike>(m: &[Pair<G, M>]) {
44 debug_assert!(
45 m.windows(2).all(|w| w[0].0 < w[1].0),
46 "AC multiset not strictly sorted / duplicate-free by class id"
47 );
48 debug_assert!(
49 m.iter().all(|(_, mult)| *mult >= M::ONE),
50 "AC multiset has a zero (or absent) multiplicity entry"
51 );
52}
53
54/// Do `a` and `b` share no class id? Disjoint multisets have a trivial critical
55/// pair (their rules commute), so the completion search skips them (spec §6).
56pub fn multiset_disjoint<G: Copy + Ord, M: MultiplicityLike>(
57 a: &[Pair<G, M>],
58 b: &[Pair<G, M>],
59) -> bool {
60 debug_assert_canonical(a);
61 debug_assert_canonical(b);
62 let (mut i, mut j) = (0, 0);
63 while i < a.len() && j < b.len() {
64 match a[i].0.cmp(&b[j].0) {
65 std::cmp::Ordering::Less => i += 1,
66 std::cmp::Ordering::Greater => j += 1,
67 std::cmp::Ordering::Equal => return false,
68 }
69 }
70 true
71}
72
73/// Is `a` a sub-multiset of `b` (`a ⊆ b`)? True iff every class in `a` occurs in
74/// `b` with at least the same multiplicity. This is the (A) inter-reduction test:
75/// the sub-sum `+a` is virtually contained in `+b`.
76pub fn multiset_subset<G: Copy + Ord, M: MultiplicityLike>(
77 a: &[Pair<G, M>],
78 b: &[Pair<G, M>],
79) -> bool {
80 debug_assert_canonical(a);
81 debug_assert_canonical(b);
82 let mut j = 0;
83 for &(ag, am) in a {
84 // Advance b past classes smaller than ag; any such class is in b but not
85 // required by a, which is fine. If we run out of b, a has an element b lacks.
86 while j < b.len() && b[j].0 < ag {
87 j += 1;
88 }
89 if j >= b.len() || b[j].0 != ag || b[j].1 < am {
90 return false;
91 }
92 j += 1;
93 }
94 true
95}
96
97/// Multiset difference `a − b` into `out` (cleared first): per-class multiplicity
98/// subtraction, clamped at zero, with zero results dropped. Classes in `b` but not
99/// `a` are ignored. `out` must not alias `a` or `b`.
100///
101/// Destination-passing form for the completion hot loop (design §9a). Computes the
102/// residual `M − A` when substituting a known sub-sum.
103pub fn multiset_subtract_into<G: Copy + Ord, M: MultiplicityLike>(
104 out: &mut Vec<Pair<G, M>>,
105 a: &[Pair<G, M>],
106 b: &[Pair<G, M>],
107) {
108 debug_assert_canonical(a);
109 debug_assert_canonical(b);
110 out.clear();
111 let (mut i, mut j) = (0, 0);
112 while i < a.len() {
113 if j < b.len() && b[j].0 < a[i].0 {
114 j += 1;
115 continue;
116 }
117 if j < b.len() && b[j].0 == a[i].0 {
118 let rem = a[i].0; // class id
119 let mult = a[i].1.saturating_sub(b[j].1);
120 if mult > M::ZERO {
121 out.push((rem, mult));
122 }
123 i += 1;
124 j += 1;
125 } else {
126 out.push(a[i]);
127 i += 1;
128 }
129 }
130}
131
132/// Allocating wrapper over [`multiset_subtract_into`].
133pub fn multiset_subtract<G: Copy + Ord, M: MultiplicityLike>(
134 a: &[Pair<G, M>],
135 b: &[Pair<G, M>],
136) -> Vec<Pair<G, M>> {
137 let mut out = Vec::with_capacity(a.len());
138 multiset_subtract_into(&mut out, a, b);
139 out
140}
141
142/// Multiset union (sum) `a ⊎ b` into `out` (cleared first): multiplicities of shared
143/// classes add. `out` must not alias `a` or `b`.
144pub fn multiset_union_into<G: Copy + Ord, M: MultiplicityLike>(
145 out: &mut Vec<Pair<G, M>>,
146 a: &[Pair<G, M>],
147 b: &[Pair<G, M>],
148) {
149 debug_assert_canonical(a);
150 debug_assert_canonical(b);
151 out.clear();
152 let (mut i, mut j) = (0, 0);
153 while i < a.len() && j < b.len() {
154 match a[i].0.cmp(&b[j].0) {
155 std::cmp::Ordering::Less => {
156 out.push(a[i]);
157 i += 1;
158 }
159 std::cmp::Ordering::Greater => {
160 out.push(b[j]);
161 j += 1;
162 }
163 std::cmp::Ordering::Equal => {
164 out.push((a[i].0, a[i].1.checked_add(b[j].1).expect(SUM_OVERFLOW)));
165 i += 1;
166 j += 1;
167 }
168 }
169 }
170 out.extend_from_slice(&a[i..]);
171 out.extend_from_slice(&b[j..]);
172}
173
174/// Allocating wrapper over [`multiset_union_into`].
175pub fn multiset_union<G: Copy + Ord, M: MultiplicityLike>(
176 a: &[Pair<G, M>],
177 b: &[Pair<G, M>],
178) -> Vec<Pair<G, M>> {
179 let mut out = Vec::with_capacity(a.len() + b.len());
180 multiset_union_into(&mut out, a, b);
181 out
182}
183
184/// Multiset lcm (least common multiple) `(a ⊎ b) − (a ∩ b)` into `out` (cleared first):
185/// per-class **maximum** multiplicity, the superposition multiset `AB` (spec §6 fix (B)),
186/// the smallest multiset containing both `a` and `b`. `out` must not alias `a` or `b`.
187pub fn multiset_lcm_into<G: Copy + Ord, M: MultiplicityLike>(
188 out: &mut Vec<Pair<G, M>>,
189 a: &[Pair<G, M>],
190 b: &[Pair<G, M>],
191) {
192 debug_assert_canonical(a);
193 debug_assert_canonical(b);
194 out.clear();
195 let (mut i, mut j) = (0, 0);
196 while i < a.len() && j < b.len() {
197 match a[i].0.cmp(&b[j].0) {
198 std::cmp::Ordering::Less => {
199 out.push(a[i]);
200 i += 1;
201 }
202 std::cmp::Ordering::Greater => {
203 out.push(b[j]);
204 j += 1;
205 }
206 std::cmp::Ordering::Equal => {
207 out.push((a[i].0, a[i].1.max(b[j].1)));
208 i += 1;
209 j += 1;
210 }
211 }
212 }
213 out.extend_from_slice(&a[i..]);
214 out.extend_from_slice(&b[j..]);
215}
216
217/// Allocating wrapper over [`multiset_lcm_into`].
218pub fn multiset_lcm<G: Copy + Ord, M: MultiplicityLike>(
219 a: &[Pair<G, M>],
220 b: &[Pair<G, M>],
221) -> Vec<Pair<G, M>> {
222 let mut out = Vec::with_capacity(a.len() + b.len());
223 multiset_lcm_into(&mut out, a, b);
224 out
225}
226
227/// Multiset intersection `a ∩ b` into `out` (cleared first): per-class **minimum**
228/// multiplicity, the common part canceled by a cancelative op (Kapur §5.1's `A ∩ B`).
229/// `out` must not alias `a` or `b`.
230pub fn multiset_intersect_into<G: Copy + Ord, M: MultiplicityLike>(
231 out: &mut Vec<Pair<G, M>>,
232 a: &[Pair<G, M>],
233 b: &[Pair<G, M>],
234) {
235 debug_assert_canonical(a);
236 debug_assert_canonical(b);
237 out.clear();
238 let (mut i, mut j) = (0, 0);
239 while i < a.len() && j < b.len() {
240 match a[i].0.cmp(&b[j].0) {
241 std::cmp::Ordering::Less => i += 1,
242 std::cmp::Ordering::Greater => j += 1,
243 std::cmp::Ordering::Equal => {
244 out.push((a[i].0, a[i].1.min(b[j].1)));
245 i += 1;
246 j += 1;
247 }
248 }
249 }
250}
251
252/// Allocating wrapper over [`multiset_intersect_into`].
253pub fn multiset_intersect<G: Copy + Ord, M: MultiplicityLike>(
254 a: &[Pair<G, M>],
255 b: &[Pair<G, M>],
256) -> Vec<Pair<G, M>> {
257 let mut out = Vec::new();
258 multiset_intersect_into(&mut out, a, b);
259 out
260}
261
262/// Total size of a monomial: the sum of its multiplicities.
263pub fn multiset_size<G: Copy, M: MultiplicityLike>(m: &[Pair<G, M>]) -> u64 {
264 m.iter()
265 .try_fold(0u64, |acc, (_, mult)| acc.checked_add(mult.to_u64()))
266 .expect(SUM_OVERFLOW)
267}
268
269/// Degree-lexicographic order on monomials — a *total admissible* monomial order
270/// (Kapur LMCS 2023 §3): compare total size first, then lexicographically over the
271/// `(class id, multiplicity)` entries **from the largest class id downward**. At the
272/// first non-tied position (descending) either one side holds a strictly larger id, or
273/// both hold the same id with different counts and the larger count wins — both branches
274/// say "the side with more of the largest differing class is greater", which is exactly
275/// Kapur's degree-lex (`∃c ∈ A−B, ∀d ∈ B−A, c ≫ d`).
276///
277/// Admissible = subterm property (a proper super-multiset is strictly larger, since size
278/// grows) + compatibility (`a ≫ b ⟹ a⊎x ≫ b⊎x`; adding `x` shifts both counts equally,
279/// so the largest differing id and the sign of its count difference are unchanged). The
280/// `≫`-smaller monomial is a class's normal-form representative; orienting every rule
281/// "larger → smaller" is what makes AC rewriting shrink and terminate (design doc §6b, §9).
282///
283/// NOTE: the tie-break direction matters. Comparing the *ascending* sequences
284/// (`a.iter().cmp(b.iter())`) is NOT admissible: at the smallest differing id it says
285/// "more copies wins" when both sides carry the id but "absence wins" when one lacks it,
286/// and those two branches disagree — `{b:2} ≫ {a,c}` yet `{a,b:2} ≺ {a:2,c}`, breaking
287/// compatibility and with it the termination of [`normalize_ms_into`].
288pub fn monomial_cmp<G: Copy + Ord, M: MultiplicityLike>(
289 a: &[Pair<G, M>],
290 b: &[Pair<G, M>],
291) -> std::cmp::Ordering {
292 multiset_size(a)
293 .cmp(&multiset_size(b))
294 .then_with(|| a.iter().rev().cmp(b.iter().rev()))
295}
296
297/// A ground AC rewrite rule `+lhs → +rhs`, both monomials, oriented `lhs ≫ rhs` by
298/// [`monomial_cmp`]. `rhs` is the **minimal monomial** of `lhs`'s e-class (its
299/// normal-form representative) — *not* a bare fresh class id, which would reintroduce
300/// an atom every critical pair and diverge (design doc §6b).
301pub struct NfRule<G, M> {
302 pub lhs: Vec<Pair<G, M>>,
303 pub rhs: Vec<Pair<G, M>>,
304}
305
306/// A borrowed view of a ground AC rewrite rule, the form the completion hot loop lends to
307/// every normalization: the round's rule table owns each `lhs`/`rhs` once and hands out
308/// `Copy` views, with no per-call deep copies. The allocating
309/// [`normalize_ms`]/[`normalize_set`]/[`normalize_nilpotent`] wrappers keep accepting owned
310/// [`NfRule`]s for tests and diagnostics and build the views internally.
311#[derive(Clone, Copy)]
312pub struct NfRuleRef<'a, G, M> {
313 pub lhs: &'a [Pair<G, M>],
314 pub rhs: &'a [Pair<G, M>],
315}
316
317impl<'a, G, M> From<&'a NfRule<G, M>> for NfRuleRef<'a, G, M> {
318 fn from(r: &'a NfRule<G, M>) -> Self {
319 Self {
320 lhs: &r.lhs,
321 rhs: &r.rhs,
322 }
323 }
324}
325
326/// A rule set as the normalizers consume it: the rules themselves, plus an optional
327/// [`NfIndex`] over them.
328///
329/// Two shapes rather than one because the two completion call sites amortize differently.
330/// The critical-pair loop normalizes thousands of reducts against one rule table already
331/// hoisted outside the loop, so an index built alongside it is paid for once — use
332/// [`indexed`](Self::indexed). Inter-reduction refills a *different* rule slice per target
333/// (each target is normalized by all rules but its own), so there is nothing to amortize
334/// over and indexing would cost more than the scan it replaces — use
335/// [`linear`](Self::linear).
336#[derive(Clone, Copy)]
337pub struct NfRules<'r, 'i, G, M> {
338 rules: &'i [NfRuleRef<'r, G, M>],
339 index: Option<&'i NfIndex<G>>,
340}
341
342impl<'r, 'i, G: Copy + Ord, M: MultiplicityLike> NfRules<'r, 'i, G, M> {
343 /// Scan every rule on every step. Correct for any rule set; the right choice when the
344 /// set is not reused across enough normalizations to pay for an index.
345 pub fn linear(rules: &'i [NfRuleRef<'r, G, M>]) -> Self {
346 Self { rules, index: None }
347 }
348
349 /// Consult `index` to narrow the rules tested. `index` must have been built from
350 /// exactly this `rules` slice ([`NfIndex::rebuild`] stores positions into it).
351 pub fn indexed(rules: &'i [NfRuleRef<'r, G, M>], index: &'i NfIndex<G>) -> Self {
352 debug_assert_eq!(
353 index.n_rules,
354 rules.len(),
355 "NfIndex was built from a different rule slice"
356 );
357 Self {
358 rules,
359 index: Some(index),
360 }
361 }
362
363 /// The lowest-indexed rule whose LHS is contained in `out`, or `None` if the monomial
364 /// is irreducible. `cands` is caller-owned scratch, reused across steps.
365 ///
366 /// **Both paths return the same rule.** A rule applies only if its whole LHS is
367 /// contained in `out`, so in particular the LHS's smallest class is present — which is
368 /// exactly the key it is indexed under. The index therefore admits every applicable
369 /// rule (it can only over-admit), and the candidates are visited in ascending position,
370 /// so the first hit is the one the linear scan's `find` would have stopped at.
371 #[inline]
372 fn find_applicable(
373 &self,
374 out: &[Pair<G, M>],
375 cands: &mut CandVec,
376 ) -> Option<NfRuleRef<'r, G, M>> {
377 match self.index {
378 None => self
379 .rules
380 .iter()
381 .copied()
382 .find(|r| rule_applies_linear(r, out)),
383 Some(ix) => {
384 ix.candidates(out, cands);
385 cands.iter().find_map(|&i| {
386 let r = self.rules[i as usize];
387 multiset_subset(r.lhs, out).then_some(r)
388 })
389 }
390 }
391 }
392}
393
394/// Applicability test for the unindexed path, with the orientation check the indexed path
395/// performs once at [`NfIndex::rebuild`] time instead.
396#[inline]
397fn rule_applies_linear<G: Copy + Ord, M: MultiplicityLike>(
398 r: &NfRuleRef<'_, G, M>,
399 out: &[Pair<G, M>],
400) -> bool {
401 // Orientation is only meaningful for a rule the normalizers can apply: `monomial_cmp`
402 // reports Equal for an empty pair, so the emptiness guard has to come first.
403 if r.lhs.is_empty() {
404 return false;
405 }
406 debug_assert!(monomial_cmp(r.lhs, r.rhs) == std::cmp::Ordering::Greater);
407 multiset_subset(r.lhs, out)
408}
409
410/// Candidate rule positions for one index probe.
411///
412/// A monomial contributes one bucket per distinct class it contains. The inline
413/// capacity is a tuning choice for the retained completion workloads; beyond it
414/// the list spills and stays correct. Capacity changes require the Criterion
415/// completion benchmark.
416type CandVec = smallvec::SmallVec<[u32; 32]>;
417
418/// Inverted index over a rule table's left-hand sides, keyed by each LHS's **smallest
419/// class**.
420///
421/// The normalize loops otherwise scan every rule per step. Keying each rule by
422/// a required LHS member avoids testing rules whose key is absent from the host
423/// monomial; the retained Criterion completion workloads measure the resulting
424/// candidate distribution.
425///
426/// Soundness needs only that the key be *some* fixed member of the LHS: containment
427/// implies every LHS class is present in the host, so whichever member is chosen, a probe
428/// over the host's classes reaches the rule's bucket. The minimum is picked as a
429/// deterministic balance heuristic rather than for correctness. Its distributional
430/// advantage, if any, is a Criterion question.
431///
432/// CSR layout — `keys` ascending and distinct, `order[starts[i]..starts[i + 1]]` the rule
433/// positions for `keys[i]` in ascending order — so a probe is a binary search plus a slice
434/// copy, and the whole index is three allocations regardless of table size.
435///
436/// # Position width
437///
438/// `starts` and `order` are `u32` and stay `u32`: they index the *rule table*, which is
439/// a population unrelated to [`EGraphConfig::Index`](crate::config::EGraphConfig::Index)
440/// and not governed by it. Unlike an id, a rule position is an index into a slice that
441/// has been materialized — 2^32 rules is at least 137 GB of monomial storage before the
442/// index is built at all — so the width is a space decision (two words per bucket
443/// instead of four, over a table read on every normalize step) and not a capacity cap
444/// anyone can reach. [`rebuild`](Self::rebuild) still checks it once rather than
445/// trusting that, because the failure mode of the unchecked cast it replaces is
446/// aliasing rule 2^32 onto rule 0 and silently rewriting with the wrong rule.
447pub struct NfIndex<G> {
448 /// Distinct LHS-minimum classes, ascending.
449 keys: Vec<G>,
450 /// `keys.len() + 1` offsets into `order`.
451 starts: Vec<u32>,
452 /// Rule positions grouped by key, ascending within each group.
453 order: Vec<u32>,
454 /// Length of the rule slice this was built from, to catch a mismatched pairing.
455 n_rules: usize,
456}
457
458/// The index is generic over the class id only: it stores LHS-minimum classes and rule
459/// positions, never a multiplicity, so one index type serves every configured
460/// [`EGraphConfig::M`](crate::config::EGraphConfig::M). The multiplicity width appears
461/// only on the methods that read rules.
462impl<G: Copy + Ord> NfIndex<G> {
463 /// Build an index over `rules`.
464 pub fn build<M: MultiplicityLike>(rules: &[NfRuleRef<'_, G, M>]) -> Self {
465 let mut ix = Self {
466 keys: Vec::new(),
467 starts: Vec::new(),
468 order: Vec::new(),
469 n_rules: 0,
470 };
471 ix.rebuild(rules);
472 ix
473 }
474
475 /// Re-index `rules` in place, reusing the existing allocations. Rules with an empty LHS
476 /// are omitted: the normalizers never apply them, so leaving them out of the index is
477 /// the same filter the linear path's `!lhs.is_empty()` performs per visit.
478 pub fn rebuild<M: MultiplicityLike>(&mut self, rules: &[NfRuleRef<'_, G, M>]) {
479 self.keys.clear();
480 self.starts.clear();
481 self.order.clear();
482 self.n_rules = rules.len();
483
484 // One check covers every narrowing below. Positions are `< rules.len()` and
485 // `order.len() <= rules.len()` (each applicable rule is pushed exactly once), so
486 // bounding the table length bounds both the values stored in `order` and the
487 // offsets stored in `starts`. Checking here rather than per-cast also means the
488 // index is never half-built from truncated positions.
489 u32::try_from(rules.len()).expect(
490 "NfIndex holds rule positions as u32; a table of 2^32 or more rules needs a \
491 wider position word",
492 );
493
494 // (LHS-minimum, position) for every applicable rule, ordered by key then position —
495 // the latter is what makes each group ascending, hence the scan order-preserving.
496 let mut pairs: Vec<(G, u32)> = rules
497 .iter()
498 .enumerate()
499 .filter(|(_, r)| {
500 // Empty-LHS rules are dropped before the orientation check: `monomial_cmp`
501 // reports Equal for an empty pair, and the normalizers never apply them.
502 if r.lhs.is_empty() {
503 return false;
504 }
505 debug_assert!(monomial_cmp(r.lhs, r.rhs) == std::cmp::Ordering::Greater);
506 true
507 })
508 .map(|(i, r)| {
509 // A canonical monomial is sorted by class, so element 0 is the minimum.
510 debug_assert_canonical(r.lhs);
511 // Exact: `i < rules.len()`, and `rules.len()` fits `u32` (checked above).
512 (r.lhs[0].0, i as u32)
513 })
514 .collect();
515 pairs.sort_unstable_by(|a, b| a.0.cmp(&b.0).then(a.1.cmp(&b.1)));
516
517 self.starts.push(0);
518 for (k, i) in pairs {
519 if self.keys.last() != Some(&k) {
520 self.keys.push(k);
521 // Exact: one push per applicable rule, so `order.len() <= rules.len()`,
522 // which fits `u32` (checked above). Same for the offset written below.
523 self.starts.push(self.order.len() as u32);
524 }
525 self.order.push(i);
526 *self.starts.last_mut().unwrap() = self.order.len() as u32;
527 }
528 }
529
530 /// Positions of every rule that could apply to `out`, ascending. Over-admits (a
531 /// candidate still needs the full containment test) but never under-admits.
532 #[inline]
533 fn candidates<M: MultiplicityLike>(&self, out: &[Pair<G, M>], buf: &mut CandVec) {
534 buf.clear();
535 for p in out {
536 if let Ok(k) = self.keys.binary_search(&p.0) {
537 let (s, e) = (self.starts[k] as usize, self.starts[k + 1] as usize);
538 buf.extend_from_slice(&self.order[s..e]);
539 }
540 }
541 // Each rule sits in exactly one bucket, so the gathered positions are distinct and
542 // sorting is all that is needed to recover the linear scan's visit order.
543 buf.sort_unstable();
544 }
545}
546
547/// Hard backstop for the normalize loops. The paper termination argument requires every
548/// rule to be oriented `lhs ≫ rhs`; this finite guard additionally prevents a bad caller
549/// from looping forever. Exhaustion is a panic in every build, never a partially normalized
550/// return value.
551const GUARD_MAX_REWRITES: usize = 1_000_000;
552
553/// Normalize a monomial to a fixpoint by AC rewriting (Kapur Def. 3): while some rule
554/// `+A → +B` has `A ⊆ ms`, replace `A` by `B` (`ms := (ms − A) ⊎ B`). Every rule is
555/// oriented `A ≫ B` ([`monomial_cmp`]), so each step strictly lowers `ms` in the
556/// degree-lex order (compatibility) and the loop terminates; the irreducible result is
557/// left in `out`.
558///
559/// Destination-passing: `out` holds the result (seeded from `ms`), `scratch` is a
560/// caller-owned ping-pong buffer; neither may alias `ms`. No per-rewrite allocation
561/// (design §9a). `rules` must already be filtered to the relevant AC op, and each must
562/// satisfy `monomial_cmp(lhs, rhs) == Greater` (the caller builds them that way). This is
563/// the "normalize the reduct before materializing" step whose omission diverges (§6b).
564pub fn normalize_ms_into<G: Copy + Ord, M: MultiplicityLike>(
565 out: &mut Vec<Pair<G, M>>,
566 scratch: &mut Vec<Pair<G, M>>,
567 ms: &[Pair<G, M>],
568 rules: NfRules<'_, '_, G, M>,
569) {
570 normalize_ms_into_with_limit(out, scratch, ms, rules, GUARD_MAX_REWRITES);
571}
572
573fn normalize_ms_into_with_limit<G: Copy + Ord, M: MultiplicityLike>(
574 out: &mut Vec<Pair<G, M>>,
575 scratch: &mut Vec<Pair<G, M>>,
576 ms: &[Pair<G, M>],
577 rules: NfRules<'_, '_, G, M>,
578 max_rewrites: usize,
579) {
580 out.clear();
581 out.extend_from_slice(ms);
582 let mut cands = CandVec::new();
583 let mut rewrites = 0usize;
584 while let Some(rule) = rules.find_applicable(out, &mut cands) {
585 assert!(
586 rewrites < max_rewrites,
587 "normalize_ms_into exceeded its rewrite guard before reaching a normal form"
588 );
589 #[cfg(debug_assertions)]
590 let before = out.clone();
591 // out := (out − lhs) ⊎ rhs, ping-ponging through `scratch`.
592 multiset_subtract_into(scratch, out, rule.lhs);
593 multiset_union_into(out, scratch, rule.rhs);
594 #[cfg(debug_assertions)]
595 debug_assert!(
596 monomial_cmp(out, &before) == std::cmp::Ordering::Less,
597 "rewrite step failed to lower the host monomial (order not admissible?)"
598 );
599 rewrites += 1;
600 }
601}
602
603/// Allocating wrapper over [`normalize_ms_into`].
604pub fn normalize_ms<G: Copy + Ord, M: MultiplicityLike>(
605 ms: &[Pair<G, M>],
606 rules: &[NfRule<G, M>],
607) -> Vec<Pair<G, M>> {
608 let refs: Vec<NfRuleRef<'_, G, M>> = rules.iter().map(NfRuleRef::from).collect();
609 let mut out = Vec::new();
610 let mut scratch = Vec::new();
611 normalize_ms_into(&mut out, &mut scratch, ms, NfRules::linear(&refs));
612 out
613}
614
615/// Clamp every multiplicity to 1 in place: the idempotent (set) normal form of a monomial
616/// (`x∘x = x`). A canonical multiset is already sorted+duplicate-free in `G`, so this only
617/// rewrites the counts, never the class set. Applied after each monomial operation for a Set
618/// (ACI) op, so its monomials stay {0,1}-valued (design "three independent axes": idempotent
619/// bounds counts to {0,1}).
620pub fn clamp_idempotent<G: Copy, M: MultiplicityLike>(ms: &mut [Pair<G, M>]) {
621 for p in ms.iter_mut() {
622 p.1 = M::ONE;
623 }
624}
625
626/// Idempotent (set) normalization: like [`normalize_ms`] but every intermediate and the final
627/// result is clamped to multiplicity 1, so the rewrite operates over sets. The union in a
628/// rewrite step (`(ms − A) ⊎ B`) can raise a count above 1 (e.g. a summand already present in
629/// both the residual and `B`); the clamp collapses it back, which is exactly the ACI
630/// idempotence join. Termination still holds: each step strictly lowers the *set* in degree-lex
631/// (the clamp only ever lowers counts), so the guard bound from the multiset case still applies.
632pub fn normalize_set_into<G: Copy + Ord, M: MultiplicityLike>(
633 out: &mut Vec<Pair<G, M>>,
634 scratch: &mut Vec<Pair<G, M>>,
635 ms: &[Pair<G, M>],
636 rules: NfRules<'_, '_, G, M>,
637) {
638 normalize_set_into_with_limit(out, scratch, ms, rules, GUARD_MAX_REWRITES);
639}
640
641fn normalize_set_into_with_limit<G: Copy + Ord, M: MultiplicityLike>(
642 out: &mut Vec<Pair<G, M>>,
643 scratch: &mut Vec<Pair<G, M>>,
644 ms: &[Pair<G, M>],
645 rules: NfRules<'_, '_, G, M>,
646 max_rewrites: usize,
647) {
648 out.clear();
649 out.extend_from_slice(ms);
650 clamp_idempotent(out);
651 let mut cands = CandVec::new();
652 let mut rewrites = 0usize;
653 while let Some(rule) = rules.find_applicable(out, &mut cands) {
654 assert!(
655 rewrites < max_rewrites,
656 "normalize_set_into exceeded its rewrite guard before reaching a normal form"
657 );
658 #[cfg(debug_assertions)]
659 let before = out.clone();
660 // out := (out − lhs) ⊎ rhs, ping-ponging through `scratch`.
661 multiset_subtract_into(scratch, out, rule.lhs);
662 multiset_union_into(out, scratch, rule.rhs);
663 clamp_idempotent(out);
664 // Strictness survives the clamp: the multiset step is strict (admissible
665 // order + lhs ≫ rhs) and the clamp only lowers counts (can(t) ≼ t).
666 #[cfg(debug_assertions)]
667 debug_assert!(
668 monomial_cmp(out, &before) == std::cmp::Ordering::Less,
669 "idempotent rewrite step failed to lower the host monomial"
670 );
671 rewrites += 1;
672 }
673}
674
675/// Allocating wrapper over [`normalize_set_into`].
676pub fn normalize_set<G: Copy + Ord, M: MultiplicityLike>(
677 ms: &[Pair<G, M>],
678 rules: &[NfRule<G, M>],
679) -> Vec<Pair<G, M>> {
680 let refs: Vec<NfRuleRef<'_, G, M>> = rules.iter().map(NfRuleRef::from).collect();
681 let mut out = Vec::new();
682 let mut scratch = Vec::new();
683 normalize_set_into(&mut out, &mut scratch, ms, NfRules::linear(&refs));
684 out
685}
686
687/// Reduce every multiplicity modulo `order` in place and drop the summands that vanish: the
688/// nilpotent normal form of a monomial (`x∘x = e` at order 2; count mod `order` in general).
689/// `order ≥ 2`. A canonical multiset is sorted+coalesced in `G`, so this only rewrites counts
690/// and removes zeroed entries; the surviving order is unchanged. Applied after each monomial
691/// operation for a nilpotent op, so its monomials stay {0,…,order−1}-valued and an emptied
692/// monomial becomes `{}` (which the caller maps to the unit). `retain` preserves order, so the
693/// result stays canonical.
694pub fn clamp_nilpotent<G: Copy, M: MultiplicityLike>(ms: &mut Vec<Pair<G, M>>, order: u8) {
695 for p in ms.iter_mut() {
696 p.1 = p.1.rem_order(order);
697 }
698 ms.retain(|p| p.1 != M::ZERO);
699}
700
701/// Nilpotent normalization: like [`normalize_ms`] but every intermediate and the final result is
702/// reduced modulo `order` ([`clamp_nilpotent`]), so the rewrite operates over the nilpotent group
703/// `(ℤ/order)`-multiset. The union in a rewrite step can raise a count to or past `order` (a
704/// summand present in both the residual and `B`); the mod-`order` clamp cancels it, which is
705/// exactly the symmetric-difference join at order 2. Termination: each step's underlying multiset
706/// rewrite strictly lowers the monomial in degree-lex, and the clamp only ever lowers counts, so
707/// the guard bound from the multiset case still applies.
708pub fn normalize_nilpotent_into<G: Copy + Ord, M: MultiplicityLike>(
709 out: &mut Vec<Pair<G, M>>,
710 scratch: &mut Vec<Pair<G, M>>,
711 ms: &[Pair<G, M>],
712 rules: NfRules<'_, '_, G, M>,
713 order: u8,
714) {
715 normalize_nilpotent_into_with_limit(out, scratch, ms, rules, order, GUARD_MAX_REWRITES);
716}
717
718fn normalize_nilpotent_into_with_limit<G: Copy + Ord, M: MultiplicityLike>(
719 out: &mut Vec<Pair<G, M>>,
720 scratch: &mut Vec<Pair<G, M>>,
721 ms: &[Pair<G, M>],
722 rules: NfRules<'_, '_, G, M>,
723 order: u8,
724 max_rewrites: usize,
725) {
726 out.clear();
727 out.extend_from_slice(ms);
728 clamp_nilpotent(out, order);
729 let mut cands = CandVec::new();
730 let mut rewrites = 0usize;
731 while let Some(rule) = rules.find_applicable(out, &mut cands) {
732 assert!(
733 rewrites < max_rewrites,
734 "normalize_nilpotent_into exceeded its rewrite guard before reaching a normal form"
735 );
736 #[cfg(debug_assertions)]
737 let before = out.clone();
738 // out := (out − lhs) ⊎ rhs, ping-ponging through `scratch`.
739 multiset_subtract_into(scratch, out, rule.lhs);
740 multiset_union_into(out, scratch, rule.rhs);
741 clamp_nilpotent(out, order);
742 // Strictness survives the clamp: the multiset step is strict (admissible
743 // order + lhs ≫ rhs) and the mod-n clamp only lowers counts (can(t) ≼ t).
744 #[cfg(debug_assertions)]
745 debug_assert!(
746 monomial_cmp(out, &before) == std::cmp::Ordering::Less,
747 "nilpotent rewrite step failed to lower the host monomial"
748 );
749 rewrites += 1;
750 }
751}
752
753/// Allocating wrapper over [`normalize_nilpotent_into`].
754pub fn normalize_nilpotent<G: Copy + Ord, M: MultiplicityLike>(
755 ms: &[Pair<G, M>],
756 rules: &[NfRule<G, M>],
757 order: u8,
758) -> Vec<Pair<G, M>> {
759 let refs: Vec<NfRuleRef<'_, G, M>> = rules.iter().map(NfRuleRef::from).collect();
760 let mut out = Vec::new();
761 let mut scratch = Vec::new();
762 normalize_nilpotent_into(&mut out, &mut scratch, ms, NfRules::linear(&refs), order);
763 out
764}
765
766#[cfg(test)]
767mod tests {
768 use super::*;
769 use crate::id::ENodeId;
770 use crate::multiplicity::Multiplicity;
771
772 fn id(n: u32) -> ENodeId {
773 ENodeId::new(n)
774 }
775
776 /// Build a canonical multiset from (id, mult) pairs given in any order.
777 fn ms(pairs: &[(u32, u32)]) -> Vec<Pair<ENodeId, Multiplicity>> {
778 let mut v: Vec<Pair<ENodeId, Multiplicity>> = pairs
779 .iter()
780 .map(|&(g, m)| (id(g), Multiplicity(m)))
781 .collect();
782 v.sort_by_key(|p| p.0);
783 v
784 }
785
786 #[test]
787 fn disjoint_basic() {
788 assert!(multiset_disjoint(
789 &ms(&[(1, 1), (2, 1)]),
790 &ms(&[(3, 1), (4, 1)])
791 ));
792 assert!(!multiset_disjoint(
793 &ms(&[(1, 1), (2, 1)]),
794 &ms(&[(2, 1), (5, 1)])
795 ));
796 // empty is disjoint from anything
797 assert!(multiset_disjoint::<ENodeId, Multiplicity>(
798 &[],
799 &ms(&[(1, 1)])
800 ));
801 assert!(multiset_disjoint::<ENodeId, Multiplicity>(&[], &[]));
802 }
803
804 #[test]
805 fn disjoint_ignores_multiplicity() {
806 // sharing a class is non-disjoint regardless of multiplicity
807 assert!(!multiset_disjoint(&ms(&[(2, 5)]), &ms(&[(2, 1)])));
808 }
809
810 #[test]
811 fn subset_basic() {
812 // {a,b} ⊆ {a,b,d}
813 assert!(multiset_subset(
814 &ms(&[(1, 1), (2, 1)]),
815 &ms(&[(1, 1), (2, 1), (4, 1)])
816 ));
817 // {a,b,d} ⊄ {a,b}
818 assert!(!multiset_subset(
819 &ms(&[(1, 1), (2, 1), (4, 1)]),
820 &ms(&[(1, 1), (2, 1)])
821 ));
822 // overlap but neither contains (the §4b case)
823 assert!(!multiset_subset(
824 &ms(&[(1, 1), (2, 1)]),
825 &ms(&[(2, 1), (4, 1)])
826 ));
827 // empty ⊆ anything
828 assert!(multiset_subset::<ENodeId, Multiplicity>(
829 &[],
830 &ms(&[(1, 1)])
831 ));
832 }
833
834 #[test]
835 fn subset_respects_multiplicity() {
836 // {a:2} ⊆ {a:3} but not {a:3} ⊆ {a:2}
837 assert!(multiset_subset(&ms(&[(1, 2)]), &ms(&[(1, 3)])));
838 assert!(!multiset_subset(&ms(&[(1, 3)]), &ms(&[(1, 2)])));
839 // equal multiplicity is a subset
840 assert!(multiset_subset(&ms(&[(1, 2)]), &ms(&[(1, 2)])));
841 }
842
843 #[test]
844 fn subtract_basic() {
845 // {a,b,d} − {a,b} = {d}
846 assert_eq!(
847 multiset_subtract(&ms(&[(1, 1), (2, 1), (4, 1)]), &ms(&[(1, 1), (2, 1)])),
848 ms(&[(4, 1)])
849 );
850 // subtracting a class not present is a no-op on it
851 assert_eq!(
852 multiset_subtract(&ms(&[(1, 1)]), &ms(&[(9, 1)])),
853 ms(&[(1, 1)])
854 );
855 }
856
857 #[test]
858 fn subtract_multiplicity_clamps_and_drops_zeros() {
859 // {a:3, b:1} − {a:1} = {a:2, b:1}
860 assert_eq!(
861 multiset_subtract(&ms(&[(1, 3), (2, 1)]), &ms(&[(1, 1)])),
862 ms(&[(1, 2), (2, 1)])
863 );
864 // exact cancel drops the class entirely
865 assert_eq!(
866 multiset_subtract(&ms(&[(1, 2), (2, 1)]), &ms(&[(1, 2)])),
867 ms(&[(2, 1)])
868 );
869 // over-subtract clamps at zero, does not go negative
870 let empty: Vec<Pair<ENodeId, Multiplicity>> = Vec::new();
871 assert_eq!(multiset_subtract(&ms(&[(1, 1)]), &ms(&[(1, 5)])), empty);
872 }
873
874 #[test]
875 fn union_sums_multiplicities() {
876 // {a,b} ⊎ {b,d} = {a, b:2, d}
877 assert_eq!(
878 multiset_union(&ms(&[(1, 1), (2, 1)]), &ms(&[(2, 1), (4, 1)])),
879 ms(&[(1, 1), (2, 2), (4, 1)])
880 );
881 // union with singleton {c} adds c (the ⊎ {a} substitution step)
882 assert_eq!(
883 multiset_union(&ms(&[(4, 1)]), &ms(&[(3, 1)])),
884 ms(&[(3, 1), (4, 1)])
885 );
886 // union with a singleton already present bumps its multiplicity
887 assert_eq!(
888 multiset_union(&ms(&[(3, 1), (4, 1)]), &ms(&[(3, 1)])),
889 ms(&[(3, 2), (4, 1)])
890 );
891 }
892
893 #[test]
894 fn lcm_takes_max_multiplicity() {
895 // lcm({a,b}, {b,d}) = {a,b,d} (the §4b superposition)
896 assert_eq!(
897 multiset_lcm(&ms(&[(1, 1), (2, 1)]), &ms(&[(2, 1), (4, 1)])),
898 ms(&[(1, 1), (2, 1), (4, 1)])
899 );
900 // per-element max, not sum: lcm({a:3}, {a:1}) = {a:3}
901 assert_eq!(multiset_lcm(&ms(&[(1, 3)]), &ms(&[(1, 1)])), ms(&[(1, 3)]));
902 // disjoint lcm is the union
903 assert_eq!(
904 multiset_lcm(&ms(&[(1, 2)]), &ms(&[(5, 1)])),
905 ms(&[(1, 2), (5, 1)])
906 );
907 }
908
909 #[test]
910 fn lcm_contains_both_operands() {
911 // a ⊆ lcm(a,b) and b ⊆ lcm(a,b), by construction (per-element max)
912 let a = ms(&[(1, 2), (2, 1)]);
913 let b = ms(&[(2, 3), (4, 1)]);
914 let ab = multiset_lcm(&a, &b);
915 assert!(multiset_subset(&a, &ab));
916 assert!(multiset_subset(&b, &ab));
917 }
918
919 #[test]
920 fn subtract_then_union_round_trips_lcm() {
921 // (AB − A) ⊎ A == AB when A ⊆ AB — the substitution arithmetic identity.
922 let a = ms(&[(1, 1), (2, 2)]);
923 let b = ms(&[(2, 1), (4, 1)]);
924 let ab = multiset_lcm(&a, &b);
925 let residual = multiset_subtract(&ab, &a);
926 assert_eq!(multiset_union(&residual, &a), ab);
927 }
928
929 #[test]
930 fn into_variants_match_allocating_and_reuse_buffer() {
931 let a = ms(&[(1, 1), (2, 2), (4, 1)]);
932 let b = ms(&[(2, 1), (4, 1), (5, 1)]);
933 // A pre-dirtied buffer must be cleared, and each _into matches its wrapper.
934 let mut buf = ms(&[(99, 7)]);
935 multiset_subtract_into(&mut buf, &a, &b);
936 assert_eq!(buf, multiset_subtract(&a, &b));
937 multiset_union_into(&mut buf, &a, &b);
938 assert_eq!(buf, multiset_union(&a, &b));
939 multiset_lcm_into(&mut buf, &a, &b);
940 assert_eq!(buf, multiset_lcm(&a, &b));
941 }
942
943 #[test]
944 fn normalize_ms_into_matches_and_reuses() {
945 // Rules: {1,2}→{3} and {3,4}→{5}, so {1,2,4} → {3,4} → {5}.
946 let rules = vec![
947 NfRule {
948 lhs: ms(&[(1, 1), (2, 1)]),
949 rhs: ms(&[(3, 1)]),
950 },
951 NfRule {
952 lhs: ms(&[(3, 1), (4, 1)]),
953 rhs: ms(&[(5, 1)]),
954 },
955 ];
956 let input = ms(&[(1, 1), (2, 1), (4, 1)]);
957 let refs: Vec<NfRuleRef<'_, ENodeId, Multiplicity>> =
958 rules.iter().map(NfRuleRef::from).collect();
959 let mut out = ms(&[(99, 3)]); // pre-dirtied
960 let mut scratch = ms(&[(88, 2)]); // pre-dirtied
961 normalize_ms_into(&mut out, &mut scratch, &input, NfRules::linear(&refs));
962 assert_eq!(out, ms(&[(5, 1)]));
963 assert_eq!(out, normalize_ms(&input, &rules));
964 }
965
966 #[test]
967 #[should_panic(
968 expected = "normalize_ms_into exceeded its rewrite guard before reaching a normal form"
969 )]
970 fn rewrite_guard_never_returns_a_partial_normal_form() {
971 let rules = [NfRule {
972 lhs: ms(&[(1, 1)]),
973 rhs: Vec::new(),
974 }];
975 let refs: Vec<NfRuleRef<'_, ENodeId, Multiplicity>> =
976 rules.iter().map(NfRuleRef::from).collect();
977 let mut out = Vec::new();
978 let mut scratch = Vec::new();
979
980 // One rewrite leaves one copy of class 1, so a budget of one is
981 // deliberately exhausted before the input reaches its empty normal form.
982 normalize_ms_into_with_limit(
983 &mut out,
984 &mut scratch,
985 &ms(&[(1, 2)]),
986 NfRules::linear(&refs),
987 1,
988 );
989 }
990
991 /// The indexed path must pick the same rule the linear scan would, not merely *a*
992 /// rule that applies — the two differ whenever more than one rule is applicable, and
993 /// which one fires determines the normal form reached.
994 ///
995 /// The rules here are ordered so position and LHS-minimum *disagree*: rule 0 keys on
996 /// class 3, rule 1 on class 1. A host containing both is reducible by either, the
997 /// linear scan takes rule 0, and an index that returned candidates in key order rather
998 /// than position order would take rule 1.
999 #[test]
1000 fn indexed_picks_the_same_rule_as_the_linear_scan() {
1001 let rules = [
1002 NfRule {
1003 lhs: ms(&[(3, 1), (4, 1)]),
1004 rhs: ms(&[(6, 1)]),
1005 },
1006 NfRule {
1007 lhs: ms(&[(1, 1), (2, 1)]),
1008 rhs: ms(&[(7, 1)]),
1009 },
1010 ];
1011 let refs: Vec<NfRuleRef<'_, ENodeId, Multiplicity>> =
1012 rules.iter().map(NfRuleRef::from).collect();
1013 let index = NfIndex::build(&refs);
1014 // Reducible by rule 0 and rule 1 both; the earlier rule must win either way.
1015 let input = ms(&[(1, 1), (2, 1), (3, 1), (4, 1)]);
1016
1017 let mut lin = Vec::new();
1018 let mut ixd = Vec::new();
1019 let mut scratch = Vec::new();
1020 normalize_ms_into(&mut lin, &mut scratch, &input, NfRules::linear(&refs));
1021 normalize_ms_into(
1022 &mut ixd,
1023 &mut scratch,
1024 &input,
1025 NfRules::indexed(&refs, &index),
1026 );
1027 assert_eq!(lin, ixd, "indexed and linear normal forms diverged");
1028 // Rule 0 fires first ({3,4}→{6}), leaving {1,2,6}, then rule 1 ({1,2}→{7}).
1029 assert_eq!(lin, ms(&[(6, 1), (7, 1)]));
1030 }
1031
1032 /// Exhaustive equivalence over a small space, for all three normalizers: every host
1033 /// monomial over 6 classes against a fixed rule table, indexed vs linear. This is the
1034 /// property the `Bclose` call site depends on, so it is checked over many shapes
1035 /// rather than the one hand-picked above — including hosts no rule touches (the 94-98%
1036 /// case the index exists to skip) and hosts reducible several steps deep.
1037 #[test]
1038 fn indexed_matches_linear_for_every_host_over_six_classes() {
1039 // LHS-minima deliberately repeated (two rules key on class 1) and out of position
1040 // order, so buckets hold multiple rules and key order ≠ position order.
1041 let rules = vec![
1042 NfRule {
1043 lhs: ms(&[(2, 1), (3, 1)]),
1044 rhs: ms(&[(1, 1)]),
1045 },
1046 NfRule {
1047 lhs: ms(&[(1, 1), (4, 1)]),
1048 rhs: ms(&[(2, 1)]),
1049 },
1050 NfRule {
1051 lhs: ms(&[(1, 2)]),
1052 rhs: ms(&[(3, 1)]),
1053 },
1054 NfRule {
1055 lhs: ms(&[(4, 1), (5, 1)]),
1056 rhs: ms(&[(1, 1)]),
1057 },
1058 NfRule {
1059 lhs: ms(&[(1, 1), (2, 1), (3, 1)]),
1060 rhs: ms(&[(5, 1)]),
1061 },
1062 ];
1063 // Orientation is the normalizers' precondition (lhs ≫ rhs); assert it up front so a
1064 // future edit to the table above fails here rather than in a debug_assert.
1065 for r in &rules {
1066 assert_eq!(
1067 monomial_cmp(&r.lhs, &r.rhs),
1068 std::cmp::Ordering::Greater,
1069 "test rule table is mis-oriented"
1070 );
1071 }
1072 let refs: Vec<NfRuleRef<'_, ENodeId, Multiplicity>> =
1073 rules.iter().map(NfRuleRef::from).collect();
1074 let index = NfIndex::build(&refs);
1075
1076 // Every multiplicity vector over classes 1..=6 with counts 0..=2: 3^6 = 729 hosts.
1077 let mut checked = 0;
1078 for code in 0..3usize.pow(6) {
1079 let mut host: Vec<Pair<ENodeId, Multiplicity>> = Vec::new();
1080 let mut c = code;
1081 for cls in 1..=6u32 {
1082 let mult = (c % 3) as u32;
1083 c /= 3;
1084 if mult > 0 {
1085 host.push((id(cls), Multiplicity(mult)));
1086 }
1087 }
1088 let (mut lin, mut ixd, mut scratch) = (Vec::new(), Vec::new(), Vec::new());
1089
1090 normalize_ms_into(&mut lin, &mut scratch, &host, NfRules::linear(&refs));
1091 normalize_ms_into(
1092 &mut ixd,
1093 &mut scratch,
1094 &host,
1095 NfRules::indexed(&refs, &index),
1096 );
1097 assert_eq!(lin, ixd, "normalize_ms_into diverged on host {host:?}");
1098
1099 normalize_set_into(&mut lin, &mut scratch, &host, NfRules::linear(&refs));
1100 normalize_set_into(
1101 &mut ixd,
1102 &mut scratch,
1103 &host,
1104 NfRules::indexed(&refs, &index),
1105 );
1106 assert_eq!(lin, ixd, "normalize_set_into diverged on host {host:?}");
1107
1108 for order in [2u8, 3] {
1109 normalize_nilpotent_into(
1110 &mut lin,
1111 &mut scratch,
1112 &host,
1113 NfRules::linear(&refs),
1114 order,
1115 );
1116 normalize_nilpotent_into(
1117 &mut ixd,
1118 &mut scratch,
1119 &host,
1120 NfRules::indexed(&refs, &index),
1121 order,
1122 );
1123 assert_eq!(
1124 lin, ixd,
1125 "normalize_nilpotent_into (order {order}) diverged on host {host:?}"
1126 );
1127 }
1128 checked += 1;
1129 }
1130 assert_eq!(checked, 729);
1131 }
1132
1133 /// `rebuild` must leave the index equivalent to a fresh `build`, since it exists to
1134 /// reuse one index's allocations across rounds.
1135 #[test]
1136 fn nf_index_rebuild_matches_fresh_build() {
1137 let first = [NfRule {
1138 lhs: ms(&[(5, 1), (6, 1)]),
1139 rhs: ms(&[(2, 1)]),
1140 }];
1141 let second = [
1142 NfRule {
1143 lhs: ms(&[(1, 1), (9, 1)]),
1144 rhs: ms(&[(4, 1)]),
1145 },
1146 NfRule {
1147 lhs: ms(&[(1, 3)]),
1148 rhs: ms(&[(2, 1)]),
1149 },
1150 ];
1151 let r1: Vec<NfRuleRef<'_, ENodeId, Multiplicity>> =
1152 first.iter().map(NfRuleRef::from).collect();
1153 let r2: Vec<NfRuleRef<'_, ENodeId, Multiplicity>> =
1154 second.iter().map(NfRuleRef::from).collect();
1155
1156 let mut reused = NfIndex::build(&r1);
1157 reused.rebuild(&r2);
1158 let fresh = NfIndex::build(&r2);
1159 assert_eq!(reused.keys, fresh.keys);
1160 assert_eq!(reused.starts, fresh.starts);
1161 assert_eq!(reused.order, fresh.order);
1162 assert_eq!(reused.n_rules, fresh.n_rules);
1163 }
1164
1165 /// An empty-LHS rule is skipped by the linear path's `!lhs.is_empty()` guard and
1166 /// omitted from the index; both must still agree, and the omission must not renumber
1167 /// the rules around it.
1168 #[test]
1169 fn empty_lhs_rule_is_skipped_by_both_paths() {
1170 let rules = [
1171 NfRule {
1172 lhs: Vec::new(),
1173 rhs: Vec::new(),
1174 },
1175 NfRule {
1176 lhs: ms(&[(1, 1), (2, 1)]),
1177 rhs: ms(&[(3, 1)]),
1178 },
1179 ];
1180 let refs: Vec<NfRuleRef<'_, ENodeId, Multiplicity>> =
1181 rules.iter().map(NfRuleRef::from).collect();
1182 let index = NfIndex::build(&refs);
1183 // Rule 1 is at position 1 in `order`, not renumbered to 0 by the omission.
1184 assert_eq!(index.order, vec![1]);
1185
1186 let input = ms(&[(1, 1), (2, 1)]);
1187 let (mut lin, mut ixd, mut scratch) = (Vec::new(), Vec::new(), Vec::new());
1188 normalize_ms_into(&mut lin, &mut scratch, &input, NfRules::linear(&refs));
1189 normalize_ms_into(
1190 &mut ixd,
1191 &mut scratch,
1192 &input,
1193 NfRules::indexed(&refs, &index),
1194 );
1195 assert_eq!(lin, ms(&[(3, 1)]));
1196 assert_eq!(lin, ixd);
1197 }
1198
1199 #[test]
1200 fn clamp_nilpotent_reduces_mod_order_and_drops_zeros() {
1201 // Order 2: counts mod 2, zeros dropped. {a:2, b:3, c:4} → {b:1}.
1202 let mut m = ms(&[(1, 2), (2, 3), (3, 4)]);
1203 clamp_nilpotent(&mut m, 2);
1204 assert_eq!(m, ms(&[(2, 1)]));
1205 // Order 3: {a:3, b:4, c:5} → {b:1, c:2}.
1206 let mut m3 = ms(&[(1, 3), (2, 4), (3, 5)]);
1207 clamp_nilpotent(&mut m3, 3);
1208 assert_eq!(m3, ms(&[(2, 1), (3, 2)]));
1209 // A fully-even monomial empties.
1210 let mut even = ms(&[(1, 2), (2, 4)]);
1211 clamp_nilpotent(&mut even, 2);
1212 assert!(even.is_empty());
1213 }
1214
1215 #[test]
1216 fn normalize_nilpotent_symmetric_difference_join() {
1217 // Rule {a,b}→{} (i.e. a⊕b = e). Normalizing {a,b,c} cancels the pair, leaving {c};
1218 // the mod-2 clamp is what makes the union in a rewrite step cancel. Also check a step
1219 // that raises a count to 2 then cancels: input {a,a,c} clamps to {c} up front.
1220 let rules = vec![NfRule {
1221 lhs: ms(&[(1, 1), (2, 1)]),
1222 rhs: vec![], // → the unit (empty monomial)
1223 }];
1224 assert_eq!(
1225 normalize_nilpotent(&ms(&[(1, 1), (2, 1), (3, 1)]), &rules, 2),
1226 ms(&[(3, 1)])
1227 );
1228 // {a,a} → {} regardless of rules (build gives {a:2}; clamp cancels).
1229 assert!(normalize_nilpotent(&ms(&[(1, 2)]), &[], 2).is_empty());
1230 // _into matches the wrapper and clears a dirty buffer.
1231 let input = ms(&[(1, 1), (2, 1), (3, 1)]);
1232 let refs: Vec<NfRuleRef<'_, ENodeId, Multiplicity>> =
1233 rules.iter().map(NfRuleRef::from).collect();
1234 let mut out = ms(&[(99, 3)]);
1235 let mut scratch = ms(&[(88, 2)]);
1236 normalize_nilpotent_into(&mut out, &mut scratch, &input, NfRules::linear(&refs), 2);
1237 assert_eq!(out, normalize_nilpotent(&input, &rules, 2));
1238 }
1239
1240 // ── Admissibility of monomial_cmp (Kapur LMCS 2023 §3) ──────────────────────
1241 // These guard the W1 conformance fix: the tie-break must compare from the largest
1242 // class id downward. The ascending tie-break it replaced violated compatibility.
1243
1244 fn lcg(rng: &mut u64, m: u32) -> u32 {
1245 *rng = rng
1246 .wrapping_mul(6364136223846793005)
1247 .wrapping_add(1442695040888963407);
1248 ((*rng >> 33) as u32) % m
1249 }
1250
1251 /// Random canonical monomial over ids 1..=6 with counts 0..=3.
1252 fn rand_ms(rng: &mut u64) -> Vec<Pair<ENodeId, Multiplicity>> {
1253 let mut v = Vec::new();
1254 for g in 1..=6u32 {
1255 let c = lcg(rng, 4);
1256 if c > 0 {
1257 v.push((id(g), Multiplicity(c)));
1258 }
1259 }
1260 v
1261 }
1262
1263 #[test]
1264 fn monomial_cmp_kapur_deglex_counterexample() {
1265 // The exact pair the old ascending tie-break got wrong (ids a=1 < b=2 < c=3).
1266 // Sizes tie at 2; the largest differing id is c, owned by {a,c}: {a,c} ≫ {b:2}.
1267 let bb = ms(&[(2, 2)]);
1268 let ac = ms(&[(1, 1), (3, 1)]);
1269 assert_eq!(monomial_cmp(&ac, &bb), std::cmp::Ordering::Greater);
1270 // Compatibility on the pair that used to flip after ⊎{a}.
1271 let ac_a = multiset_union(&ac, &ms(&[(1, 1)])); // {a:2, c}
1272 let bb_a = multiset_union(&bb, &ms(&[(1, 1)])); // {a, b:2}
1273 assert_eq!(monomial_cmp(&ac_a, &bb_a), std::cmp::Ordering::Greater);
1274 }
1275
1276 #[test]
1277 fn monomial_cmp_compatibility_randomized() {
1278 // Admissibility axiom: a ≫ b ⟹ a⊎x ≫ b⊎x (and Equal only for identical multisets).
1279 let mut rng: u64 = 42;
1280 let mut checked = 0usize;
1281 for _ in 0..2000 {
1282 let a = rand_ms(&mut rng);
1283 let b = rand_ms(&mut rng);
1284 let x = rand_ms(&mut rng);
1285 let ord = monomial_cmp(&a, &b);
1286 if ord == std::cmp::Ordering::Equal {
1287 assert_eq!(a, b, "Equal must mean identical multisets");
1288 continue;
1289 }
1290 assert_eq!(
1291 monomial_cmp(&multiset_union(&a, &x), &multiset_union(&b, &x)),
1292 ord,
1293 "compatibility violated: a={a:?} b={b:?} x={x:?}"
1294 );
1295 checked += 1;
1296 }
1297 assert!(checked > 1000);
1298 }
1299
1300 #[test]
1301 fn monomial_cmp_subterm_property_randomized() {
1302 // A proper super-multiset is strictly greater (degree component).
1303 let mut rng: u64 = 7;
1304 for _ in 0..1000 {
1305 let b = rand_ms(&mut rng);
1306 let mut ext = rand_ms(&mut rng);
1307 if ext.is_empty() {
1308 ext = ms(&[(1, 1)]);
1309 }
1310 let a = multiset_union(&b, &ext);
1311 assert_eq!(monomial_cmp(&a, &b), std::cmp::Ordering::Greater);
1312 }
1313 }
1314
1315 #[test]
1316 fn former_cycle_rules_terminate_at_irreducible_normal_form() {
1317 // Under the old tie-break, {b:2}→{a,c} and {a:2,c}→{a,b:2} both passed the
1318 // Greater orientation guard and normalize_ms two-cycled on {a,b:2} until the
1319 // defensive guard, returning a REDUCIBLE monomial. Under Kapur deg-lex the first
1320 // orients the other way; with both correctly oriented, normalization terminates
1321 // at an irreducible normal form from every start point.
1322 let r1 = NfRule {
1323 lhs: ms(&[(1, 1), (3, 1)]),
1324 rhs: ms(&[(2, 2)]),
1325 }; // {a,c} → {b:2}
1326 let r2 = NfRule {
1327 lhs: ms(&[(1, 2), (3, 1)]),
1328 rhs: ms(&[(1, 1), (2, 2)]),
1329 }; // {a:2,c} → {a,b:2}
1330 assert_eq!(monomial_cmp(&r1.lhs, &r1.rhs), std::cmp::Ordering::Greater);
1331 assert_eq!(monomial_cmp(&r2.lhs, &r2.rhs), std::cmp::Ordering::Greater);
1332 let rules = [r1, r2];
1333 for host in [
1334 ms(&[(1, 1), (2, 2)]),
1335 ms(&[(1, 2), (3, 1)]),
1336 ms(&[(1, 2), (3, 2)]),
1337 ] {
1338 let out = normalize_ms(&host, &rules);
1339 for r in &rules {
1340 assert!(
1341 !multiset_subset(&r.lhs, &out),
1342 "normalize_ms({host:?}) returned a reducible result {out:?}"
1343 );
1344 }
1345 }
1346 }
1347}