Skip to main content

semi_persistent_egraph/au/
actions.rs

1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// SPDX-License-Identifier: Apache-2.0
3//! Action generation per node kind (§3.4).
4//!
5//! For a class pair `(l, r)`, structural actions are the ways to factor both classes
6//! through a common operator. Every unequal state also has the shared terminal
7//! generalize action `Variants(best_term(l), best_term(r))`, evaluated by
8//! `terms::evaluate_generalize_action`. It is not cached here because it has no
9//! operator or child subproblems. Structural results are cached by `(l, r)` and
10//! shared across contexts; cycle filtering happens at the OR node level.
11
12use crate::canon::{MSetCanon, VarCanon};
13use crate::config::EGraphConfig;
14use crate::containers::{DenseId, MapToken, ShrinkPolicy, SpMap};
15use crate::egraph::EGraph;
16use crate::id::ENodeKind;
17use crate::literal::LitVal;
18use crate::multiplicity::{Multiplicity, MultiplicityLike};
19
20use super::AuIds31;
21use super::egraph_api::{AuSnapshot, ClassOf};
22use crate::config::AuIds;
23
24/// One structural action: an operator plus its paired children with multiplicities.
25#[derive(Debug)]
26pub struct Action<O: DenseId, A: AuIds = AuIds31, M: MultiplicityLike = Multiplicity> {
27    pub op: O,
28    pub pairs: Vec<ActionPair<A, M>>,
29}
30
31// Manual impls: derives would demand `A: Clone`, but `A` is a family marker.
32impl<O: DenseId, A: AuIds, M: MultiplicityLike> Clone for Action<O, A, M> {
33    fn clone(&self) -> Self {
34        Action {
35            op: self.op,
36            pairs: self.pairs.clone(),
37        }
38    }
39}
40
41/// A single child-pair in an action. `count` is the multiplicity (>1 for AC repeated children).
42///
43/// `count` is at the configured multiplicity width [`EGraphConfig::M`], not a fixed `u32`.
44/// It is a copy of an AC child multiplicity — or, in the matrix enumerator, a sum of
45/// several — so `Cfg::M` is the width it already has, and the previous hardcoded `u32`
46/// meant a *narrowing* on the way in. At `Multiplicity64` that narrowing dropped members
47/// whose multiplicity the e-graph represents fine: a completeness loss with no upside,
48/// since the enumerator's arithmetic is checked at whatever width it runs.
49///
50/// This is not a space argument in either direction. At 4-byte class ids a 2-byte count
51/// pads to the same 12-byte pair as a 4-byte one, and at 8-byte ids every width pads to
52/// 24 — the same padding fact `multiplicity_width_is_free_at_the_wide_id_width` records
53/// for AC children. Every shipped config is byte-for-byte unchanged by this parameter;
54/// what it buys is that the field cannot cap a width the e-graph supports.
55///
56/// [`EGraphConfig::M`]: crate::config::EGraphConfig::M
57#[derive(Debug)]
58pub struct ActionPair<A: AuIds = AuIds31, M: MultiplicityLike = Multiplicity> {
59    pub left: A::Class,
60    pub right: A::Class,
61    pub count: M,
62}
63
64impl<A: AuIds, M: MultiplicityLike> Clone for ActionPair<A, M> {
65    fn clone(&self) -> Self {
66        *self
67    }
68}
69impl<A: AuIds, M: MultiplicityLike> Copy for ActionPair<A, M> {}
70impl<A: AuIds, M: MultiplicityLike> PartialEq for ActionPair<A, M> {
71    fn eq(&self, other: &Self) -> bool {
72        self.left == other.left && self.right == other.right && self.count == other.count
73    }
74}
75impl<A: AuIds, M: MultiplicityLike> Eq for ActionPair<A, M> {}
76
77/// Default maximum number of AC matrices to materialize before using lazy chain states.
78pub const DEFAULT_A_MAX: usize = 32;
79
80/// The action cache: maps class pair `(l, r)` to a list of actions.
81/// Semi-persistent: the `index` map (AppendOnlyVec + SpMap) is append-only and
82/// provides branch genealogy for tokens. The `values` vec grows in lockstep
83/// and is truncated on restore. Actions are deterministic from the immutable
84/// snapshot, so re-derivation after restore is cheap (cache is a performance
85/// optimization, not a correctness requirement).
86pub struct ActionCache<O: DenseId, A: AuIds = AuIds31, M: MultiplicityLike = Multiplicity> {
87    /// Deduplication map: (l, r) -> typed action-list id into `values`.
88    ///
89    /// Index word `A::Index`: the map's log positions are what the `A::Action`s are
90    /// minted from, and `A::Action::Index` is that word.
91    index: SpMap<(A::Class, A::Class), A::Action, A::Index>,
92    /// Action lists, indexed by the map's stored value.
93    values: Vec<Vec<Action<O, A, M>>>,
94    a_max: usize,
95    include_ac: bool,
96}
97
98/// Token for restoring an `ActionCache`. Wraps the SpMap's token, which
99/// carries container identity and branch genealogy.
100#[derive(Clone, Copy, Debug)]
101pub struct ActionCacheToken {
102    index: MapToken,
103    values_len: usize,
104}
105
106impl<O: DenseId, A: AuIds, M: MultiplicityLike> ActionCache<O, A, M> {
107    pub fn new(a_max: usize) -> Self {
108        ActionCache {
109            index: SpMap::new(),
110            values: Vec::new(),
111            a_max,
112            include_ac: true,
113        }
114    }
115
116    /// A cache whose `generate_actions` skips AC/ACI matrix materialization.
117    /// Used by the exact solver, which handles those operators by transport.
118    pub fn without_ac_actions(a_max: usize) -> Self {
119        ActionCache {
120            index: SpMap::new(),
121            values: Vec::new(),
122            a_max,
123            include_ac: false,
124        }
125    }
126
127    pub fn include_ac(&self) -> bool {
128        self.include_ac
129    }
130
131    pub fn get(&self, l: A::Class, r: A::Class) -> Option<&[Action<O, A, M>]> {
132        let key = (l, r);
133        self.index.id_of(&key).map(|log_idx| {
134            let &idx = self.index.get_val(log_idx);
135            self.values[idx.to_usize()].as_slice()
136        })
137    }
138
139    pub fn insert(&mut self, l: A::Class, r: A::Class, actions: Vec<Action<O, A, M>>) {
140        // Checked: `values` is a plain `Vec`, so nothing but this call stands between the
141        // action-list count and the `A::Action` id space. Masking would hand the new list
142        // the id of an older one, and `get` would then serve the wrong action list for a
143        // class pair — a search that expands moves belonging to a different subproblem.
144        let idx = crate::id::id_at::<A::Action>(self.values.len());
145        self.values.push(actions);
146        self.index
147            .try_insert((l, r), idx)
148            .expect("AU arena sized by its index word");
149    }
150
151    pub fn a_max(&self) -> usize {
152        self.a_max
153    }
154
155    pub fn mark(&mut self) -> ActionCacheToken {
156        ActionCacheToken {
157            index: self
158                .index
159                .try_mark(ShrinkPolicy::Never)
160                .expect("mark: depth bounded by the search driver"),
161            values_len: self.values.len(),
162        }
163    }
164
165    /// Is this token restorable right now (same instance, live branch)?
166    pub fn is_valid_token(&self, token: &ActionCacheToken) -> bool {
167        self.index.is_valid_token(&token.index)
168    }
169
170    pub fn restore(&mut self, token: ActionCacheToken) {
171        self.index
172            .try_restore(token.index)
173            .expect("restore: token minted by this container's own mark");
174        self.values.truncate(token.values_len);
175    }
176}
177
178impl<O: DenseId, A: AuIds, M: MultiplicityLike> Default for ActionCache<O, A, M> {
179    fn default() -> Self {
180        Self::new(DEFAULT_A_MAX)
181    }
182}
183
184/// Generate all actions for a class pair `(l, r)` by scanning their common operators.
185/// Actions are NOT cycle-filtered here; that is done at the OR-node level.
186pub fn generate_actions<Cfg: EGraphConfig, L: LitVal, const T: bool, const P: bool>(
187    snap: &AuSnapshot<Cfg, L, T, P>,
188    cache: &mut ActionCache<Cfg::O, Cfg::Au, Cfg::M>,
189    l: ClassOf<Cfg>,
190    r: ClassOf<Cfg>,
191) where
192    MSetCanon: VarCanon<Cfg::G, Cfg::C>,
193{
194    if cache.get(l, r).is_some() {
195        return;
196    }
197
198    let eg = snap.egraph();
199    let members_l = snap.members(l);
200    let members_r = snap.members(r);
201    let a_max = cache.a_max();
202    let include_ac = cache.include_ac();
203
204    let mut actions: Vec<Action<Cfg::O, Cfg::Au, Cfg::M>> = Vec::new();
205
206    // Group members by op (they are already sorted by op).
207    let mut il = 0;
208    let mut ir = 0;
209
210    while il < members_l.len() && ir < members_r.len() {
211        let (op_l, _) = members_l[il];
212        let (op_r, _) = members_r[ir];
213
214        match op_l.to_usize().cmp(&op_r.to_usize()) {
215            std::cmp::Ordering::Less => {
216                // Advance l past this op.
217                while il < members_l.len() && members_l[il].0 == op_l {
218                    il += 1;
219                }
220            }
221            std::cmp::Ordering::Greater => {
222                // Advance r past this op.
223                while ir < members_r.len() && members_r[ir].0 == op_r {
224                    ir += 1;
225                }
226            }
227            std::cmp::Ordering::Equal => {
228                // Common operator: collect all l-members and r-members with this op.
229                let il_start = il;
230                while il < members_l.len() && members_l[il].0 == op_l {
231                    il += 1;
232                }
233                let ir_start = ir;
234                while ir < members_r.len() && members_r[ir].0 == op_r {
235                    ir += 1;
236                }
237
238                let l_nodes = &members_l[il_start..il];
239                let r_nodes = &members_r[ir_start..ir];
240
241                let kind = eg.ops().info(op_l).canon_class();
242                match kind {
243                    ENodeKind::Plain0 => {
244                        // Nullary: one action with no children (the op itself matches).
245                        actions.push(Action {
246                            op: op_l,
247                            pairs: Vec::new(),
248                        });
249                    }
250                    ENodeKind::Plain1
251                    | ENodeKind::Plain2
252                    | ENodeKind::Plain3
253                    | ENodeKind::PlainN => {
254                        generate_ordered_actions(snap, eg, op_l, l_nodes, r_nodes, &mut actions);
255                    }
256                    ENodeKind::Seq => {
257                        generate_seq_actions(snap, eg, op_l, l_nodes, r_nodes, &mut actions);
258                    }
259                    ENodeKind::SPair => {
260                        generate_spair_actions(snap, eg, op_l, l_nodes, r_nodes, &mut actions);
261                    }
262                    ENodeKind::MSet => {
263                        if include_ac {
264                            generate_mset_actions(
265                                snap,
266                                eg,
267                                op_l,
268                                l_nodes,
269                                r_nodes,
270                                a_max,
271                                &mut actions,
272                            );
273                        }
274                    }
275                    ENodeKind::Set => {
276                        if include_ac {
277                            generate_set_actions(
278                                snap,
279                                eg,
280                                op_l,
281                                l_nodes,
282                                r_nodes,
283                                a_max,
284                                &mut actions,
285                            );
286                        }
287                    }
288                    ENodeKind::Lit => {
289                        generate_lit_actions(eg, op_l, l_nodes, r_nodes, &mut actions);
290                    }
291                }
292            }
293        }
294    }
295
296    // Identity expansion for singleton-canonized classes: if one side has AC/ACI
297    // members for an op with identity and the other side does not (because the
298    // e-graph canonized a single-child application to the bare child), generate
299    // actions by treating the bare side as the singleton monomial {class^1}.
300    if !include_ac {
301        // The exact solver handles all AC/ACI pairs (including identity
302        // expansion) through the transport path; skip materialization.
303        dedup_and_insert(cache, l, r, actions);
304        return;
305    }
306    for &(op_id, _) in members_l.iter() {
307        let kind = eg.ops().info(op_id).canon_class();
308        if !matches!(kind, ENodeKind::MSet | ENodeKind::Set) {
309            continue;
310        }
311        let identity = snap.op_identity_class(op_id);
312        if identity.is_none() {
313            continue;
314        }
315        // Check if the right side has no members with this op.
316        let r_has_op = members_r.iter().any(|&(o, _)| o == op_id);
317        if r_has_op {
318            continue;
319        }
320        // Treat right as singleton monomial {r^1}, left as its AC members.
321        let l_op_members: Vec<(Cfg::O, Cfg::G)> = members_l
322            .iter()
323            .filter(|&&(o, _)| o == op_id)
324            .copied()
325            .collect();
326        if kind == ENodeKind::Set {
327            // ACI: right is a singleton set {r}.
328            let r_children = vec![(r, Cfg::M::ONE)];
329            for &(_, l_id) in &l_op_members {
330                let mut l_children: Vec<ClassOf<Cfg>> = Vec::new();
331                eg.for_each_child(l_id, |child, _| {
332                    l_children.push(snap.class_of(child).unwrap());
333                });
334                let mut l_classes: Vec<(ClassOf<Cfg>, Cfg::M)> =
335                    l_children.iter().map(|&c| (c, Cfg::M::ONE)).collect();
336                let id_class = identity.unwrap();
337                // A set member's cardinality is bounded by `for_each_child`'s
338                // 64·node_count cap, which exceeds `Count` for a wide config, so
339                // even these all-ones totals are summed with overflow detection.
340                let (Some(r_total), Some(l_total)) =
341                    (counts_total(&r_children), counts_total(&l_classes))
342                else {
343                    continue;
344                };
345                let mut r_padded = r_children.clone();
346                if l_total > r_total {
347                    r_padded.push((id_class, l_total.saturating_sub(r_total)));
348                } else if r_total > l_total
349                    && pad_identity(&mut l_classes, id_class, r_total.saturating_sub(l_total))
350                        .is_none()
351                {
352                    continue;
353                }
354                enumerate_matrices(op_id, &l_classes, &r_padded, a_max, &mut actions);
355            }
356        } else {
357            // AC (MSet): right is singleton {r^1}.
358            let mut l_mset_buf: Vec<(Cfg::G, Cfg::M)> = Vec::new();
359            for &(_, l_id) in &l_op_members {
360                eg.mset_children(l_id, &mut l_mset_buf);
361                let Some((l_classes, l_total)) = mset_counts(snap, &l_mset_buf) else {
362                    continue;
363                };
364                let id_class = identity.unwrap();
365                let mut r_classes = vec![(r, Cfg::M::ONE)];
366                if l_total > Cfg::M::ONE {
367                    r_classes.push((id_class, l_total.saturating_sub(Cfg::M::ONE)));
368                }
369                enumerate_matrices(op_id, &l_classes, &r_classes, a_max, &mut actions);
370            }
371        }
372    }
373    // Symmetric: right has the op, left does not.
374    for &(op_id, _) in members_r.iter() {
375        let kind = eg.ops().info(op_id).canon_class();
376        if !matches!(kind, ENodeKind::MSet | ENodeKind::Set) {
377            continue;
378        }
379        let identity = snap.op_identity_class(op_id);
380        if identity.is_none() {
381            continue;
382        }
383        let l_has_op = members_l.iter().any(|&(o, _)| o == op_id);
384        if l_has_op {
385            continue;
386        }
387        let r_op_members: Vec<(Cfg::O, Cfg::G)> = members_r
388            .iter()
389            .filter(|&&(o, _)| o == op_id)
390            .copied()
391            .collect();
392        if kind == ENodeKind::Set {
393            let l_children = vec![(l, Cfg::M::ONE)];
394            for &(_, r_id) in &r_op_members {
395                let mut r_children: Vec<ClassOf<Cfg>> = Vec::new();
396                eg.for_each_child(r_id, |child, _| {
397                    r_children.push(snap.class_of(child).unwrap());
398                });
399                let mut r_classes: Vec<(ClassOf<Cfg>, Cfg::M)> =
400                    r_children.iter().map(|&c| (c, Cfg::M::ONE)).collect();
401                let id_class = identity.unwrap();
402                // See the mirrored branch above on why these are checked.
403                let (Some(r_total), Some(l_total)) =
404                    (counts_total(&r_classes), counts_total(&l_children))
405                else {
406                    continue;
407                };
408                let mut l_padded = l_children.clone();
409                if r_total > l_total {
410                    l_padded.push((id_class, r_total.saturating_sub(l_total)));
411                } else if l_total > r_total
412                    && pad_identity(&mut r_classes, id_class, l_total.saturating_sub(r_total))
413                        .is_none()
414                {
415                    continue;
416                }
417                enumerate_matrices(op_id, &l_padded, &r_classes, a_max, &mut actions);
418            }
419        } else {
420            let mut r_mset_buf: Vec<(Cfg::G, Cfg::M)> = Vec::new();
421            for &(_, r_id) in &r_op_members {
422                eg.mset_children(r_id, &mut r_mset_buf);
423                let Some((r_classes, r_total)) = mset_counts(snap, &r_mset_buf) else {
424                    continue;
425                };
426                let id_class = identity.unwrap();
427                let mut l_classes = vec![(l, Cfg::M::ONE)];
428                if r_total > Cfg::M::ONE {
429                    l_classes.push((id_class, r_total.saturating_sub(Cfg::M::ONE)));
430                }
431                enumerate_matrices(op_id, &l_classes, &r_classes, a_max, &mut actions);
432            }
433        }
434    }
435
436    dedup_and_insert(cache, l, r, actions);
437}
438
439/// Deduplicate actions by operator plus canonical (left, right, count)
440/// signature and insert into the cache. Rewrite-derived equivalent members can produce identical
441/// actions from different (l_node, r_node) pairs; duplicates would surface as
442/// separate statistics edges and bias MCGS selection toward the duplicated
443/// action.
444fn dedup_and_insert<O: DenseId, A: AuIds, M: MultiplicityLike>(
445    cache: &mut ActionCache<O, A, M>,
446    l: A::Class,
447    r: A::Class,
448    mut actions: Vec<Action<O, A, M>>,
449) {
450    // The signature holds the pair's own types. Widening the two class ids to `usize` to
451    // key a hash set bought nothing — dense ids are already `Hash + Ord` — and cost real
452    // bytes in a set that is rebuilt for every class pair the search visits: at the 31-bit
453    // family a `(usize, usize, u32)` entry is 24 bytes to this tuple's 12, because the two
454    // widened words also raise the tuple's alignment and so its tail padding.
455    // The operator is part of the signature: two operators can witness the same
456    // child pairing (distinct merged heads over shared children), and both
457    // actions must survive so either operator can head the reported
458    // generalization. The dedup collapses same-operator duplicates only.
459    let mut seen: hashbrown::HashSet<(O, Vec<(A::Class, A::Class, M)>)> = hashbrown::HashSet::new();
460    actions.retain(|action| {
461        let mut sig: Vec<(A::Class, A::Class, M)> = action
462            .pairs
463            .iter()
464            .map(|p| (p.left, p.right, p.count))
465            .collect();
466        sig.sort_unstable();
467        seen.insert((action.op, sig))
468    });
469    cache.insert(l, r, actions);
470}
471
472/// Ordered operators (fixed arity): positional zip of same-arity member pairs (§3.4.1).
473fn generate_ordered_actions<Cfg: EGraphConfig, L: LitVal, const T: bool, const P: bool>(
474    snap: &AuSnapshot<Cfg, L, T, P>,
475    eg: &EGraph<Cfg, L, T, P>,
476    op: Cfg::O,
477    l_nodes: &[(Cfg::O, Cfg::G)],
478    r_nodes: &[(Cfg::O, Cfg::G)],
479    actions: &mut Vec<Action<Cfg::O, Cfg::Au, Cfg::M>>,
480) where
481    MSetCanon: VarCanon<Cfg::G, Cfg::C>,
482{
483    for &(_, l_id) in l_nodes {
484        let l_arity = eg.for_each_child(l_id, |_, _| {});
485        for &(_, r_id) in r_nodes {
486            let r_arity = eg.for_each_child(r_id, |_, _| {});
487            if l_arity != r_arity {
488                continue;
489            }
490            // Positional zip.
491            let mut pairs = Vec::with_capacity(l_arity);
492            let mut l_children = Vec::with_capacity(l_arity);
493            let mut r_children = Vec::with_capacity(r_arity);
494            eg.for_each_child(l_id, |child, _| l_children.push(child));
495            eg.for_each_child(r_id, |child, _| r_children.push(child));
496
497            for i in 0..l_arity {
498                let lc = snap.class_of(l_children[i]).unwrap();
499                let rc = snap.class_of(r_children[i]).unwrap();
500                pairs.push(ActionPair::<Cfg::Au, Cfg::M> {
501                    left: lc,
502                    right: rc,
503                    count: Cfg::M::ONE,
504                });
505            }
506            actions.push(Action { op, pairs });
507        }
508    }
509}
510
511/// Associative operators (sequences): one positional action when lengths
512/// are equal, none otherwise (§3.4.3). Unequal-length factoring is future work
513/// (doc/future/au-associative-operators.md).
514fn generate_seq_actions<Cfg: EGraphConfig, L: LitVal, const T: bool, const P: bool>(
515    snap: &AuSnapshot<Cfg, L, T, P>,
516    eg: &EGraph<Cfg, L, T, P>,
517    op: Cfg::O,
518    l_nodes: &[(Cfg::O, Cfg::G)],
519    r_nodes: &[(Cfg::O, Cfg::G)],
520    actions: &mut Vec<Action<Cfg::O, Cfg::Au, Cfg::M>>,
521) where
522    MSetCanon: VarCanon<Cfg::G, Cfg::C>,
523{
524    // Same logic as ordered: positional zip only when lengths match.
525    generate_ordered_actions(snap, eg, op, l_nodes, r_nodes, actions);
526}
527
528/// Commutative binary operators (sorted pairs): up to two distinct orientations
529/// per member pair (§3.4.2), followed by whole-cache deduplication.
530fn generate_spair_actions<Cfg: EGraphConfig, L: LitVal, const T: bool, const P: bool>(
531    snap: &AuSnapshot<Cfg, L, T, P>,
532    eg: &EGraph<Cfg, L, T, P>,
533    op: Cfg::O,
534    l_nodes: &[(Cfg::O, Cfg::G)],
535    r_nodes: &[(Cfg::O, Cfg::G)],
536    actions: &mut Vec<Action<Cfg::O, Cfg::Au, Cfg::M>>,
537) where
538    MSetCanon: VarCanon<Cfg::G, Cfg::C>,
539{
540    for &(_, l_id) in l_nodes {
541        let mut l_children = [<ClassOf<Cfg>>::default(); 2];
542        let mut li = 0;
543        eg.for_each_child(l_id, |child, _| {
544            if li < 2 {
545                l_children[li] = snap.class_of(child).unwrap();
546                li += 1;
547            }
548        });
549
550        for &(_, r_id) in r_nodes {
551            let mut r_children = [<ClassOf<Cfg>>::default(); 2];
552            let mut ri = 0;
553            eg.for_each_child(r_id, |child, _| {
554                if ri < 2 {
555                    r_children[ri] = snap.class_of(child).unwrap();
556                    ri += 1;
557                }
558            });
559
560            // Orientation 1: positional (a,c), (b,d).
561            let pairs1 = vec![
562                ActionPair::<Cfg::Au, Cfg::M> {
563                    left: l_children[0],
564                    right: r_children[0],
565                    count: Cfg::M::ONE,
566                },
567                ActionPair::<Cfg::Au, Cfg::M> {
568                    left: l_children[1],
569                    right: r_children[1],
570                    count: Cfg::M::ONE,
571                },
572            ];
573            actions.push(Action { op, pairs: pairs1 });
574
575            // Orientation 2: crossed (a,d), (b,c) — skip if same as orientation 1.
576            if !(l_children[0] == l_children[1] || r_children[0] == r_children[1]) {
577                let pairs2 = vec![
578                    ActionPair::<Cfg::Au, Cfg::M> {
579                        left: l_children[0],
580                        right: r_children[1],
581                        count: Cfg::M::ONE,
582                    },
583                    ActionPair::<Cfg::Au, Cfg::M> {
584                        left: l_children[1],
585                        right: r_children[0],
586                        count: Cfg::M::ONE,
587                    },
588                ];
589                actions.push(Action { op, pairs: pairs2 });
590            }
591        }
592    }
593}
594
595/// AC operators (multisets): bounded matrix enumeration, used only by the
596/// differential test oracle — both production paths use min-cost transport (§3.4.4).
597/// When totals are unequal and the operator has a declared identity element, the
598/// shorter side is padded with identity copies to equalize the totals; the resulting
599/// anti-unifier pairs unmatched elements against the identity (producing
600/// `Variants(element, identity)` at those positions).
601fn generate_mset_actions<Cfg: EGraphConfig, L: LitVal, const T: bool, const P: bool>(
602    snap: &AuSnapshot<Cfg, L, T, P>,
603    eg: &EGraph<Cfg, L, T, P>,
604    op: Cfg::O,
605    l_nodes: &[(Cfg::O, Cfg::G)],
606    r_nodes: &[(Cfg::O, Cfg::G)],
607    a_max: usize,
608    actions: &mut Vec<Action<Cfg::O, Cfg::Au, Cfg::M>>,
609) where
610    MSetCanon: VarCanon<Cfg::G, Cfg::C>,
611{
612    let identity_class = snap.op_identity_class(op);
613    let mut l_mset_buf: Vec<(Cfg::G, Cfg::M)> = Vec::new();
614    let mut r_mset_buf: Vec<(Cfg::G, Cfg::M)> = Vec::new();
615
616    for &(_, l_id) in l_nodes {
617        eg.mset_children(l_id, &mut l_mset_buf);
618        // Counts and total come from one checked read, so they cannot disagree.
619        let Some((l_read, l_total)) = mset_counts(snap, &l_mset_buf) else {
620            continue;
621        };
622
623        for &(_, r_id) in r_nodes {
624            eg.mset_children(r_id, &mut r_mset_buf);
625            let Some((r_read, r_total)) = mset_counts(snap, &r_mset_buf) else {
626                continue;
627            };
628
629            let mut l_classes = l_read.clone();
630            let mut r_classes = r_read;
631
632            if l_total != r_total {
633                // Pad the shorter side with identity copies if available.
634                let Some(id_class) = identity_class else {
635                    continue;
636                };
637                let padded = if l_total < r_total {
638                    pad_identity(&mut l_classes, id_class, r_total.saturating_sub(l_total))
639                } else {
640                    pad_identity(&mut r_classes, id_class, l_total.saturating_sub(r_total))
641                };
642                if padded.is_none() {
643                    continue;
644                }
645            }
646
647            enumerate_matrices(op, &l_classes, &r_classes, a_max, actions);
648        }
649    }
650}
651
652/// ACI operators (sets): bijection enumeration (§3.4.5). When cardinalities
653/// differ and the operator has a declared identity, the shorter side is padded
654/// with identity elements to equalize; unmatched elements pair against the
655/// identity (producing `Variants(element, identity)`).
656fn generate_set_actions<Cfg: EGraphConfig, L: LitVal, const T: bool, const P: bool>(
657    snap: &AuSnapshot<Cfg, L, T, P>,
658    eg: &EGraph<Cfg, L, T, P>,
659    op: Cfg::O,
660    l_nodes: &[(Cfg::O, Cfg::G)],
661    r_nodes: &[(Cfg::O, Cfg::G)],
662    a_max: usize,
663    actions: &mut Vec<Action<Cfg::O, Cfg::Au, Cfg::M>>,
664) where
665    MSetCanon: VarCanon<Cfg::G, Cfg::C>,
666{
667    let identity_class = snap.op_identity_class(op);
668
669    for &(_, l_id) in l_nodes {
670        let mut l_children: Vec<ClassOf<Cfg>> = Vec::new();
671        eg.for_each_child(l_id, |child, _| {
672            l_children.push(snap.class_of(child).unwrap());
673        });
674
675        for &(_, r_id) in r_nodes {
676            let mut r_children: Vec<ClassOf<Cfg>> = Vec::new();
677            eg.for_each_child(r_id, |child, _| {
678                r_children.push(snap.class_of(child).unwrap());
679            });
680
681            if l_children.len() != r_children.len() {
682                let Some(id_class) = identity_class else {
683                    continue;
684                };
685                // Pad the shorter side with identity elements.
686                while l_children.len() < r_children.len() {
687                    l_children.push(id_class);
688                }
689                while r_children.len() < l_children.len() {
690                    r_children.push(id_class);
691                }
692            }
693
694            let l_classes: Vec<(ClassOf<Cfg>, Cfg::M)> =
695                l_children.iter().map(|&c| (c, Cfg::M::ONE)).collect();
696            let r_classes: Vec<(ClassOf<Cfg>, Cfg::M)> =
697                r_children.iter().map(|&c| (c, Cfg::M::ONE)).collect();
698
699            enumerate_matrices(op, &l_classes, &r_classes, a_max, actions);
700        }
701    }
702}
703
704/// Literals: same-value pairing only (§3.4.6).
705fn generate_lit_actions<Cfg: EGraphConfig, L: LitVal, const T: bool, const P: bool>(
706    eg: &EGraph<Cfg, L, T, P>,
707    op: Cfg::O,
708    l_nodes: &[(Cfg::O, Cfg::G)],
709    r_nodes: &[(Cfg::O, Cfg::G)],
710    actions: &mut Vec<Action<Cfg::O, Cfg::Au, Cfg::M>>,
711) where
712    MSetCanon: VarCanon<Cfg::G, Cfg::C>,
713{
714    for &(_, l_id) in l_nodes {
715        let l_val = eg.get_lit_val_id(l_id);
716        for &(_, r_id) in r_nodes {
717            let r_val = eg.get_lit_val_id(r_id);
718            if l_val == r_val {
719                // Terminal action with no children.
720                actions.push(Action {
721                    op,
722                    pairs: Vec::new(),
723                });
724            }
725        }
726    }
727}
728
729// ---------------------------------------------------------------------------
730// AC matrix enumeration
731// ---------------------------------------------------------------------------
732
733/// Read an AC member's child multiset into class counts, together with their total.
734///
735/// Reading the multiplicities is exact — they are already at the configured width — but
736/// the *total* is not: a sum of multiplicities can exceed the width one multiplicity fits
737/// in. `None` on that overflow, meaning "enumerate no actions from this member". Actions
738/// are candidate generalizations, so dropping one costs search completeness, never
739/// soundness — whereas a wrapped total would drive the enumerator over margins the
740/// e-graph's multiset does not have, and report the resulting term as a generalization of
741/// one it does.
742fn mset_counts<Cfg: EGraphConfig, L: LitVal, const T: bool, const P: bool>(
743    snap: &AuSnapshot<Cfg, L, T, P>,
744    buf: &[(Cfg::G, Cfg::M)],
745) -> Option<(Vec<(ClassOf<Cfg>, Cfg::M)>, Cfg::M)>
746where
747    MSetCanon: VarCanon<Cfg::G, Cfg::C>,
748{
749    let mut out: Vec<(ClassOf<Cfg>, Cfg::M)> = Vec::with_capacity(buf.len());
750    let mut total = Cfg::M::ZERO;
751    for (g, m) in buf {
752        out.push((snap.class_of(*g).unwrap(), *m));
753        total = total.checked_add(*m)?;
754    }
755    Some((out, total))
756}
757
758/// Sum of the counts, or `None` on overflow of the multiplicity width.
759fn counts_total<C, M: MultiplicityLike>(v: &[(C, M)]) -> Option<M> {
760    v.iter()
761        .try_fold(M::ZERO, |acc, (_, k)| acc.checked_add(*k))
762}
763
764/// Add `deficit` identity copies, merging into an existing identity entry so the
765/// vector stays duplicate-free. `None` on overflow of the multiplicity width.
766fn pad_identity<C: PartialEq, M: MultiplicityLike>(
767    v: &mut Vec<(C, M)>,
768    id_class: C,
769    deficit: M,
770) -> Option<()> {
771    match v.iter_mut().find(|(c, _)| *c == id_class) {
772        Some(entry) => entry.1 = entry.1.checked_add(deficit)?,
773        None => v.push((id_class, deficit)),
774    }
775    Some(())
776}
777
778/// Enumerate all valid matching-count matrices for multisets `M` and `N` with equal
779/// total multiplicity. A matrix X has `x[i][j]` copies of pair `(l_i, r_j)`;
780/// row i sums to `m_i`, column j sums to `n_j`.
781///
782/// Row-by-row distribution, complete and greedy-first (diagonal matches tried first).
783/// Used only as a differential test oracle — both production paths use min-cost
784/// transport instead. `a_max` bounds the number of emitted actions.
785///
786/// Margins, residuals and cells all carry the configured multiplicity width, the same
787/// width the input multisets came in at, so nothing here needs a narrowing check. The
788/// arithmetic that *can* leave the width is the summation the caller already did
789/// ([`counts_total`], [`pad_identity`], [`mset_counts`]); inside the recursion every
790/// value is bounded by a margin, so the subtractions are exact and the descending scans
791/// stay in range by construction.
792fn enumerate_matrices<O: DenseId, A: AuIds, M: MultiplicityLike>(
793    op: O,
794    l_classes: &[(A::Class, M)],
795    r_classes: &[(A::Class, M)],
796    a_max: usize,
797    actions: &mut Vec<Action<O, A, M>>,
798) {
799    let rows = l_classes.len();
800    let cols = r_classes.len();
801
802    if rows == 0 || cols == 0 {
803        return;
804    }
805
806    let row_sums: Vec<M> = l_classes.iter().map(|(_, m)| *m).collect();
807    let col_residual: Vec<M> = r_classes.iter().map(|(_, m)| *m).collect();
808    let mut matrix: Vec<Vec<M>> = vec![vec![M::ZERO; cols]; rows];
809    let mut count = 0;
810
811    enumerate_row(
812        op,
813        l_classes,
814        r_classes,
815        &row_sums,
816        &mut matrix,
817        0,
818        &mut col_residual.clone(),
819        a_max,
820        &mut count,
821        actions,
822    );
823}
824
825#[allow(clippy::too_many_arguments)]
826fn enumerate_row<O: DenseId, A: AuIds, M: MultiplicityLike>(
827    op: O,
828    l_classes: &[(A::Class, M)],
829    r_classes: &[(A::Class, M)],
830    row_sums: &[M],
831    matrix: &mut [Vec<M>],
832    row: usize,
833    col_residual: &mut Vec<M>,
834    a_max: usize,
835    count: &mut usize,
836    actions: &mut Vec<Action<O, A, M>>,
837) {
838    if *count >= a_max {
839        return;
840    }
841
842    let rows = l_classes.len();
843    let cols = r_classes.len();
844
845    if row == rows {
846        let mut pairs: Vec<ActionPair<A, M>> = Vec::new();
847        for i in 0..rows {
848            for j in 0..cols {
849                if matrix[i][j] > M::ZERO {
850                    pairs.push(ActionPair::<A, M> {
851                        left: l_classes[i].0,
852                        right: r_classes[j].0,
853                        count: matrix[i][j],
854                    });
855                }
856            }
857        }
858        actions.push(Action { op, pairs });
859        *count += 1;
860        return;
861    }
862
863    distribute_row(
864        op,
865        l_classes,
866        r_classes,
867        row_sums,
868        matrix,
869        row,
870        0,
871        row_sums[row],
872        col_residual,
873        a_max,
874        count,
875        actions,
876    );
877}
878
879#[allow(clippy::too_many_arguments)]
880fn distribute_row<O: DenseId, A: AuIds, M: MultiplicityLike>(
881    op: O,
882    l_classes: &[(A::Class, M)],
883    r_classes: &[(A::Class, M)],
884    row_sums: &[M],
885    matrix: &mut [Vec<M>],
886    row: usize,
887    col: usize,
888    remaining: M,
889    col_residual: &mut Vec<M>,
890    a_max: usize,
891    count: &mut usize,
892    actions: &mut Vec<Action<O, A, M>>,
893) {
894    if *count >= a_max {
895        return;
896    }
897
898    let cols = r_classes.len();
899
900    if col == cols - 1 {
901        if remaining <= col_residual[col] {
902            // Save-and-restore rather than subtract-then-add-back: the residual returns to
903            // exactly the value it held, with no second arithmetic step that could leave
904            // the width. The `saturating_sub` is exact under the guard above.
905            let saved = col_residual[col];
906            matrix[row][col] = remaining;
907            col_residual[col] = saved.saturating_sub(remaining);
908            enumerate_row(
909                op,
910                l_classes,
911                r_classes,
912                row_sums,
913                matrix,
914                row + 1,
915                col_residual,
916                a_max,
917                count,
918                actions,
919            );
920            col_residual[col] = saved;
921            matrix[row][col] = M::ZERO;
922        }
923        return;
924    }
925
926    let max_assign = remaining.min(col_residual[col]);
927    let saved = col_residual[col];
928
929    // Greedy-first: if l_classes[row] == r_classes[col] (diagonal), try the
930    // maximum allocation first (it is usually optimal). Otherwise descend from max.
931    let greedy = l_classes[row].0 == r_classes[col].0;
932    if greedy {
933        // Try max_assign first (the diagonal greedy), then the rest descending.
934        for val in descending_upto(max_assign) {
935            matrix[row][col] = val;
936            col_residual[col] = saved.saturating_sub(val);
937            distribute_row(
938                op,
939                l_classes,
940                r_classes,
941                row_sums,
942                matrix,
943                row,
944                col + 1,
945                remaining.saturating_sub(val),
946                col_residual,
947                a_max,
948                count,
949                actions,
950            );
951            col_residual[col] = saved;
952            matrix[row][col] = M::ZERO;
953            if *count >= a_max {
954                return;
955            }
956        }
957    } else {
958        // Off-diagonal: try from max down (so smaller allocations come later).
959        for val in descending_upto(max_assign) {
960            matrix[row][col] = val;
961            col_residual[col] = saved.saturating_sub(val);
962            distribute_row(
963                op,
964                l_classes,
965                r_classes,
966                row_sums,
967                matrix,
968                row,
969                col + 1,
970                remaining.saturating_sub(val),
971                col_residual,
972                a_max,
973                count,
974                actions,
975            );
976            col_residual[col] = saved;
977            matrix[row][col] = M::ZERO;
978            if *count >= a_max {
979                return;
980            }
981        }
982    }
983}
984
985/// `max ..= 0` descending, at the multiplicity width.
986///
987/// A multiplicity is not an integer literal type, so `(0..=max).rev()` — which needs
988/// `Step` — is unavailable; the range is walked at the surface width and narrowed back.
989/// Every step is `<= max`, and `max` is a value of this width, so the narrowing cannot
990/// fail. It is still spelled as a checked conversion with the reason attached rather than
991/// an `as` cast, because that argument is what makes it safe and an `as` would hide it.
992fn descending_upto<M: MultiplicityLike>(max: M) -> impl Iterator<Item = M> {
993    (0..=max.to_u64()).rev().map(|v| {
994        M::try_from_u64(v).expect("a value at or below `max` fits the width `max` came from")
995    })
996}
997
998#[cfg(test)]
999mod tests {
1000    use super::*;
1001    use crate::egraph::EGraph31;
1002    use crate::literal::NiraLitVal;
1003
1004    /// Appendix B worked example: AU(and{a,b,c}, and{b,c,d}) produces exactly 6 actions.
1005    #[test]
1006    fn appendix_b_six_actions() {
1007        let mut eg = EGraph31::<NiraLitVal, false, false>::new();
1008        let int = eg.intern_sort("Int");
1009        let a_op = eg.register_op0("a", int);
1010        let b_op = eg.register_op0("b", int);
1011        let c_op = eg.register_op0("c", int);
1012        let d_op = eg.register_op0("d", int);
1013        let and_op = eg.register_set("and", int, int);
1014
1015        let a = eg.add(a_op, &[]);
1016        let b = eg.add(b_op, &[]);
1017        let c = eg.add(c_op, &[]);
1018        let d = eg.add(d_op, &[]);
1019        let and_abc = eg.add(and_op, &[a, b, c]);
1020        let and_bcd = eg.add(and_op, &[b, c, d]);
1021        eg.rebuild();
1022
1023        let snap = AuSnapshot::new(&eg).unwrap();
1024        let l = snap.class_of(and_abc).unwrap();
1025        let r = snap.class_of(and_bcd).unwrap();
1026
1027        let mut cache = ActionCache::new(100);
1028        generate_actions(&snap, &mut cache, l, r);
1029
1030        let acts = cache.get(l, r).unwrap();
1031        // 3 distinct children on each side, all mult 1 -> 3! = 6 bijections.
1032        assert_eq!(acts.len(), 6, "expected 6 actions, got {}", acts.len());
1033
1034        // Each action should have 3 pairs with count 1.
1035        for action in acts {
1036            assert_eq!(action.pairs.len(), 3);
1037            for pair in &action.pairs {
1038                assert_eq!(pair.count, Multiplicity::ONE);
1039            }
1040        }
1041    }
1042
1043    /// AC with repeated children: AU(plus{a,a}, plus{a,b}) -> matrices with margin (2) and (1,1).
1044    #[test]
1045    fn ac_repeated_children() {
1046        let mut eg = EGraph31::<NiraLitVal, false, false>::new();
1047        let int = eg.intern_sort("Int");
1048        let a_op = eg.register_op0("a", int);
1049        let b_op = eg.register_op0("b", int);
1050        let plus_op = eg.register_mset("plus", int, int);
1051
1052        let a = eg.add(a_op, &[]);
1053        let b = eg.add(b_op, &[]);
1054        let plus_aa = eg.add(plus_op, &[a, a]);
1055        let plus_ab = eg.add(plus_op, &[a, b]);
1056        eg.rebuild();
1057
1058        let snap = AuSnapshot::new(&eg).unwrap();
1059        let l = snap.class_of(plus_aa).unwrap();
1060        let r = snap.class_of(plus_ab).unwrap();
1061
1062        let mut cache = ActionCache::new(100);
1063        generate_actions(&snap, &mut cache, l, r);
1064
1065        let acts = cache.get(l, r).unwrap();
1066        // L = {a^2}, R = {a^1, b^1}. Row margin = [2], col margins = [1, 1].
1067        // Only one matrix: x[0][0]=1, x[0][1]=1 (the row of 2 is split across 2 cols).
1068        assert_eq!(acts.len(), 1, "expected 1 action, got {}", acts.len());
1069        assert_eq!(acts[0].pairs.len(), 2);
1070    }
1071
1072    /// Ordered: f(a,b) and f(c,d) produce one positional action with 2 pairs.
1073    #[test]
1074    fn ordered_positional_zip() {
1075        let mut eg = EGraph31::<NiraLitVal, false, false>::new();
1076        let int = eg.intern_sort("Int");
1077        let a_op = eg.register_op0("a", int);
1078        let b_op = eg.register_op0("b", int);
1079        let c_op = eg.register_op0("c", int);
1080        let d_op = eg.register_op0("d", int);
1081        let f_op = eg.register_op2("f", int, int, int);
1082
1083        let a = eg.add(a_op, &[]);
1084        let b = eg.add(b_op, &[]);
1085        let c = eg.add(c_op, &[]);
1086        let d = eg.add(d_op, &[]);
1087        let fab = eg.add(f_op, &[a, b]);
1088        let fcd = eg.add(f_op, &[c, d]);
1089        eg.rebuild();
1090
1091        let snap = AuSnapshot::new(&eg).unwrap();
1092        let l = snap.class_of(fab).unwrap();
1093        let r = snap.class_of(fcd).unwrap();
1094
1095        let mut cache = ActionCache::new(100);
1096        generate_actions(&snap, &mut cache, l, r);
1097
1098        let acts = cache.get(l, r).unwrap();
1099        assert_eq!(acts.len(), 1);
1100        assert_eq!(acts[0].pairs.len(), 2);
1101        assert_eq!(acts[0].pairs[0].count, Multiplicity::ONE);
1102        assert_eq!(acts[0].pairs[1].count, Multiplicity::ONE);
1103    }
1104
1105    /// Seq preserves order and zips only equal-length members positionally.
1106    #[test]
1107    fn seq_equal_length_zips_positionally() {
1108        let mut eg = EGraph31::<NiraLitVal, false, false>::new();
1109        let int = eg.intern_sort("Int");
1110        let a_op = eg.register_op0("a", int);
1111        let b_op = eg.register_op0("b", int);
1112        let c_op = eg.register_op0("c", int);
1113        let d_op = eg.register_op0("d", int);
1114        let seq_op = eg.register_a("seq", int, int, crate::registry::AssocDir::Both);
1115
1116        let a = eg.add(a_op, &[]);
1117        let b = eg.add(b_op, &[]);
1118        let c = eg.add(c_op, &[]);
1119        let d = eg.add(d_op, &[]);
1120        let left = eg.add(seq_op, &[a, b]);
1121        let right = eg.add(seq_op, &[c, d]);
1122        eg.rebuild();
1123
1124        let snap = AuSnapshot::new(&eg).unwrap();
1125        let left_class = snap.class_of(left).unwrap();
1126        let right_class = snap.class_of(right).unwrap();
1127        let mut cache = ActionCache::new(100);
1128        generate_actions(&snap, &mut cache, left_class, right_class);
1129
1130        let actions = cache.get(left_class, right_class).unwrap();
1131        assert_eq!(actions.len(), 1);
1132        assert_eq!(actions[0].pairs.len(), 2);
1133        assert_eq!(actions[0].pairs[0].left, snap.class_of(a).unwrap());
1134        assert_eq!(actions[0].pairs[0].right, snap.class_of(c).unwrap());
1135        assert_eq!(actions[0].pairs[1].left, snap.class_of(b).unwrap());
1136        assert_eq!(actions[0].pairs[1].right, snap.class_of(d).unwrap());
1137    }
1138
1139    /// Unequal-length Seq factoring is deferred; no identity/end padding is added.
1140    #[test]
1141    fn seq_unequal_length_has_no_structural_action() {
1142        let mut eg = EGraph31::<NiraLitVal, false, false>::new();
1143        let int = eg.intern_sort("Int");
1144        let a_op = eg.register_op0("a", int);
1145        let b_op = eg.register_op0("b", int);
1146        let c_op = eg.register_op0("c", int);
1147        let d_op = eg.register_op0("d", int);
1148        let e_op = eg.register_op0("e", int);
1149        let seq_op = eg.register_a("seq", int, int, crate::registry::AssocDir::Both);
1150
1151        let a = eg.add(a_op, &[]);
1152        let b = eg.add(b_op, &[]);
1153        let c = eg.add(c_op, &[]);
1154        let d = eg.add(d_op, &[]);
1155        let e = eg.add(e_op, &[]);
1156        let left = eg.add(seq_op, &[a, b]);
1157        let right = eg.add(seq_op, &[c, d, e]);
1158        eg.rebuild();
1159
1160        let snap = AuSnapshot::new(&eg).unwrap();
1161        let left_class = snap.class_of(left).unwrap();
1162        let right_class = snap.class_of(right).unwrap();
1163        let mut cache = ActionCache::new(100);
1164        generate_actions(&snap, &mut cache, left_class, right_class);
1165
1166        assert!(cache.get(left_class, right_class).unwrap().is_empty());
1167    }
1168
1169    /// SPair: eq(a,b) vs eq(c,d) produces 2 orientations.
1170    #[test]
1171    fn spair_two_orientations() {
1172        let mut eg = EGraph31::<NiraLitVal, false, false>::new();
1173        let int = eg.intern_sort("Int");
1174        let a_op = eg.register_op0("a", int);
1175        let b_op = eg.register_op0("b", int);
1176        let c_op = eg.register_op0("c", int);
1177        let d_op = eg.register_op0("d", int);
1178        let eq_op = eg.register_c("eq", [int, int], int);
1179
1180        let a = eg.add(a_op, &[]);
1181        let b = eg.add(b_op, &[]);
1182        let c = eg.add(c_op, &[]);
1183        let d = eg.add(d_op, &[]);
1184        let eq_ab = eg.add(eq_op, &[a, b]);
1185        let eq_cd = eg.add(eq_op, &[c, d]);
1186        eg.rebuild();
1187
1188        let snap = AuSnapshot::new(&eg).unwrap();
1189        let l = snap.class_of(eq_ab).unwrap();
1190        let r = snap.class_of(eq_cd).unwrap();
1191
1192        let mut cache = ActionCache::new(100);
1193        generate_actions(&snap, &mut cache, l, r);
1194
1195        let acts = cache.get(l, r).unwrap();
1196        assert_eq!(acts.len(), 2, "expected 2 orientations");
1197    }
1198
1199    /// SPair dedup when a == b: eq(a,a) vs eq(c,d) produces only 1 orientation.
1200    #[test]
1201    fn spair_dedup_same_children() {
1202        let mut eg = EGraph31::<NiraLitVal, false, false>::new();
1203        let int = eg.intern_sort("Int");
1204        let a_op = eg.register_op0("a", int);
1205        let c_op = eg.register_op0("c", int);
1206        let d_op = eg.register_op0("d", int);
1207        let eq_op = eg.register_c("eq", [int, int], int);
1208
1209        let a = eg.add(a_op, &[]);
1210        let c = eg.add(c_op, &[]);
1211        let d = eg.add(d_op, &[]);
1212        let eq_aa = eg.add(eq_op, &[a, a]);
1213        let eq_cd = eg.add(eq_op, &[c, d]);
1214        eg.rebuild();
1215
1216        let snap = AuSnapshot::new(&eg).unwrap();
1217        let l = snap.class_of(eq_aa).unwrap();
1218        let r = snap.class_of(eq_cd).unwrap();
1219
1220        let mut cache = ActionCache::new(100);
1221        generate_actions(&snap, &mut cache, l, r);
1222
1223        let acts = cache.get(l, r).unwrap();
1224        assert_eq!(
1225            acts.len(),
1226            1,
1227            "dedup: only 1 orientation when l children are same"
1228        );
1229    }
1230
1231    /// Identity padding: conj{a, b, c} vs conj{b, c} with identity `tt`.
1232    /// The shorter side is padded to conj{b, c, tt}, then the bijection pairs
1233    /// b-b, c-c, a-tt, producing one action with 3 pairs.
1234    #[test]
1235    fn identity_padding_unequal_cardinality() {
1236        let mut eg = EGraph31::<NiraLitVal, false, false>::new();
1237        let bool_s = eg.intern_sort("Bool");
1238        let a_op = eg.register_op0("a", bool_s);
1239        let b_op = eg.register_op0("b", bool_s);
1240        let c_op = eg.register_op0("c", bool_s);
1241        let tt_op = eg.register_op0("tt", bool_s);
1242        let conj_op = eg.register_set("conj", bool_s, bool_s);
1243
1244        let a = eg.add(a_op, &[]);
1245        let b = eg.add(b_op, &[]);
1246        let c = eg.add(c_op, &[]);
1247        let tt = eg.add(tt_op, &[]);
1248        eg.set_unit_node(conj_op, tt);
1249
1250        let left = eg.add(conj_op, &[a, b, c]); // conj{a, b, c}
1251        let right = eg.add(conj_op, &[b, c]); // conj{b, c}
1252        eg.rebuild();
1253
1254        let snap = AuSnapshot::new(&eg).unwrap();
1255        let lc = snap.class_of(left).unwrap();
1256        let rc = snap.class_of(right).unwrap();
1257
1258        let mut cache = ActionCache::new(100);
1259        generate_actions(&snap, &mut cache, lc, rc);
1260
1261        let acts = cache.get(lc, rc).unwrap();
1262        // With identity padding: 3 elements on each side, so 3! = 6 bijections.
1263        // But b and c are shared, so the greedy diagonal dominates. At minimum
1264        // there should be actions (not zero, which the old code would produce).
1265        assert!(
1266            !acts.is_empty(),
1267            "identity padding should produce actions for unequal cardinality"
1268        );
1269        // The optimal action has 3 pairs (one of which pairs a with tt).
1270        let has_identity_pair = acts.iter().any(|action| {
1271            action.pairs.len() == 3
1272                && action.pairs.iter().any(|p| {
1273                    let tt_class = snap.class_of(tt).unwrap();
1274                    (p.left == snap.class_of(a).unwrap() && p.right == tt_class)
1275                        || (p.right == snap.class_of(a).unwrap() && p.left == tt_class)
1276                })
1277        });
1278        assert!(has_identity_pair, "one action should pair `a` with `tt`");
1279    }
1280
1281    /// Complete AC matrix enumeration: plus{a^2, b^2} vs plus{c^2, d^2}
1282    /// has margins [2,2] and [2,2]. The complete enumerator produces 3 valid
1283    /// matrices (k=0,1,2 for the (a,c) cell), including the interior one. This
1284    /// fixture establishes that finite enumeration only; solver optimality has
1285    /// separate bounded oracles and an open universal proof obligation.
1286    #[test]
1287    fn ac_complete_enumeration_includes_all_matrices() {
1288        let mut eg = EGraph31::<NiraLitVal, false, false>::new();
1289        let int = eg.intern_sort("Int");
1290        let a_op = eg.register_op0("a", int);
1291        let b_op = eg.register_op0("b", int);
1292        let c_op = eg.register_op0("c", int);
1293        let d_op = eg.register_op0("d", int);
1294        let plus_op = eg.register_mset("plus", int, int);
1295
1296        let a = eg.add(a_op, &[]);
1297        let b = eg.add(b_op, &[]);
1298        let c = eg.add(c_op, &[]);
1299        let d = eg.add(d_op, &[]);
1300        let left = eg.add(plus_op, &[a, a, b, b]); // plus{a^2, b^2}
1301        let right = eg.add(plus_op, &[c, c, d, d]); // plus{c^2, d^2}
1302        eg.rebuild();
1303
1304        let snap = AuSnapshot::new(&eg).unwrap();
1305        let lc = snap.class_of(left).unwrap();
1306        let rc = snap.class_of(right).unwrap();
1307
1308        let mut cache = ActionCache::new(100);
1309        generate_actions(&snap, &mut cache, lc, rc);
1310
1311        let acts = cache.get(lc, rc).unwrap();
1312        // 3 valid matrices: k=0, k=1, k=2 for the (a,c) cell.
1313        assert_eq!(
1314            acts.len(),
1315            3,
1316            "expected 3 complete matrices, got {}",
1317            acts.len()
1318        );
1319    }
1320
1321    /// Literal: same value matches, different values don't.
1322    #[test]
1323    fn literal_same_value() {
1324        let mut eg = EGraph31::<NiraLitVal, false, false>::new();
1325        let int = eg.intern_sort("Int");
1326        let lit_op = eg.register_lit("intlit", int);
1327
1328        let val1 = eg.intern_lit(crate::literal::NiraLitVal::Int(42.into()));
1329        let val2 = eg.intern_lit(crate::literal::NiraLitVal::Int(99.into()));
1330
1331        let l = eg.add_lit(lit_op, val1);
1332        let r1 = eg.add_lit(lit_op, val1);
1333        let r2 = eg.add_lit(lit_op, val2);
1334        eg.rebuild();
1335
1336        let snap = AuSnapshot::new(&eg).unwrap();
1337        let lc = snap.class_of(l).unwrap();
1338        let r1c = snap.class_of(r1).unwrap();
1339        let r2c = snap.class_of(r2).unwrap();
1340
1341        // Same value -> 1 action.
1342        let mut cache = ActionCache::new(100);
1343        generate_actions(&snap, &mut cache, lc, r1c);
1344        let acts = cache.get(lc, r1c).unwrap();
1345        assert_eq!(acts.len(), 1);
1346
1347        // Different value -> 0 actions.
1348        generate_actions(&snap, &mut cache, lc, r2c);
1349        let acts = cache.get(lc, r2c).unwrap();
1350        assert_eq!(acts.len(), 0);
1351    }
1352
1353    /// D3 regression: two operators witnessing the same child pairing must both
1354    /// survive dedup. merge(f(a), g(a)) and merge(f(b), g(b)) put an f-node and
1355    /// a g-node in each class; AU over the two classes must keep one action per
1356    /// operator, not drop whichever operator enumerates second.
1357    #[test]
1358    fn cross_operator_actions_survive_dedup() {
1359        let mut eg = EGraph31::<NiraLitVal, false, false>::new();
1360        let int = eg.intern_sort("Int");
1361        let a_op = eg.register_op0("a", int);
1362        let b_op = eg.register_op0("b", int);
1363        let f_op = eg.register_op1("f", int, int);
1364        let g_op = eg.register_op1("g", int, int);
1365
1366        let a = eg.add(a_op, &[]);
1367        let b = eg.add(b_op, &[]);
1368        let fa = eg.add(f_op, &[a]);
1369        let ga = eg.add(g_op, &[a]);
1370        let fb = eg.add(f_op, &[b]);
1371        let gb = eg.add(g_op, &[b]);
1372        eg.merge(fa, ga);
1373        eg.merge(fb, gb);
1374        eg.rebuild();
1375
1376        let snap = AuSnapshot::new(&eg).unwrap();
1377        let l = snap.class_of(fa).unwrap();
1378        let r = snap.class_of(fb).unwrap();
1379
1380        let mut cache = ActionCache::new(100);
1381        generate_actions(&snap, &mut cache, l, r);
1382
1383        let acts = cache.get(l, r).unwrap();
1384        assert_eq!(
1385            acts.len(),
1386            2,
1387            "expected one action per operator, got {}",
1388            acts.len()
1389        );
1390        assert_ne!(
1391            acts[0].op, acts[1].op,
1392            "the two actions must differ in operator"
1393        );
1394        for action in acts {
1395            assert_eq!(action.pairs.len(), 1);
1396            assert_eq!(action.pairs[0].count, Multiplicity::ONE);
1397        }
1398    }
1399}