semi_persistent_egraph/ac_invariants.rs
1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// SPDX-License-Identifier: Apache-2.0
3//! Executable invariant checks for the AC reduced-basis (design §6b/§9a/§9b).
4//!
5//! These witness, at runtime, the properties the completion machinery is supposed to
6//! maintain, so a diverging run can be inspected via `printf` to see *which* invariant
7//! breaks. Diagnostic API, not a production hot path: each function rescans all
8//! nodes. See `doc/design/ac-completion-spec.md` §3 (the checkable properties).
9//!
10//! The model: every active AC node (not `FLAG_SUBSUMED`, not `FLAG_AC_COLLAPSED`) whose
11//! own monomial `M` is strictly `≫_f`-greater than its class's selected summand candidate
12//! `rhs` is a rule `+M → rhs`. The finite diagnostics are:
13//! - **antichain**: no active rule's LHS is a sub-multiset of another's (collapse, §6b);
14//! - **irreducible**: no active rule's LHS is reducible by *another* active rule
15//! (equivalent phrasing of the antichain; the §6b property collapse must keep);
16//! - **min_monomial consistency**: a non-atomic class's stored `min_monomial` really is the
17//! `monomial_cmp`-least AC monomial among that class's nodes.
18
19use crate::canon::{MSetCanon, VarCanon};
20use crate::config::EGraphConfig;
21use crate::containers::DenseId;
22use crate::egraph::EGraph;
23use crate::literal::LitVal;
24use crate::multiplicity::MultiplicityLike;
25use crate::multiset::{NfRule, monomial_cmp, multiset_subset, normalize_ms};
26use crate::node_types::{FLAG_AC_COLLAPSED, FLAG_SUBSUMED};
27use crate::typed_routing::NodeRef;
28use std::collections::BTreeMap;
29
30/// One active AC rule, materialized for inspection.
31pub struct BasisRule<G, O, M> {
32 pub node: G,
33 /// The typed op id. This was a `usize` copy of one, which cost the checker a
34 /// `Cfg::O::from_usize` conversion on every read to get back what it already had,
35 /// and widened the row past the configured op width for no gain — the field is only
36 /// ever compared for equality and printed.
37 pub op: O,
38 pub lhs: Vec<(G, M)>,
39 pub rhs: Vec<(G, M)>,
40}
41
42/// Result of checking the reduced-basis invariants on the current e-graph state.
43pub struct BasisReport<G, O, M> {
44 pub n_ac_nodes: usize,
45 pub n_subsumed: usize,
46 pub n_collapsed: usize,
47 pub rules: Vec<BasisRule<G, O, M>>,
48 /// Pairs (i, j) of `rules` indices where `rules[i].lhs ⊊ rules[j].lhs` and same op:
49 /// `rules[j]` is reducible by `rules[i]`, so it should have been collapsed (§6b).
50 /// Non-empty ⟹ the antichain/irreducible invariant is violated (collapse bug).
51 pub reducible_pairs: Vec<(usize, usize)>,
52 /// Distinct `rules` indices that are reducible (the `j` side of some pair): rules that
53 /// inter-reduction would retire. `rules.len() - reducible_rule_count` is the antichain
54 /// core after one direct-containment pass, not a canonical or necessarily fully reduced
55 /// basis size. A core far below the active count diagnoses direct collapse debt in this
56 /// finite state.
57 pub reducible_rule_count: usize,
58}
59
60impl<Cfg: EGraphConfig, L: LitVal, const TRACK: bool, const PROOFS: bool>
61 EGraph<Cfg, L, TRACK, PROOFS>
62where
63 MSetCanon: VarCanon<Cfg::G, Cfg::C>,
64{
65 /// Canonical child monomial (class-repr, mult) of a completion node — MSet (coalesced
66 /// counts) or Set (deduped, all counts 1). Delegates to the engine's own
67 /// `node_monomial_into` so the checker cannot drift from what completion reads.
68 fn cc_invariant_monomial(&self, id: Cfg::G) -> Vec<(Cfg::G, Cfg::M)> {
69 let mut out = Vec::new();
70 self.node_monomial_into(id, &mut out);
71 out
72 }
73
74 /// The class's canonical summand form (the rule RHS): the empty monomial if the class
75 /// is the op's identity (Kapur's `f({}) = e`, see `class_rhs_into`), `{class}` if
76 /// atomic, else the monomial of the stored `min_monomial`. Mirrors `class_rhs_into`.
77 fn cc_invariant_rhs(&self, id: Cfg::G) -> Vec<(Cfg::G, Cfg::M)> {
78 let cls = self.class_repr(id);
79 if self
80 .unit_node(self.node_op(id))
81 .is_some_and(|u| self.class_repr(u) == cls)
82 {
83 return Vec::new();
84 }
85 if self.class_atomic(id) == Some(true) {
86 vec![(cls, Cfg::M::ONE)]
87 } else if let Some(min_node) = self.class_min_monomial(id) {
88 self.cc_invariant_monomial(min_node)
89 } else {
90 vec![(cls, Cfg::M::ONE)]
91 }
92 }
93
94 /// Compute the current active AC rule set and check the reduced-basis invariants.
95 /// Pure read; safe to call any time. Diagnostic operation that rescans all nodes.
96 pub fn cc_basis_report(&self) -> BasisReport<Cfg::G, Cfg::O, Cfg::M> {
97 let inactive = FLAG_SUBSUMED | FLAG_AC_COLLAPSED;
98 let (mut n_ac_nodes, mut n_subsumed, mut n_collapsed) = (0usize, 0usize, 0usize);
99 let mut rules: Vec<BasisRule<Cfg::G, Cfg::O, Cfg::M>> = Vec::new();
100
101 for gid in self.node_ids() {
102 // Both completion partitions: MSet (plain AC / nilpotent) and Set (ACI).
103 if !matches!(self.node_ref(gid), NodeRef::MSet(_) | NodeRef::Set(_)) {
104 continue;
105 }
106 n_ac_nodes += 1;
107 let flags = self.node_flags(gid);
108 if flags & FLAG_SUBSUMED != 0 {
109 n_subsumed += 1;
110 }
111 if flags & FLAG_AC_COLLAPSED != 0 {
112 n_collapsed += 1;
113 }
114 if flags & inactive != 0 {
115 continue;
116 }
117 let lhs = self.cc_invariant_monomial(gid);
118 let rhs = self.cc_invariant_rhs(gid);
119 // A node is a rule iff its own monomial is strictly greater than its RHS.
120 if monomial_cmp(&lhs, &rhs) == std::cmp::Ordering::Greater {
121 rules.push(BasisRule {
122 node: gid,
123 op: self.node_op(gid),
124 lhs,
125 rhs,
126 });
127 }
128 }
129
130 // Reducible pairs: rules[i].lhs ⊊ rules[j].lhs, same op ⟹ j reducible by i.
131 let mut reducible_pairs = Vec::new();
132 for i in 0..rules.len() {
133 for j in 0..rules.len() {
134 if i == j || rules[i].op != rules[j].op {
135 continue;
136 }
137 if rules[i].lhs != rules[j].lhs && multiset_subset(&rules[i].lhs, &rules[j].lhs) {
138 reducible_pairs.push((i, j));
139 }
140 }
141 }
142
143 let mut reducible: std::collections::BTreeSet<usize> = std::collections::BTreeSet::new();
144 for &(_, j) in &reducible_pairs {
145 reducible.insert(j);
146 }
147 let reducible_rule_count = reducible.len();
148
149 BasisReport {
150 n_ac_nodes,
151 n_subsumed,
152 n_collapsed,
153 rules,
154 reducible_pairs,
155 reducible_rule_count,
156 }
157 }
158
159 /// GROUND-TRUTH check 1: is the RHS each rule actually *uses* the true minimal monomial?
160 ///
161 /// `cc_basis_report` reads `rhs` exactly as completion does (`class_rhs_into`: `{class}`
162 /// if atomic, else the stored `min_monomial`). Here we instead brute-force, per (class, op),
163 /// the `monomial_cmp`-least monomial over *all* active AC nodes of that op in the class,
164 /// and compare. A mismatch means the RHS completion used was **not** minimal at the point
165 /// of use (the §1.4 best-effort gap, or, more seriously, the single-op-slot conflating two
166 /// AC ops, §9b axis-1). Returns the count of rules whose used RHS is non-minimal, and the
167 /// worst offenders. Op-aware: the true min is taken only over same-op nodes.
168 pub fn cc_min_used_nonminimal(&self) -> (usize, Vec<(Cfg::G, Cfg::O)>) {
169 let inactive = FLAG_SUBSUMED | FLAG_AC_COLLAPSED;
170 // Per (class repr, op): the true least same-op monomial among active AC nodes. Both
171 // halves of the key are typed ids: dense ids are `Ord`, so widening the op to a
172 // `usize` bought the map nothing and cost the width.
173 let mut truemin: BTreeMap<(Cfg::G, Cfg::O), Vec<(Cfg::G, Cfg::M)>> = BTreeMap::new();
174 for gid in self.node_ids() {
175 if !matches!(self.node_ref(gid), NodeRef::MSet(_) | NodeRef::Set(_))
176 || self.node_flags(gid) & inactive != 0
177 {
178 continue;
179 }
180 let key = (self.class_repr(gid), self.node_op(gid));
181 let m = self.cc_invariant_monomial(gid);
182 truemin
183 .entry(key)
184 .and_modify(|cur| {
185 if monomial_cmp(&m, cur) == std::cmp::Ordering::Less {
186 *cur = m.clone();
187 }
188 })
189 .or_insert(m);
190 }
191 // For every active rule, compare the RHS it would *use* to the true min of its op.
192 let mut nonminimal = 0usize;
193 let mut offenders: Vec<(Cfg::G, Cfg::O)> = Vec::new();
194 for gid in self.node_ids() {
195 if !matches!(self.node_ref(gid), NodeRef::MSet(_) | NodeRef::Set(_))
196 || self.node_flags(gid) & inactive != 0
197 {
198 continue;
199 }
200 let op = self.node_op(gid);
201 let lhs = self.cc_invariant_monomial(gid);
202 let rhs = self.cc_invariant_rhs(gid);
203 if monomial_cmp(&lhs, &rhs) != std::cmp::Ordering::Greater {
204 continue; // not a rule
205 }
206 // The used RHS is non-minimal iff a strictly smaller same-op monomial exists in
207 // the class AND the used RHS is not itself that minimum. `{class}` (atomic) is a
208 // legitimately smaller representative, so only flag when the used RHS is the
209 // `min_monomial` monomial yet a smaller same-op node exists.
210 if self.class_atomic(gid) == Some(true) {
211 continue; // RHS is `{class}`, the genuine size-1 minimum; not an min_monomial question
212 }
213 if let Some(tm) = truemin.get(&(self.class_repr(gid), op))
214 && monomial_cmp(tm, &rhs) == std::cmp::Ordering::Less
215 {
216 nonminimal += 1;
217 offenders.push((gid, op));
218 }
219 }
220 offenders.truncate(20);
221 (nonminimal, offenders)
222 }
223
224 /// Finite-state diagnostic 2: is the active rule set *fully reduced* in Kapur's sense
225 /// (§3), rather than only a direct-containment antichain? Kapur-reduced means that neither
226 /// side of any rule can be rewritten by the *other* rules. `reducible_pairs` only catches
227 /// direct sub-multiset containment; this computes multi-step normalization in the current
228 /// finite rule set. It is not a theorem about every reachable state.
229 ///
230 /// Returns `(n_lhs_reducible, n_rhs_reducible)`. The `.egg` basis gate currently asserts
231 /// only that the LHS count is zero; callers that require full reducedness must check both.
232 pub fn cc_not_kapur_reduced(&self) -> (usize, usize) {
233 use crate::egraph::CompletionClamp;
234 use crate::multiset::{normalize_nilpotent, normalize_set};
235 let r = self.cc_basis_report();
236 // Per op, the NfRule set (every rule except the one under test is the reducer set).
237 let mut n_lhs = 0usize;
238 let mut n_rhs = 0usize;
239 for k in 0..r.rules.len() {
240 let op = r.rules[k].op;
241 let others: Vec<NfRule<Cfg::G, Cfg::M>> = r
242 .rules
243 .iter()
244 .enumerate()
245 .filter(|(j, rj)| *j != k && rj.op == op)
246 .map(|(_, rj)| NfRule {
247 lhs: rj.lhs.clone(),
248 rhs: rj.rhs.clone(),
249 })
250 .collect();
251 // Normalize in the op's count domain (idempotent → set, nilpotent → mod-n,
252 // plain AC → ℕ), matching cc_round — a Set rule checked in ℕ would miss
253 // clamp-joins and report spurious reducibility.
254 let clamp = self.op_clamp(op);
255 let nf = |m: &[(Cfg::G, Cfg::M)]| -> Vec<(Cfg::G, Cfg::M)> {
256 match clamp {
257 CompletionClamp::Idempotent => normalize_set(m, &others),
258 CompletionClamp::Nilpotent { order } => normalize_nilpotent(m, &others, order),
259 CompletionClamp::Multiset => normalize_ms(m, &others),
260 }
261 };
262 if nf(&r.rules[k].lhs) != r.rules[k].lhs {
263 n_lhs += 1;
264 }
265 if nf(&r.rules[k].rhs) != r.rules[k].rhs {
266 n_rhs += 1;
267 }
268 }
269 (n_lhs, n_rhs)
270 }
271
272 /// Ground-truth check 3 (Kapur §4): every per-rule axiom critical pair of
273 /// an idempotent or nilpotent op is joinable under the current state.
274 ///
275 /// - Idempotent (Lemma 4.1(ii)): for a rule `f(M) → f(N)` and each `a ∈ M`, the pair
276 /// `(f(N ⊎ {a}), f(N))` must join.
277 /// - Nilpotent order n (Lemma 4.2(ii)/4.5): for each `a` with multiplicity `m` in `M`,
278 /// the pair `(f(N ⊎ {a: n−m}), f(M − {a: m}))` must join.
279 ///
280 /// "Join" is checked at the e-graph level, where Kapur's constant rules live in the
281 /// union-find: the two reducts join iff their normal forms coincide as multisets, or
282 /// both resolve (lookup-only, no mutation) to the *same class*. A reduct that neither
283 /// matches nor resolves was never materialized — the completion missed the axiom
284 /// superposition. Rules are read over BOTH completion partitions (MSet and Set).
285 /// Returns the non-joinable pair count and up to 20 (rule node, op) witnesses.
286 pub fn cc_axiom_cps_nonjoinable(&self) -> (usize, Vec<(Cfg::G, Cfg::O)>) {
287 use crate::egraph::CompletionClamp;
288 use crate::multiset::{
289 clamp_idempotent, clamp_nilpotent, multiset_subtract, multiset_union,
290 normalize_nilpotent, normalize_set,
291 };
292 let inactive = FLAG_SUBSUMED | FLAG_AC_COLLAPSED;
293
294 // Active rules over both partitions, exactly as cc_round reads them.
295 struct AxRule<G, O, M> {
296 node: G,
297 /// Typed, for the reason [`BasisRule::op`] gives.
298 op: O,
299 lhs: Vec<(G, M)>,
300 rhs: Vec<(G, M)>,
301 }
302 let mut rules: Vec<AxRule<Cfg::G, Cfg::O, Cfg::M>> = Vec::new();
303 let mut lhs_buf = Vec::new();
304 let mut rhs_buf = Vec::new();
305 for gid in self.node_ids() {
306 if !matches!(self.node_ref(gid), NodeRef::MSet(_) | NodeRef::Set(_))
307 || self.node_flags(gid) & inactive != 0
308 {
309 continue;
310 }
311 self.node_monomial_into(gid, &mut lhs_buf);
312 if !self.class_rhs_into(gid, &mut rhs_buf) {
313 continue;
314 }
315 if monomial_cmp(&lhs_buf, &rhs_buf) == std::cmp::Ordering::Greater {
316 rules.push(AxRule {
317 node: gid,
318 op: self.node_op(gid),
319 lhs: lhs_buf.clone(),
320 rhs: rhs_buf.clone(),
321 });
322 }
323 }
324
325 let mut nonjoin = 0usize;
326 let mut offenders: Vec<(Cfg::G, Cfg::O)> = Vec::new();
327 for k in 0..rules.len() {
328 let op = rules[k].op;
329 let clamp = self.op_clamp(op);
330 type Pair<G, M> = (Vec<(G, M)>, Vec<(G, M)>);
331 let axiom_pairs: Vec<Pair<Cfg::G, Cfg::M>> = match clamp {
332 CompletionClamp::Idempotent => rules[k]
333 .lhs
334 .iter()
335 .map(|&(a, _)| {
336 let mut r1 = multiset_union(&rules[k].rhs, &[(a, Cfg::M::ONE)]);
337 clamp_idempotent(&mut r1);
338 (r1, rules[k].rhs.clone())
339 })
340 .collect(),
341 CompletionClamp::Nilpotent { order } => rules[k]
342 .lhs
343 .iter()
344 .filter_map(|&(a, m)| {
345 // `order` is a `u8`, so the deficit is below 256 and
346 // representable at every supported multiplicity width.
347 let ord = Cfg::M::try_from_u64(u64::from(order))
348 .expect("a u8 nilpotent order fits every multiplicity width");
349 let extra = ord.saturating_sub(m);
350 if extra == Cfg::M::ZERO {
351 return None;
352 }
353 let mut r1 = multiset_union(&rules[k].rhs, &[(a, extra)]);
354 clamp_nilpotent(&mut r1, order);
355 Some((r1, multiset_subtract(&rules[k].lhs, &[(a, m)])))
356 })
357 .collect(),
358 CompletionClamp::Multiset => Vec::new(),
359 };
360 if axiom_pairs.is_empty() {
361 continue;
362 }
363 let nf_rules: Vec<NfRule<Cfg::G, Cfg::M>> = rules
364 .iter()
365 .filter(|r| r.op == rules[k].op)
366 .map(|r| NfRule {
367 lhs: r.lhs.clone(),
368 rhs: r.rhs.clone(),
369 })
370 .collect();
371 for (r1, r2) in axiom_pairs {
372 let (n1, n2) = match clamp {
373 CompletionClamp::Idempotent => {
374 (normalize_set(&r1, &nf_rules), normalize_set(&r2, &nf_rules))
375 }
376 CompletionClamp::Nilpotent { order } => (
377 normalize_nilpotent(&r1, &nf_rules, order),
378 normalize_nilpotent(&r2, &nf_rules, order),
379 ),
380 CompletionClamp::Multiset => unreachable!(),
381 };
382 let joined = n1 == n2
383 || matches!(
384 (
385 self.resolve_monomial_class(op, &n1),
386 self.resolve_monomial_class(op, &n2)
387 ),
388 (Some(c1), Some(c2)) if c1 == c2
389 );
390 if !joined {
391 nonjoin += 1;
392 if offenders.len() < 20 {
393 offenders.push((rules[k].node, rules[k].op));
394 }
395 }
396 }
397 }
398 (nonjoin, offenders)
399 }
400
401 /// Print the basis report (one line per rule + the invariant verdicts). `tag` labels
402 /// the call site (e.g. a round number). This operation rescans all nodes.
403 pub fn cc_basis_dump(&self, tag: &str) {
404 let r = self.cc_basis_report();
405 let (nonmin, _) = self.cc_min_used_nonminimal();
406 let (lhs_red, rhs_red) = self.cc_not_kapur_reduced();
407 eprintln!(
408 "[basis {tag}] completion_nodes={} subsumed={} collapsed={} active_rules={} reducible_pairs={} reducible_rules={} antichain_core={} | cc_min_used_nonminimal={nonmin} kapur_lhs_reducible={lhs_red} kapur_rhs_reducible={rhs_red}",
409 r.n_ac_nodes,
410 r.n_subsumed,
411 r.n_collapsed,
412 r.rules.len(),
413 r.reducible_pairs.len(),
414 r.reducible_rule_count,
415 r.rules.len() - r.reducible_rule_count,
416 );
417 let show = |m: &[(Cfg::G, Cfg::M)]| -> String {
418 let mut s = String::from("{");
419 for (k, (g, mult)) in m.iter().enumerate() {
420 if k > 0 {
421 s.push(',');
422 }
423 s.push_str(&format!("{}:{}", g.to_usize(), mult));
424 }
425 s.push('}');
426 s
427 };
428 for (k, rule) in r.rules.iter().enumerate() {
429 eprintln!(
430 "[basis {tag}] rule[{k}] node={} op={} lhs={} -> rhs={}",
431 rule.node.to_usize(),
432 rule.op.to_usize(),
433 show(&rule.lhs),
434 show(&rule.rhs),
435 );
436 }
437 for &(i, j) in &r.reducible_pairs {
438 eprintln!(
439 "[basis {tag}] !! REDUCIBLE: rule[{j}] (node {}) lhs {} contains rule[{i}] (node {}) lhs {} — should be collapsed",
440 r.rules[j].node.to_usize(),
441 show(&r.rules[j].lhs),
442 r.rules[i].node.to_usize(),
443 show(&r.rules[i].lhs),
444 );
445 }
446 }
447}