semi-persistent-egraph 0.2.0

Semi-persistent equality saturation engine with e-matching, rewrite scheduling, and proof logging
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//! Executable invariant checks for the AC reduced-basis (design §6b/§9a/§9b).
//!
//! These witness, at runtime, the properties the completion machinery is supposed to
//! maintain, so a diverging run can be inspected via `printf` to see *which* invariant
//! breaks. Diagnostic API, not a production hot path: each function rescans all
//! nodes. See `doc/design/ac-completion-spec.md` §3 (the checkable properties).
//!
//! The model: every active AC node (not `FLAG_SUBSUMED`, not `FLAG_AC_COLLAPSED`) whose
//! own monomial `M` is strictly `≫_f`-greater than its class's selected summand candidate
//! `rhs` is a rule `+M → rhs`. The finite diagnostics are:
//!  - **antichain**: no active rule's LHS is a sub-multiset of another's (collapse, §6b);
//!  - **irreducible**: no active rule's LHS is reducible by *another* active rule
//!    (equivalent phrasing of the antichain; the §6b property collapse must keep);
//!  - **min_monomial consistency**: a non-atomic class's stored `min_monomial` really is the
//!    `monomial_cmp`-least AC monomial among that class's nodes.

use crate::canon::{MSetCanon, VarCanon};
use crate::config::EGraphConfig;
use crate::containers::DenseId;
use crate::egraph::EGraph;
use crate::literal::LitVal;
use crate::multiplicity::MultiplicityLike;
use crate::multiset::{NfRule, monomial_cmp, multiset_subset, normalize_ms};
use crate::node_types::{FLAG_AC_COLLAPSED, FLAG_SUBSUMED};
use crate::typed_routing::NodeRef;
use std::collections::BTreeMap;

/// One active AC rule, materialized for inspection.
pub struct BasisRule<G, O, M> {
    pub node: G,
    /// The typed op id. This was a `usize` copy of one, which cost the checker a
    /// `Cfg::O::from_usize` conversion on every read to get back what it already had,
    /// and widened the row past the configured op width for no gain — the field is only
    /// ever compared for equality and printed.
    pub op: O,
    pub lhs: Vec<(G, M)>,
    pub rhs: Vec<(G, M)>,
}

/// Result of checking the reduced-basis invariants on the current e-graph state.
pub struct BasisReport<G, O, M> {
    pub n_ac_nodes: usize,
    pub n_subsumed: usize,
    pub n_collapsed: usize,
    pub rules: Vec<BasisRule<G, O, M>>,
    /// Pairs (i, j) of `rules` indices where `rules[i].lhs ⊊ rules[j].lhs` and same op:
    /// `rules[j]` is reducible by `rules[i]`, so it should have been collapsed (§6b).
    /// Non-empty ⟹ the antichain/irreducible invariant is violated (collapse bug).
    pub reducible_pairs: Vec<(usize, usize)>,
    /// Distinct `rules` indices that are reducible (the `j` side of some pair): rules that
    /// inter-reduction would retire. `rules.len() - reducible_rule_count` is the antichain
    /// core after one direct-containment pass, not a canonical or necessarily fully reduced
    /// basis size. A core far below the active count diagnoses direct collapse debt in this
    /// finite state.
    pub reducible_rule_count: usize,
}

impl<Cfg: EGraphConfig, L: LitVal, const TRACK: bool, const PROOFS: bool>
    EGraph<Cfg, L, TRACK, PROOFS>
where
    MSetCanon: VarCanon<Cfg::G, Cfg::C>,
{
    /// Canonical child monomial (class-repr, mult) of a completion node — MSet (coalesced
    /// counts) or Set (deduped, all counts 1). Delegates to the engine's own
    /// `node_monomial_into` so the checker cannot drift from what completion reads.
    fn cc_invariant_monomial(&self, id: Cfg::G) -> Vec<(Cfg::G, Cfg::M)> {
        let mut out = Vec::new();
        self.node_monomial_into(id, &mut out);
        out
    }

    /// The class's canonical summand form (the rule RHS): the empty monomial if the class
    /// is the op's identity (Kapur's `f({}) = e`, see `class_rhs_into`), `{class}` if
    /// atomic, else the monomial of the stored `min_monomial`. Mirrors `class_rhs_into`.
    fn cc_invariant_rhs(&self, id: Cfg::G) -> Vec<(Cfg::G, Cfg::M)> {
        let cls = self.class_repr(id);
        if self
            .unit_node(self.node_op(id))
            .is_some_and(|u| self.class_repr(u) == cls)
        {
            return Vec::new();
        }
        if self.class_atomic(id) == Some(true) {
            vec![(cls, Cfg::M::ONE)]
        } else if let Some(min_node) = self.class_min_monomial(id) {
            self.cc_invariant_monomial(min_node)
        } else {
            vec![(cls, Cfg::M::ONE)]
        }
    }

    /// Compute the current active AC rule set and check the reduced-basis invariants.
    /// Pure read; safe to call any time. Diagnostic operation that rescans all nodes.
    pub fn cc_basis_report(&self) -> BasisReport<Cfg::G, Cfg::O, Cfg::M> {
        let inactive = FLAG_SUBSUMED | FLAG_AC_COLLAPSED;
        let (mut n_ac_nodes, mut n_subsumed, mut n_collapsed) = (0usize, 0usize, 0usize);
        let mut rules: Vec<BasisRule<Cfg::G, Cfg::O, Cfg::M>> = Vec::new();

        for gid in self.node_ids() {
            // Both completion partitions: MSet (plain AC / nilpotent) and Set (ACI).
            if !matches!(self.node_ref(gid), NodeRef::MSet(_) | NodeRef::Set(_)) {
                continue;
            }
            n_ac_nodes += 1;
            let flags = self.node_flags(gid);
            if flags & FLAG_SUBSUMED != 0 {
                n_subsumed += 1;
            }
            if flags & FLAG_AC_COLLAPSED != 0 {
                n_collapsed += 1;
            }
            if flags & inactive != 0 {
                continue;
            }
            let lhs = self.cc_invariant_monomial(gid);
            let rhs = self.cc_invariant_rhs(gid);
            // A node is a rule iff its own monomial is strictly greater than its RHS.
            if monomial_cmp(&lhs, &rhs) == std::cmp::Ordering::Greater {
                rules.push(BasisRule {
                    node: gid,
                    op: self.node_op(gid),
                    lhs,
                    rhs,
                });
            }
        }

        // Reducible pairs: rules[i].lhs ⊊ rules[j].lhs, same op ⟹ j reducible by i.
        let mut reducible_pairs = Vec::new();
        for i in 0..rules.len() {
            for j in 0..rules.len() {
                if i == j || rules[i].op != rules[j].op {
                    continue;
                }
                if rules[i].lhs != rules[j].lhs && multiset_subset(&rules[i].lhs, &rules[j].lhs) {
                    reducible_pairs.push((i, j));
                }
            }
        }

        let mut reducible: std::collections::BTreeSet<usize> = std::collections::BTreeSet::new();
        for &(_, j) in &reducible_pairs {
            reducible.insert(j);
        }
        let reducible_rule_count = reducible.len();

        BasisReport {
            n_ac_nodes,
            n_subsumed,
            n_collapsed,
            rules,
            reducible_pairs,
            reducible_rule_count,
        }
    }

    /// GROUND-TRUTH check 1: is the RHS each rule actually *uses* the true minimal monomial?
    ///
    /// `cc_basis_report` reads `rhs` exactly as completion does (`class_rhs_into`: `{class}`
    /// if atomic, else the stored `min_monomial`). Here we instead brute-force, per (class, op),
    /// the `monomial_cmp`-least monomial over *all* active AC nodes of that op in the class,
    /// and compare. A mismatch means the RHS completion used was **not** minimal at the point
    /// of use (the §1.4 best-effort gap, or, more seriously, the single-op-slot conflating two
    /// AC ops, §9b axis-1). Returns the count of rules whose used RHS is non-minimal, and the
    /// worst offenders. Op-aware: the true min is taken only over same-op nodes.
    pub fn cc_min_used_nonminimal(&self) -> (usize, Vec<(Cfg::G, Cfg::O)>) {
        let inactive = FLAG_SUBSUMED | FLAG_AC_COLLAPSED;
        // Per (class repr, op): the true least same-op monomial among active AC nodes. Both
        // halves of the key are typed ids: dense ids are `Ord`, so widening the op to a
        // `usize` bought the map nothing and cost the width.
        let mut truemin: BTreeMap<(Cfg::G, Cfg::O), Vec<(Cfg::G, Cfg::M)>> = BTreeMap::new();
        for gid in self.node_ids() {
            if !matches!(self.node_ref(gid), NodeRef::MSet(_) | NodeRef::Set(_))
                || self.node_flags(gid) & inactive != 0
            {
                continue;
            }
            let key = (self.class_repr(gid), self.node_op(gid));
            let m = self.cc_invariant_monomial(gid);
            truemin
                .entry(key)
                .and_modify(|cur| {
                    if monomial_cmp(&m, cur) == std::cmp::Ordering::Less {
                        *cur = m.clone();
                    }
                })
                .or_insert(m);
        }
        // For every active rule, compare the RHS it would *use* to the true min of its op.
        let mut nonminimal = 0usize;
        let mut offenders: Vec<(Cfg::G, Cfg::O)> = Vec::new();
        for gid in self.node_ids() {
            if !matches!(self.node_ref(gid), NodeRef::MSet(_) | NodeRef::Set(_))
                || self.node_flags(gid) & inactive != 0
            {
                continue;
            }
            let op = self.node_op(gid);
            let lhs = self.cc_invariant_monomial(gid);
            let rhs = self.cc_invariant_rhs(gid);
            if monomial_cmp(&lhs, &rhs) != std::cmp::Ordering::Greater {
                continue; // not a rule
            }
            // The used RHS is non-minimal iff a strictly smaller same-op monomial exists in
            // the class AND the used RHS is not itself that minimum. `{class}` (atomic) is a
            // legitimately smaller representative, so only flag when the used RHS is the
            // `min_monomial` monomial yet a smaller same-op node exists.
            if self.class_atomic(gid) == Some(true) {
                continue; // RHS is `{class}`, the genuine size-1 minimum; not an min_monomial question
            }
            if let Some(tm) = truemin.get(&(self.class_repr(gid), op))
                && monomial_cmp(tm, &rhs) == std::cmp::Ordering::Less
            {
                nonminimal += 1;
                offenders.push((gid, op));
            }
        }
        offenders.truncate(20);
        (nonminimal, offenders)
    }

    /// Finite-state diagnostic 2: is the active rule set *fully reduced* in Kapur's sense
    /// (§3), rather than only a direct-containment antichain? Kapur-reduced means that neither
    /// side of any rule can be rewritten by the *other* rules. `reducible_pairs` only catches
    /// direct sub-multiset containment; this computes multi-step normalization in the current
    /// finite rule set. It is not a theorem about every reachable state.
    ///
    /// Returns `(n_lhs_reducible, n_rhs_reducible)`. The `.egg` basis gate currently asserts
    /// only that the LHS count is zero; callers that require full reducedness must check both.
    pub fn cc_not_kapur_reduced(&self) -> (usize, usize) {
        use crate::egraph::CompletionClamp;
        use crate::multiset::{normalize_nilpotent, normalize_set};
        let r = self.cc_basis_report();
        // Per op, the NfRule set (every rule except the one under test is the reducer set).
        let mut n_lhs = 0usize;
        let mut n_rhs = 0usize;
        for k in 0..r.rules.len() {
            let op = r.rules[k].op;
            let others: Vec<NfRule<Cfg::G, Cfg::M>> = r
                .rules
                .iter()
                .enumerate()
                .filter(|(j, rj)| *j != k && rj.op == op)
                .map(|(_, rj)| NfRule {
                    lhs: rj.lhs.clone(),
                    rhs: rj.rhs.clone(),
                })
                .collect();
            // Normalize in the op's count domain (idempotent → set, nilpotent → mod-n,
            // plain AC → ℕ), matching cc_round — a Set rule checked in ℕ would miss
            // clamp-joins and report spurious reducibility.
            let clamp = self.op_clamp(op);
            let nf = |m: &[(Cfg::G, Cfg::M)]| -> Vec<(Cfg::G, Cfg::M)> {
                match clamp {
                    CompletionClamp::Idempotent => normalize_set(m, &others),
                    CompletionClamp::Nilpotent { order } => normalize_nilpotent(m, &others, order),
                    CompletionClamp::Multiset => normalize_ms(m, &others),
                }
            };
            if nf(&r.rules[k].lhs) != r.rules[k].lhs {
                n_lhs += 1;
            }
            if nf(&r.rules[k].rhs) != r.rules[k].rhs {
                n_rhs += 1;
            }
        }
        (n_lhs, n_rhs)
    }

    /// Ground-truth check 3 (Kapur §4): every per-rule axiom critical pair of
    /// an idempotent or nilpotent op is joinable under the current state.
    ///
    /// - Idempotent (Lemma 4.1(ii)): for a rule `f(M) → f(N)` and each `a ∈ M`, the pair
    ///   `(f(N ⊎ {a}), f(N))` must join.
    /// - Nilpotent order n (Lemma 4.2(ii)/4.5): for each `a` with multiplicity `m` in `M`,
    ///   the pair `(f(N ⊎ {a: n−m}), f(M − {a: m}))` must join.
    ///
    /// "Join" is checked at the e-graph level, where Kapur's constant rules live in the
    /// union-find: the two reducts join iff their normal forms coincide as multisets, or
    /// both resolve (lookup-only, no mutation) to the *same class*. A reduct that neither
    /// matches nor resolves was never materialized — the completion missed the axiom
    /// superposition. Rules are read over BOTH completion partitions (MSet and Set).
    /// Returns the non-joinable pair count and up to 20 (rule node, op) witnesses.
    pub fn cc_axiom_cps_nonjoinable(&self) -> (usize, Vec<(Cfg::G, Cfg::O)>) {
        use crate::egraph::CompletionClamp;
        use crate::multiset::{
            clamp_idempotent, clamp_nilpotent, multiset_subtract, multiset_union,
            normalize_nilpotent, normalize_set,
        };
        let inactive = FLAG_SUBSUMED | FLAG_AC_COLLAPSED;

        // Active rules over both partitions, exactly as cc_round reads them.
        struct AxRule<G, O, M> {
            node: G,
            /// Typed, for the reason [`BasisRule::op`] gives.
            op: O,
            lhs: Vec<(G, M)>,
            rhs: Vec<(G, M)>,
        }
        let mut rules: Vec<AxRule<Cfg::G, Cfg::O, Cfg::M>> = Vec::new();
        let mut lhs_buf = Vec::new();
        let mut rhs_buf = Vec::new();
        for gid in self.node_ids() {
            if !matches!(self.node_ref(gid), NodeRef::MSet(_) | NodeRef::Set(_))
                || self.node_flags(gid) & inactive != 0
            {
                continue;
            }
            self.node_monomial_into(gid, &mut lhs_buf);
            if !self.class_rhs_into(gid, &mut rhs_buf) {
                continue;
            }
            if monomial_cmp(&lhs_buf, &rhs_buf) == std::cmp::Ordering::Greater {
                rules.push(AxRule {
                    node: gid,
                    op: self.node_op(gid),
                    lhs: lhs_buf.clone(),
                    rhs: rhs_buf.clone(),
                });
            }
        }

        let mut nonjoin = 0usize;
        let mut offenders: Vec<(Cfg::G, Cfg::O)> = Vec::new();
        for k in 0..rules.len() {
            let op = rules[k].op;
            let clamp = self.op_clamp(op);
            type Pair<G, M> = (Vec<(G, M)>, Vec<(G, M)>);
            let axiom_pairs: Vec<Pair<Cfg::G, Cfg::M>> = match clamp {
                CompletionClamp::Idempotent => rules[k]
                    .lhs
                    .iter()
                    .map(|&(a, _)| {
                        let mut r1 = multiset_union(&rules[k].rhs, &[(a, Cfg::M::ONE)]);
                        clamp_idempotent(&mut r1);
                        (r1, rules[k].rhs.clone())
                    })
                    .collect(),
                CompletionClamp::Nilpotent { order } => rules[k]
                    .lhs
                    .iter()
                    .filter_map(|&(a, m)| {
                        // `order` is a `u8`, so the deficit is below 256 and
                        // representable at every supported multiplicity width.
                        let ord = Cfg::M::try_from_u64(u64::from(order))
                            .expect("a u8 nilpotent order fits every multiplicity width");
                        let extra = ord.saturating_sub(m);
                        if extra == Cfg::M::ZERO {
                            return None;
                        }
                        let mut r1 = multiset_union(&rules[k].rhs, &[(a, extra)]);
                        clamp_nilpotent(&mut r1, order);
                        Some((r1, multiset_subtract(&rules[k].lhs, &[(a, m)])))
                    })
                    .collect(),
                CompletionClamp::Multiset => Vec::new(),
            };
            if axiom_pairs.is_empty() {
                continue;
            }
            let nf_rules: Vec<NfRule<Cfg::G, Cfg::M>> = rules
                .iter()
                .filter(|r| r.op == rules[k].op)
                .map(|r| NfRule {
                    lhs: r.lhs.clone(),
                    rhs: r.rhs.clone(),
                })
                .collect();
            for (r1, r2) in axiom_pairs {
                let (n1, n2) = match clamp {
                    CompletionClamp::Idempotent => {
                        (normalize_set(&r1, &nf_rules), normalize_set(&r2, &nf_rules))
                    }
                    CompletionClamp::Nilpotent { order } => (
                        normalize_nilpotent(&r1, &nf_rules, order),
                        normalize_nilpotent(&r2, &nf_rules, order),
                    ),
                    CompletionClamp::Multiset => unreachable!(),
                };
                let joined = n1 == n2
                    || matches!(
                        (
                            self.resolve_monomial_class(op, &n1),
                            self.resolve_monomial_class(op, &n2)
                        ),
                        (Some(c1), Some(c2)) if c1 == c2
                    );
                if !joined {
                    nonjoin += 1;
                    if offenders.len() < 20 {
                        offenders.push((rules[k].node, rules[k].op));
                    }
                }
            }
        }
        (nonjoin, offenders)
    }

    /// Print the basis report (one line per rule + the invariant verdicts). `tag` labels
    /// the call site (e.g. a round number). This operation rescans all nodes.
    pub fn cc_basis_dump(&self, tag: &str) {
        let r = self.cc_basis_report();
        let (nonmin, _) = self.cc_min_used_nonminimal();
        let (lhs_red, rhs_red) = self.cc_not_kapur_reduced();
        eprintln!(
            "[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}",
            r.n_ac_nodes,
            r.n_subsumed,
            r.n_collapsed,
            r.rules.len(),
            r.reducible_pairs.len(),
            r.reducible_rule_count,
            r.rules.len() - r.reducible_rule_count,
        );
        let show = |m: &[(Cfg::G, Cfg::M)]| -> String {
            let mut s = String::from("{");
            for (k, (g, mult)) in m.iter().enumerate() {
                if k > 0 {
                    s.push(',');
                }
                s.push_str(&format!("{}:{}", g.to_usize(), mult));
            }
            s.push('}');
            s
        };
        for (k, rule) in r.rules.iter().enumerate() {
            eprintln!(
                "[basis {tag}]   rule[{k}] node={} op={} lhs={} -> rhs={}",
                rule.node.to_usize(),
                rule.op.to_usize(),
                show(&rule.lhs),
                show(&rule.rhs),
            );
        }
        for &(i, j) in &r.reducible_pairs {
            eprintln!(
                "[basis {tag}]   !! REDUCIBLE: rule[{j}] (node {}) lhs {} contains rule[{i}] (node {}) lhs {} — should be collapsed",
                r.rules[j].node.to_usize(),
                show(&r.rules[j].lhs),
                r.rules[i].node.to_usize(),
                show(&r.rules[i].lhs),
            );
        }
    }
}