Skip to main content

semi_persistent_egraph/
cc.rs

1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// SPDX-License-Identifier: Apache-2.0
3//! AC congruence completion: superposition + inter-reduction during rebuild.
4//!
5//! This implements the completion machinery intended to recover AC congruence
6//! consequences that canonization alone cannot provide: recanonicalizing an AC
7//! node substitutes equal *atoms* but never equal *sub-sums*, so equalities like
8//! `+(a,b)=c ∧ +(b,d)=e ⊨ +(c,d)=+(a,e)` are otherwise missed. The code-to-paper
9//! correspondence is tested on finite fixtures, but an end-to-end completeness
10//! theorem for this implementation remains open. See
11//! `doc/design/ac-congruence-completeness.md` for the theory and
12//! `doc/design/ac-completion-spec.md` for the engine-level spec.
13//!
14//! This file contains the representation-agnostic per-round snapshot used by
15//! completion diagnostics and conformance tests. The completion round itself
16//! lives in `egraph.rs::cc_round` and finds partners through class use-lists.
17//! The snapshot must cover both MSet and Set nodes to agree with
18//! `completion_node_ids` semantics.
19
20use crate::canon::{MSetCanon, VarCanon};
21use crate::config::EGraphConfig;
22use crate::egraph::EGraph;
23use crate::literal::LitVal;
24use std::collections::HashMap;
25
26/// Same rationale as `index::FastMap`: `(op, child_repr)` keys are internal
27/// dense ids, so SipHash's collision resistance buys nothing here.
28type FastMap<K, V> = HashMap<K, V, foldhash::fast::RandomState>;
29
30/// A per-round search index over the live AC nodes, restricted to AC ops.
31///
32/// This is the narrow slice of [`crate::index::IndexStore`] that the completion
33/// search needs: the spec's candidate set `⋃_{x ∈ distinct(M)} by_contains[x] ∩
34/// by_op[f]`. We pre-intersect with `by_op[f]` by keying on
35/// `(op, child_repr)`, so a lookup directly yields the AC nodes of op `f` that
36/// contain child class `x` — no separate `by_op` intersection at use time.
37///
38/// Unlike `IndexStore`, this diagnostic index covers only AC ops and carries no
39/// `by_repr`/`by_child_pos`. Production completion currently finds candidates
40/// through class use-lists instead. Subsumed nodes are skipped, matching
41/// `IndexStore`.
42///
43/// Node ids in each bucket are sorted and deduplicated.
44pub struct CcSnapshot<Cfg: EGraphConfig> {
45    /// `(op, child_repr) → sorted, deduped AC node ids of that op containing the child`.
46    by_op_contains: FastMap<(Cfg::O, Cfg::G), Vec<Cfg::G>>,
47    /// All live (non-subsumed) AC node ids, sorted — the set of completion targets/rules.
48    completion_nodes: Vec<Cfg::G>,
49}
50
51impl<Cfg: EGraphConfig> CcSnapshot<Cfg>
52where
53    MSetCanon: VarCanon<Cfg::G, Cfg::C>,
54{
55    /// Build the snapshot from the current e-graph state. Walks every node once,
56    /// keeping only AC nodes (`ops.is_mset`), skipping subsumed nodes.
57    pub fn build<L: LitVal, const TRACK: bool, const PROOFS: bool>(
58        eg: &EGraph<Cfg, L, TRACK, PROOFS>,
59    ) -> Self {
60        let mut by_op_contains: FastMap<(Cfg::O, Cfg::G), Vec<Cfg::G>> = FastMap::default();
61        let mut completion_nodes: Vec<Cfg::G> = Vec::new();
62
63        // Active completion nodes only: skip user-subsumed (not matchable) and AC-collapsed
64        // (reducible by a smaller rule) — neither is a completion rule. See §6b. Both
65        // completion partitions are covered: MSet (plain AC / nilpotent) and Set (ACI).
66        let inactive = crate::node_types::FLAG_SUBSUMED | crate::node_types::FLAG_AC_COLLAPSED;
67        for gid in eg.node_ids() {
68            if eg.node_flags(gid) & inactive != 0 {
69                continue;
70            }
71            let op = eg.node_op(gid);
72            if !eg.ops().is_mset(op) && !eg.ops().is_set(op) {
73                continue;
74            }
75            completion_nodes.push(gid);
76
77            // Bucket this node under each distinct child class it contains.
78            let mut seen: Vec<Cfg::G> = Vec::new();
79            eg.for_each_child(gid, |child, _mult| {
80                let cr = eg.class_repr(child);
81                if !seen.contains(&cr) {
82                    seen.push(cr);
83                    by_op_contains.entry((op, cr)).or_default().push(gid);
84                }
85            });
86        }
87
88        for v in by_op_contains.values_mut() {
89            v.sort_unstable();
90            v.dedup();
91        }
92        completion_nodes.sort_unstable();
93        completion_nodes.dedup();
94
95        Self {
96            by_op_contains,
97            completion_nodes,
98        }
99    }
100
101    /// All live AC node ids (sorted). These are the completion targets — each is
102    /// both a node `+M = d` to complete and a rule `+M → d` to complete against.
103    pub fn completion_nodes(&self) -> &[Cfg::G] {
104        &self.completion_nodes
105    }
106
107    /// AC nodes of op `op` that contain child class `child_repr` (sorted, deduped).
108    /// This is the spec's `by_contains[child_repr] ∩ by_op[op]`, pre-intersected.
109    pub fn partners(&self, op: Cfg::O, child_repr: Cfg::G) -> &[Cfg::G] {
110        self.by_op_contains
111            .get(&(op, child_repr))
112            .map(|v| v.as_slice())
113            .unwrap_or(&[])
114    }
115}
116
117#[cfg(test)]
118mod tests {
119    use super::*;
120    use crate::egraph::EGraph31;
121    use crate::literal::NiraLitVal;
122
123    /// Brute-force reference: AC nodes of `op` whose `mset_children` contain `cr`.
124    fn ref_partners(
125        eg: &EGraph31<NiraLitVal, false, false>,
126        op: crate::id::OpId,
127        cr: crate::id::ENodeId,
128    ) -> Vec<crate::id::ENodeId> {
129        let mut out = Vec::new();
130        let mut buf = Vec::new();
131        let inactive = crate::node_types::FLAG_SUBSUMED | crate::node_types::FLAG_AC_COLLAPSED;
132        for i in 0..eg.node_count() {
133            let gid = crate::id::ENodeId::new(i as u32);
134            if eg.node_flags(gid) & inactive != 0 {
135                continue;
136            }
137            if eg.node_op(gid) != op || !(eg.ops().is_mset(op) || eg.ops().is_set(op)) {
138                continue;
139            }
140            buf.clear();
141            eg.for_each_child(gid, |c, m| buf.push((c, m)));
142            if buf.iter().any(|&(c, _)| eg.class_repr(c) == cr) {
143                out.push(gid);
144            }
145        }
146        out.sort_unstable();
147        out.dedup();
148        out
149    }
150
151    #[test]
152    fn snapshot_matches_by_contains_variadic_fixture() {
153        // Mirror of index.rs `by_contains_variadic`, but through the AC snapshot.
154        let mut eg = EGraph31::<NiraLitVal, false, false>::new();
155        let int = eg.intern_sort("Int");
156        let plus = eg.register_mset("plus", int, int);
157        let x_op = eg.register_op0("x", int);
158        let y_op = eg.register_op0("y", int);
159        let z_op = eg.register_op0("z", int);
160
161        let x = eg.add(x_op, &[]);
162        let y = eg.add(y_op, &[]);
163        let z = eg.add(z_op, &[]);
164        let pxy = eg.add(plus, &[x, y]);
165        let pxz = eg.add(plus, &[x, z]);
166
167        let snap = CcSnapshot::build(&eg);
168
169        // x is contained in both pxy and pxz.
170        let mut cx = snap.partners(plus, x).to_vec();
171        cx.sort_unstable();
172        assert_eq!(cx, vec![pxy.min(pxz), pxy.max(pxz)]);
173
174        // y is contained only in pxy.
175        assert_eq!(snap.partners(plus, y), &[pxy]);
176
177        // completion_nodes lists exactly the two AC sums (not the op0 leaves).
178        assert_eq!(snap.completion_nodes(), &[pxy.min(pxz), pxy.max(pxz)]);
179    }
180
181    #[test]
182    fn snapshot_only_indexes_ac_ops() {
183        let mut eg = EGraph31::<NiraLitVal, false, false>::new();
184        let int = eg.intern_sort("Int");
185        let plus = eg.register_mset("plus", int, int);
186        let f = eg.register_op1("f", int, int); // Normal — must not appear
187        let x_op = eg.register_op0("x", int);
188
189        let x = eg.add(x_op, &[]);
190        let fx = eg.add(f, &[x]);
191        let pfx = eg.add(plus, &[x, fx]);
192
193        let snap = CcSnapshot::build(&eg);
194
195        // Only the AC node is a completion target.
196        assert_eq!(snap.completion_nodes(), &[pfx]);
197        // The plain node f(x) is not bucketed even though it contains x.
198        assert!(snap.partners(f, eg.class_repr(x)).is_empty());
199        // The AC sum is found under both its children.
200        assert_eq!(snap.partners(plus, eg.class_repr(x)), &[pfx]);
201        assert_eq!(snap.partners(plus, eg.class_repr(fx)), &[pfx]);
202    }
203
204    #[test]
205    fn snapshot_agrees_with_brute_force_after_merge() {
206        // Multiplicities + a merge that changes class reprs.
207        let mut eg = EGraph31::<NiraLitVal, false, false>::new();
208        let int = eg.intern_sort("Int");
209        let plus = eg.register_mset("plus", int, int);
210        let a_op = eg.register_op0("a", int);
211        let b_op = eg.register_op0("b", int);
212        let d_op = eg.register_op0("d", int);
213
214        let a = eg.add(a_op, &[]);
215        let b = eg.add(b_op, &[]);
216        let d = eg.add(d_op, &[]);
217        let _ab = eg.add(plus, &[a, b]);
218        let _bd = eg.add(plus, &[b, d]);
219        let _abb = eg.add(plus, &[a, b, b]); // multiplicity > 1 on b
220
221        // Merge a and d, then rebuild so reprs settle.
222        eg.merge(a, d);
223        eg.rebuild();
224
225        let snap = CcSnapshot::build(&eg);
226
227        // For every (AC op, child class) the snapshot must equal the brute-force set.
228        for x in [a, b, d] {
229            let cr = eg.class_repr(x);
230            let mut got = snap.partners(plus, cr).to_vec();
231            got.sort_unstable();
232            assert_eq!(
233                got,
234                ref_partners(&eg, plus, cr),
235                "mismatch for child {cr:?}"
236            );
237        }
238    }
239
240    #[test]
241    fn cc_collapsed_leaves_completion_set_but_stays_matchable() {
242        // FLAG_AC_COLLAPSED and FLAG_SUBSUMED are distinct (design §6b): a collapsed node
243        // drops out of completion's active set but remains visible to the matcher's index.
244        use crate::index::IndexStore;
245        let mut eg = EGraph31::<NiraLitVal, false, false>::new();
246        let int = eg.intern_sort("Int");
247        let plus = eg.register_mset("plus", int, int);
248        let a_op = eg.register_op0("a", int);
249        let b_op = eg.register_op0("b", int);
250        let a = eg.add(a_op, &[]);
251        let b = eg.add(b_op, &[]);
252        let pab = eg.add(plus, &[a, b]);
253
254        // Baseline: pab is both a completion candidate and in the matcher index.
255        assert_eq!(CcSnapshot::build(&eg).completion_nodes(), &[pab]);
256        assert!(IndexStore::build(&eg).nodes_by_op(plus).contains(&pab));
257
258        // Collapse it (the completion-internal retirement).
259        eg.set_cc_collapsed(pab);
260
261        // Gone from completion's active set...
262        assert!(
263            CcSnapshot::build(&eg).completion_nodes().is_empty(),
264            "AC-collapsed node must leave the completion active set"
265        );
266        // ...but still matchable: present in the index and still in its class.
267        assert!(
268            IndexStore::build(&eg).nodes_by_op(plus).contains(&pab),
269            "AC-collapsed node must stay visible to the matcher (not subsumed)"
270        );
271        assert_eq!(eg.class_repr(pab), eg.class_repr(pab));
272
273        // Contrast: user subsume DOES hide it from the matcher.
274        eg.subsume(pab);
275        assert!(
276            !IndexStore::build(&eg).nodes_by_op(plus).contains(&pab),
277            "subsumed node must be hidden from the matcher index"
278        );
279    }
280}