Skip to main content

semi_persistent_egraph/
ematch.rs

1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// SPDX-License-Identifier: Apache-2.0
3//! E-matching execution over flattened relational atoms.
4//!
5//! The primary saturation path executes a statically scheduled `QueryPlan`, or
6//! schedules its next atom from the live bindings, through push-style continuations.
7//! Rust calls explore those continuations depth-first; this is control flow, not
8//! top-down pattern matching. Sortcheck has already flattened nested patterns into
9//! atoms. A separate [`MatchIterator`] provides lazy pull execution of a static plan
10//! with an explicit DFS stack.
11
12use crate::ast::{CmpOp, LitValVarId, MsetVarId, MultVarId, SeqVarId, SetVarId, VarId};
13use crate::canon::{MSetCanon, VarCanon};
14use crate::config::EGraphConfig;
15use crate::containers::IndexLike;
16use crate::egraph::EGraph;
17use crate::index::{IndexMode, IndexStore, SortedVecCursor, VariantIndex};
18use crate::leapfrog::seek_stats::Probed;
19use crate::leapfrog::{CursorVec, Difference, LeapfrogJoin, SortedCursor};
20use crate::literal::LitVal;
21use crate::multiplicity::MultiplicityLike;
22use crate::resolve::{PatVar, RMult};
23use crate::schedule::{IndexLookup, QueryPlan, Step};
24use smallvec::SmallVec;
25use std::sync::atomic::{AtomicUsize, Ordering};
26
27// ---------------------------------------------------------------------------
28// Match-work instrumentation
29// ---------------------------------------------------------------------------
30//
31// A thread-local counter of "matching steps": one increment per executed
32// `run_step` step and per emitted match. It is an implementation-level proxy
33// for e-matching work, not a count of semantic matches or a machine-independent
34// time measure.
35//
36// The hot path does not touch the thread-local at all. `run_step` increments a
37// plain `u64` on the `MatchPool` it already carries by `&mut`, and
38// `run_query_into` folds that into the thread-local once per query, if counting
39// is enabled. A thread-local read can be an out-of-line call on Apple targets,
40// so the earlier "one bool load per step" model was incomplete. The maintained
41// Criterion workload owns the current overhead comparison.
42//
43// Counting stays gated at runtime by a thread-local flag, off by default, so a
44// normal (release) run can be profiled by flipping the flag — e.g. the
45// `--count-match-steps` CLI flag — with no test-mode rebuild.
46//
47// Use `set_match_step_counting(true)` to enable, `reset_match_steps()` before a
48// measured region, and `match_steps()` after to read the delta.
49
50use std::cell::Cell;
51
52thread_local! {
53    static MATCH_STEPS: Cell<u64> = const { Cell::new(0) };
54    static COUNTING: Cell<bool> = const { Cell::new(false) };
55}
56
57/// Enable or disable match-step counting at runtime. Off by default. Turn it on
58/// to profile a run (the `--count-match-steps` CLI flag, or a measuring test)
59/// without rebuilding in test mode.
60pub fn set_match_step_counting(on: bool) {
61    COUNTING.with(|c| c.set(on));
62}
63
64/// Whether match-step counting is currently enabled on this thread.
65pub fn match_step_counting_enabled() -> bool {
66    COUNTING.with(|c| c.get())
67}
68
69/// Reset the match-step counter to zero.
70pub fn reset_match_steps() {
71    MATCH_STEPS.with(|c| c.set(0));
72}
73
74/// Read the match-step counter (number of `run_step` entries counted while
75/// counting was enabled, since the last reset).
76pub fn match_steps() -> u64 {
77    MATCH_STEPS.with(|c| c.get())
78}
79
80/// Fold a query's step tally into the thread-local counter, if counting is on.
81#[inline]
82fn add_match_steps(n: u64) {
83    if COUNTING.with(|c| c.get()) {
84        MATCH_STEPS.with(|c| c.set(c.get() + n));
85    }
86}
87
88// ---------------------------------------------------------------------------
89// Rest-pool spans
90// ---------------------------------------------------------------------------
91
92/// A `(start, len)` span into one of the flattened rest pools, in the config's index
93/// word.
94///
95/// `Cfg::Index`, not `u32` and not `usize`. Not `u32`, because a 63-bit config's pools
96/// address far past four billion entries and a fixed word would cap them there — the same
97/// hard-coded ceiling this pass exists to remove. Not `usize`, because these spans are
98/// *stored*: `Match` keeps one per seq/set/mset variable and `MatchSet` keeps one per
99/// (match, variable), so at a 31-bit config the pair is 8 bytes rather than 16, and the
100/// stride-packed span vectors — the largest arrays in a `MatchSet` after the pools
101/// themselves — halve.
102type PoolSpan<Cfg> = (<Cfg as EGraphConfig>::Index, <Cfg as EGraphConfig>::Index);
103
104/// The empty span, for an unbound rest variable.
105#[inline]
106fn empty_span<Cfg: EGraphConfig>() -> PoolSpan<Cfg> {
107    let zero = <Cfg::Index as IndexLike>::min();
108    (zero, zero)
109}
110
111/// `(start, len)` for the region `start..end` of a pool, converted into the config's
112/// index word, or a panic naming the pool if the region is not addressable there.
113///
114/// Checked on the **end** position, which is the quantity that bounds the pair: `start`
115/// and `end - start` are both at most `end`, so one check covers all three, and the span
116/// can then be read back as `s + l` in the index word without a second check at every
117/// read. Checking the two fields separately instead would wave through exactly the case
118/// that matters — a start and a length that each fit while their sum does not.
119///
120/// This is a hard failure rather than a saturating clamp because a truncated span is
121/// unrecoverable and silent: it aliases one variable's rest data onto another's, and
122/// e-matching would then report confident, wrong matches. The message names the pool and
123/// the ceiling so the remedy (a wider `EGraphConfig::Index`) is actionable.
124#[inline]
125fn pool_span<Cfg: EGraphConfig>(start: usize, end: usize, pool: &'static str) -> PoolSpan<Cfg> {
126    debug_assert!(
127        start <= end,
128        "{pool}: span end {end} precedes start {start}"
129    );
130    if <Cfg::Index as IndexLike>::try_from_usize(end).is_none() {
131        panic!(
132            "{pool} grew to {end} entries, past the {} addressable by EGraphConfig::Index; \
133             configure a wider index word",
134            <Cfg::Index as IndexLike>::max().as_usize(),
135        );
136    }
137    // Both fit, given `end` does: `start <= end` and `end - start <= end`.
138    let ix = |n: usize| {
139        <Cfg::Index as IndexLike>::try_from_usize(n).expect("bounded by the checked end position")
140    };
141    (ix(start), ix(end - start))
142}
143
144/// The `start..start + len` range of a stored span, back in `usize` for slicing.
145///
146/// Widening, so it cannot truncate, and the sum cannot overflow `usize`: both fields came
147/// from positions in a live `Vec`, whose length is a `usize`.
148#[inline]
149fn span_range<Cfg: EGraphConfig>(span: PoolSpan<Cfg>) -> core::ops::Range<usize> {
150    let start = span.0.as_usize();
151    start..start + span.1.as_usize()
152}
153
154// ---------------------------------------------------------------------------
155// Binding environment
156// ---------------------------------------------------------------------------
157
158#[derive(Debug)]
159pub struct Match<Cfg: EGraphConfig> {
160    /// E-node bindings indexed by VarId.
161    pub nodes: Vec<Option<Cfg::G>>,
162    /// Multiplicity bindings indexed by MultVarId.
163    pub mults: Vec<Cfg::M>,
164    /// Literal value bindings indexed by LitValVarId.
165    pub lit_vals: Vec<Cfg::V>,
166    /// Sequence rest pool — all seq slices packed contiguously.
167    pub seq_pool: Vec<Cfg::G>,
168    /// Span (start, len) into seq_pool, indexed by SeqVarId.
169    pub seq_spans: Vec<PoolSpan<Cfg>>,
170    /// Set rest pool — all set slices packed contiguously.
171    pub set_pool: Vec<Cfg::G>,
172    /// Span (start, len) into set_pool, indexed by SetVarId.
173    pub set_spans: Vec<PoolSpan<Cfg>>,
174    /// Multiset rest pool — packed AC children (id + mult).
175    pub mset_pool: Vec<Cfg::C>,
176    /// Span (start, len) into mset_pool, indexed by MsetVarId.
177    pub mset_spans: Vec<PoolSpan<Cfg>>,
178}
179
180impl<Cfg: EGraphConfig> Clone for Match<Cfg> {
181    fn clone(&self) -> Self {
182        Self {
183            nodes: self.nodes.clone(),
184            mults: self.mults.clone(),
185            lit_vals: self.lit_vals.clone(),
186            seq_pool: self.seq_pool.clone(),
187            seq_spans: self.seq_spans.clone(),
188            set_pool: self.set_pool.clone(),
189            set_spans: self.set_spans.clone(),
190            mset_pool: self.mset_pool.clone(),
191            mset_spans: self.mset_spans.clone(),
192        }
193    }
194
195    /// Overwrite in place, keeping every existing allocation.
196    ///
197    /// Spelled out rather than left to the default `*self = source.clone()`,
198    /// which drops nine buffers and allocates nine more. `Vec::clone_from`
199    /// reuses the destination's capacity when it suffices, so a recycled match
200    /// costs nine `memcpy`s and no allocator traffic. This is what makes
201    /// [`MatchPool`] worth retaining across matches.
202    fn clone_from(&mut self, source: &Self) {
203        self.nodes.clone_from(&source.nodes);
204        self.mults.clone_from(&source.mults);
205        self.lit_vals.clone_from(&source.lit_vals);
206        self.seq_pool.clone_from(&source.seq_pool);
207        self.seq_spans.clone_from(&source.seq_spans);
208        self.set_pool.clone_from(&source.set_pool);
209        self.set_spans.clone_from(&source.set_spans);
210        self.mset_pool.clone_from(&source.mset_pool);
211        self.mset_spans.clone_from(&source.mset_spans);
212    }
213}
214
215impl<Cfg: EGraphConfig> Match<Cfg> {
216    pub fn new(shape: &crate::resolve::MatchShape) -> Self {
217        Self {
218            nodes: vec![None; shape.num_vars()],
219            mults: vec![Cfg::M::ZERO; shape.num_mult_vars()],
220            lit_vals: vec![Cfg::V::default(); shape.num_lit_val_vars()],
221            seq_pool: Vec::new(),
222            seq_spans: vec![empty_span::<Cfg>(); shape.num_seq_vars()],
223            set_pool: Vec::new(),
224            set_spans: vec![empty_span::<Cfg>(); shape.num_set_vars()],
225            mset_pool: Vec::new(),
226            mset_spans: vec![empty_span::<Cfg>(); shape.num_mset_vars()],
227        }
228    }
229    // Node bindings
230    pub fn get(&self, v: VarId) -> Cfg::G {
231        self.nodes[v.idx()].unwrap()
232    }
233    pub fn set(&mut self, v: VarId, val: Cfg::G) {
234        self.nodes[v.idx()] = Some(val);
235    }
236    pub fn clear(&mut self, v: VarId) {
237        self.nodes[v.idx()] = None;
238    }
239    /// Read the raw binding (bound value or `None`). For save/restore of a slot that may
240    /// already be bound (the bound-node re-join in `leapfrog_join`).
241    pub fn get_opt(&self, v: VarId) -> Option<Cfg::G> {
242        self.nodes[v.idx()]
243    }
244    /// Restore a raw binding saved by `get_opt`.
245    pub fn set_opt(&mut self, v: VarId, val: Option<Cfg::G>) {
246        self.nodes[v.idx()] = val;
247    }
248    /// Resolve a PatVar: local from env, global from GlobalCtx.
249    pub fn resolve_pv<S: Copy>(
250        &self,
251        pv: PatVar,
252        globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
253    ) -> Cfg::G {
254        match pv {
255            PatVar::Local(vid) => self.get(vid),
256            PatVar::Global(gid) => globals.binding(gid),
257        }
258    }
259    // Mult bindings
260    pub fn get_mult(&self, v: MultVarId) -> Cfg::M {
261        self.mults[v.idx()]
262    }
263    pub fn set_mult(&mut self, v: MultVarId, val: Cfg::M) {
264        self.mults[v.idx()] = val;
265    }
266    // Lit val bindings
267    pub fn get_lit_val(&self, v: LitValVarId) -> Cfg::V {
268        self.lit_vals[v.idx()]
269    }
270    pub fn set_lit_val(&mut self, v: LitValVarId, val: Cfg::V) {
271        self.lit_vals[v.idx()] = val;
272    }
273    // Seq rest
274    pub fn seq_slice(&self, v: SeqVarId) -> &[Cfg::G] {
275        &self.seq_pool[span_range::<Cfg>(self.seq_spans[v.idx()])]
276    }
277    pub fn push_seq(&mut self, v: SeqVarId, data: &[Cfg::G]) {
278        let start = self.seq_pool.len();
279        self.seq_pool.extend_from_slice(data);
280        self.seq_spans[v.idx()] = pool_span::<Cfg>(start, self.seq_pool.len(), "Match::seq_pool");
281    }
282    pub fn pop_seq(&mut self, v: SeqVarId) {
283        let (s, _) = self.seq_spans[v.idx()];
284        self.seq_pool.truncate(s.as_usize());
285        self.seq_spans[v.idx()] = empty_span::<Cfg>();
286    }
287    // Set rest
288    pub fn set_slice(&self, v: SetVarId) -> &[Cfg::G] {
289        &self.set_pool[span_range::<Cfg>(self.set_spans[v.idx()])]
290    }
291    pub fn push_set(&mut self, v: SetVarId, data: &[Cfg::G]) {
292        let start = self.set_pool.len();
293        self.set_pool.extend_from_slice(data);
294        self.set_spans[v.idx()] = pool_span::<Cfg>(start, self.set_pool.len(), "Match::set_pool");
295    }
296    pub fn pop_set(&mut self, v: SetVarId) {
297        let (s, _) = self.set_spans[v.idx()];
298        self.set_pool.truncate(s.as_usize());
299        self.set_spans[v.idx()] = empty_span::<Cfg>();
300    }
301    // Mset rest
302    pub fn mset_slice(&self, v: MsetVarId) -> &[Cfg::C] {
303        &self.mset_pool[span_range::<Cfg>(self.mset_spans[v.idx()])]
304    }
305    pub fn push_mset(&mut self, v: MsetVarId, data: &[Cfg::C]) {
306        let start = self.mset_pool.len();
307        self.mset_pool.extend_from_slice(data);
308        self.mset_spans[v.idx()] =
309            pool_span::<Cfg>(start, self.mset_pool.len(), "Match::mset_pool");
310    }
311    pub fn pop_mset(&mut self, v: MsetVarId) {
312        let (s, _) = self.mset_spans[v.idx()];
313        self.mset_pool.truncate(s.as_usize());
314        self.mset_spans[v.idx()] = empty_span::<Cfg>();
315    }
316
317    /// Bind `v` to the still-available residual entries, writing them
318    /// straight onto the pool tail (E15). `push_mset` with a caller-built
319    /// slice re-bought a temporary per binding at every leaf of the AC
320    /// assignment search - 221k bindings per allocprobe run, three growth
321    /// allocations each; the pool was the destination all along.
322    pub fn push_mset_residual(&mut self, v: MsetVarId, residual: &[(Cfg::G, Cfg::M)]) {
323        let start = self.mset_pool.len();
324        let zero = Cfg::M::ZERO;
325        self.mset_pool.extend(
326            residual
327                .iter()
328                .filter(|&&(_, m)| m > zero)
329                .map(|&(g, m)| Cfg::mset_child_with_mult(g, m)),
330        );
331        self.mset_spans[v.idx()] =
332            pool_span::<Cfg>(start, self.mset_pool.len(), "Match::mset_pool");
333    }
334
335    /// The ACI counterpart: bind `v` to the residual ids not consumed by the
336    /// element assignment (same write-through mechanism).
337    pub fn push_set_residual(
338        &mut self,
339        v: SetVarId,
340        residual: &[Cfg::G],
341        used: &crate::containers::bitset::BitSet,
342    ) {
343        let start = self.set_pool.len();
344        self.set_pool.extend(
345            residual
346                .iter()
347                .enumerate()
348                .filter(|&(i, _)| !used.test(i))
349                .map(|(_, &g)| g),
350        );
351        self.set_spans[v.idx()] = pool_span::<Cfg>(start, self.set_pool.len(), "Match::set_pool");
352    }
353}
354
355// ---------------------------------------------------------------------------
356// MatchPool — recycled match storage across queries
357// ---------------------------------------------------------------------------
358
359/// A reusable buffer of matches.
360///
361/// `run_query` emits one `Match` per solution, and each `Match` owns nine
362/// `Vec`s. Freshly allocating them per match cost about nine allocations per
363/// emitted match, and freeing them at the end of the round cost as many again —
364/// on the `plain7` workload that is the single largest source of allocator
365/// traffic in saturation.
366///
367/// A pool stores each query's solutions in one flat, stride-packed `MatchSet`.
368/// Clearing or reshaping resets the vector lengths while retaining their
369/// allocations; pushing appends bindings and rest data into those warm vectors.
370/// Because a saturation round runs many queries of similar shapes and sizes,
371/// the vectors reach their high-water capacities early and then allocate
372/// little or nothing.
373///
374/// The two scratch free-lists (`Self::take_id_buf` and
375/// friends) are deliberately *not* touched by [`Self::clear`]. They hold no
376/// query state — every borrower fills them from scratch before reading, since
377/// `seq_children`/`set_children`/`mset_children` all begin with `buf.clear()` —
378/// so surviving a `clear` is the whole point of them.
379pub struct MatchPool<Cfg: EGraphConfig> {
380    /// Flat stride-packed storage (E17): the per-slot form allocated ~5 vecs
381    /// per fresh slot up to the query's high-water — 76k slots and ~380k
382    /// allocations on ac10/naive — where the flat arrays grow amortized.
383    set: MatchSet<Cfg>,
384    /// Retired child-id buffers, lent to the `ExpandA`/`DecomposeACI` steps.
385    id_bufs: Vec<Vec<Cfg::G>>,
386    /// Retired `(id, multiplicity)` buffers, lent to the `DecomposeAC` step.
387    mset_bufs: Vec<Vec<(Cfg::G, Cfg::M)>>,
388    /// Partial-match extensions the current query has explored — one per
389    /// `run_step` entry. Reset by `run_query_into` and folded into the
390    /// thread-local match-step counter when the query finishes; see the
391    /// match-work instrumentation notes at the top of this file.
392    steps: u64,
393    /// [`op_filter_policy`] as of this query's start. Carried on the pool
394    /// because it is the only per-query state `run_join` already receives; see
395    /// [`OP_FILTER_POLICY`] for why it is not read per join.
396    op_filter_policy: OpFilterPolicy,
397}
398
399impl<Cfg: EGraphConfig> Default for MatchPool<Cfg> {
400    fn default() -> Self {
401        Self::new()
402    }
403}
404
405impl<Cfg: EGraphConfig> MatchPool<Cfg> {
406    pub fn new() -> Self {
407        Self {
408            set: MatchSet::empty(),
409            id_bufs: Vec::new(),
410            mset_bufs: Vec::new(),
411            steps: 0,
412            op_filter_policy: OpFilterPolicy::Adaptive,
413        }
414    }
415
416    /// Adopt a query's shape, dropping stored matches and keeping every flat
417    /// allocation warm.
418    pub fn reshape(&mut self, shape: &crate::resolve::MatchShape) {
419        self.set.reshape(shape);
420    }
421
422    /// One stored match, by row.
423    #[inline]
424    pub fn row(&self, j: usize) -> MatchRow<'_, Cfg> {
425        MatchRow { set: &self.set, j }
426    }
427
428    /// Reconstruct row `j` as an owned `Match` (tests and diagnostics; this
429    /// allocates and the hot paths never call it).
430    pub fn clone_match(&self, j: usize) -> Match<Cfg> {
431        let s = &self.set;
432        let mut m = Match {
433            nodes: (0..s.node_stride)
434                .map(|i| Some(s.nodes[j * s.node_stride + i]))
435                .collect(),
436            mults: s.mults[j * s.mult_stride..(j + 1) * s.mult_stride].to_vec(),
437            lit_vals: s.lit_vals[j * s.lit_stride..(j + 1) * s.lit_stride].to_vec(),
438            seq_pool: Vec::new(),
439            seq_spans: vec![empty_span::<Cfg>(); s.seq_stride],
440            set_pool: Vec::new(),
441            set_spans: vec![empty_span::<Cfg>(); s.set_stride],
442            mset_pool: Vec::new(),
443            mset_spans: vec![empty_span::<Cfg>(); s.mset_stride],
444        };
445        for i in 0..s.seq_stride {
446            let span = s.seq_spans[j * s.seq_stride + i];
447            let start = m.seq_pool.len();
448            m.seq_pool
449                .extend_from_slice(&s.seq_pool[span_range::<Cfg>(span)]);
450            m.seq_spans[i] = pool_span::<Cfg>(start, m.seq_pool.len(), "clone_match:seq");
451        }
452        for i in 0..s.set_stride {
453            let span = s.set_spans[j * s.set_stride + i];
454            let start = m.set_pool.len();
455            m.set_pool
456                .extend_from_slice(&s.set_pool[span_range::<Cfg>(span)]);
457            m.set_spans[i] = pool_span::<Cfg>(start, m.set_pool.len(), "clone_match:set");
458        }
459        for i in 0..s.mset_stride {
460            let span = s.mset_spans[j * s.mset_stride + i];
461            let start = m.mset_pool.len();
462            m.mset_pool
463                .extend_from_slice(&s.mset_pool[span_range::<Cfg>(span)]);
464            m.mset_spans[i] = pool_span::<Cfg>(start, m.mset_pool.len(), "clone_match:mset");
465        }
466        m
467    }
468
469    /// Borrow a child-id buffer, by move.
470    ///
471    /// By move rather than by reference because the borrower passes `&mut self`
472    /// down the same call it uses the buffer in, so a `&mut` into the pool could
473    /// not coexist with it. The caller must return it via [`Self::give_id_buf`];
474    /// failing to is a leak of one allocation, not a correctness bug.
475    #[inline]
476    fn take_id_buf(&mut self) -> Vec<Cfg::G> {
477        self.id_bufs.pop().unwrap_or_default()
478    }
479
480    #[inline]
481    fn give_id_buf(&mut self, buf: Vec<Cfg::G>) {
482        self.id_bufs.push(buf);
483    }
484
485    #[inline]
486    fn take_mset_buf(&mut self) -> Vec<(Cfg::G, Cfg::M)> {
487        self.mset_bufs.pop().unwrap_or_default()
488    }
489
490    #[inline]
491    fn give_mset_buf(&mut self, buf: Vec<(Cfg::G, Cfg::M)>) {
492        self.mset_bufs.push(buf);
493    }
494
495    /// Drop the previous query's results without releasing their storage.
496    #[inline]
497    pub fn clear(&mut self) {
498        self.set.clear();
499    }
500
501    /// Append a copy of `env` into the flat store.
502    #[inline]
503    pub fn push(&mut self, env: &Match<Cfg>) {
504        self.set.push(env);
505    }
506
507    #[inline]
508    pub fn len(&self) -> usize {
509        self.set.len()
510    }
511
512    #[inline]
513    pub fn is_empty(&self) -> bool {
514        self.set.is_empty()
515    }
516}
517
518// ---------------------------------------------------------------------------
519// MatchSet — flat SoA storage for multiple matches
520// ---------------------------------------------------------------------------
521
522/// Flat, stride-packed storage for all matches of a query.
523///
524/// Each variable kind occupies a single `Vec` with `stride` entries per match.
525/// Stride = number of variables of that kind (from `MatchShape`).
526/// Rest data lives in shared append-only pools; per-match spans are strided.
527pub struct MatchSet<Cfg: EGraphConfig> {
528    pub count: usize,
529    node_stride: usize,
530    mult_stride: usize,
531    lit_stride: usize,
532    seq_stride: usize,
533    set_stride: usize,
534    mset_stride: usize,
535    nodes: Vec<Cfg::G>,
536    mults: Vec<Cfg::M>,
537    lit_vals: Vec<Cfg::V>,
538    seq_spans: Vec<PoolSpan<Cfg>>,
539    set_spans: Vec<PoolSpan<Cfg>>,
540    mset_spans: Vec<PoolSpan<Cfg>>,
541    seq_pool: Vec<Cfg::G>,
542    set_pool: Vec<Cfg::G>,
543    mset_pool: Vec<Cfg::C>,
544}
545
546impl<Cfg: EGraphConfig> MatchSet<Cfg> {
547    pub fn new(shape: &crate::resolve::MatchShape) -> Self {
548        Self {
549            count: 0,
550            node_stride: shape.num_vars(),
551            mult_stride: shape.num_mult_vars(),
552            lit_stride: shape.num_lit_val_vars(),
553            seq_stride: shape.num_seq_vars(),
554            set_stride: shape.num_set_vars(),
555            mset_stride: shape.num_mset_vars(),
556            nodes: Vec::new(),
557            mults: Vec::new(),
558            lit_vals: Vec::new(),
559            seq_spans: Vec::new(),
560            set_spans: Vec::new(),
561            mset_spans: Vec::new(),
562            seq_pool: Vec::new(),
563            set_pool: Vec::new(),
564            mset_pool: Vec::new(),
565        }
566    }
567
568    /// A shapeless set (every stride zero); given a real shape by
569    /// [`Self::reshape`] before first use. What lets one warm store serve
570    /// queries of different shapes across a whole saturation.
571    pub fn empty() -> Self {
572        Self {
573            count: 0,
574            node_stride: 0,
575            mult_stride: 0,
576            lit_stride: 0,
577            seq_stride: 0,
578            set_stride: 0,
579            mset_stride: 0,
580            nodes: Vec::new(),
581            mults: Vec::new(),
582            lit_vals: Vec::new(),
583            seq_spans: Vec::new(),
584            set_spans: Vec::new(),
585            mset_spans: Vec::new(),
586            seq_pool: Vec::new(),
587            set_pool: Vec::new(),
588            mset_pool: Vec::new(),
589        }
590    }
591
592    /// Adopt a query's shape: set the strides and drop stored matches, keeping
593    /// every flat allocation (the warm-reuse discipline across queries).
594    pub fn reshape(&mut self, shape: &crate::resolve::MatchShape) {
595        self.node_stride = shape.num_vars();
596        self.mult_stride = shape.num_mult_vars();
597        self.lit_stride = shape.num_lit_val_vars();
598        self.seq_stride = shape.num_seq_vars();
599        self.set_stride = shape.num_set_vars();
600        self.mset_stride = shape.num_mset_vars();
601        self.count = 0;
602        self.nodes.clear();
603        self.mults.clear();
604        self.lit_vals.clear();
605        self.seq_spans.clear();
606        self.set_spans.clear();
607        self.mset_spans.clear();
608        self.seq_pool.clear();
609        self.set_pool.clear();
610        self.mset_pool.clear();
611    }
612
613    /// Append one match.
614    pub fn push(&mut self, m: &Match<Cfg>) {
615        // `extend` over a sized iterator, not a `push` per variable: the
616        // capacity check moves out of the loop, and this runs once per match.
617        self.nodes
618            .extend(m.nodes[..self.node_stride].iter().map(|v| v.unwrap()));
619        if !m.mults.is_empty() {
620            self.mults.extend_from_slice(&m.mults);
621        }
622        if !m.lit_vals.is_empty() {
623            self.lit_vals.extend_from_slice(&m.lit_vals);
624        }
625        for &span in &m.seq_spans {
626            let start = self.seq_pool.len();
627            self.seq_pool
628                .extend_from_slice(&m.seq_pool[span_range::<Cfg>(span)]);
629            self.seq_spans.push(pool_span::<Cfg>(
630                start,
631                self.seq_pool.len(),
632                "MatchSet::seq_pool",
633            ));
634        }
635        for &span in &m.set_spans {
636            let start = self.set_pool.len();
637            self.set_pool
638                .extend_from_slice(&m.set_pool[span_range::<Cfg>(span)]);
639            self.set_spans.push(pool_span::<Cfg>(
640                start,
641                self.set_pool.len(),
642                "MatchSet::set_pool",
643            ));
644        }
645        for &span in &m.mset_spans {
646            let start = self.mset_pool.len();
647            self.mset_pool
648                .extend_from_slice(&m.mset_pool[span_range::<Cfg>(span)]);
649            self.mset_spans.push(pool_span::<Cfg>(
650                start,
651                self.mset_pool.len(),
652                "MatchSet::mset_pool",
653            ));
654        }
655        self.count += 1;
656    }
657
658    pub fn is_empty(&self) -> bool {
659        self.count == 0
660    }
661
662    pub fn len(&self) -> usize {
663        self.count
664    }
665
666    pub fn get_node(&self, v: VarId, j: usize) -> Cfg::G {
667        self.nodes[j * self.node_stride + v.idx()]
668    }
669    pub fn get_mult(&self, v: MultVarId, j: usize) -> Cfg::M {
670        self.mults[j * self.mult_stride + v.idx()]
671    }
672    pub fn get_lit_val(&self, v: LitValVarId, j: usize) -> Cfg::V {
673        self.lit_vals[j * self.lit_stride + v.idx()]
674    }
675    pub fn set_node(&mut self, v: VarId, j: usize, val: Cfg::G) {
676        self.nodes[j * self.node_stride + v.idx()] = val;
677    }
678    pub fn set_mult(&mut self, v: MultVarId, j: usize, val: Cfg::M) {
679        self.mults[j * self.mult_stride + v.idx()] = val;
680    }
681    pub fn seq_slice(&self, v: SeqVarId, j: usize) -> &[Cfg::G] {
682        let span = self.seq_spans[j * self.seq_stride + v.idx()];
683        &self.seq_pool[span_range::<Cfg>(span)]
684    }
685    pub fn set_slice(&self, v: SetVarId, j: usize) -> &[Cfg::G] {
686        let span = self.set_spans[j * self.set_stride + v.idx()];
687        &self.set_pool[span_range::<Cfg>(span)]
688    }
689    pub fn mset_slice(&self, v: MsetVarId, j: usize) -> &[Cfg::C] {
690        let span = self.mset_spans[j * self.mset_stride + v.idx()];
691        &self.mset_pool[span_range::<Cfg>(span)]
692    }
693
694    /// Drop the stored matches without releasing storage (the `MatchPool`
695    /// warm-reuse discipline, for consumers that keep a `MatchSet` across
696    /// queries).
697    pub fn clear(&mut self) {
698        self.count = 0;
699        self.nodes.clear();
700        self.mults.clear();
701        self.lit_vals.clear();
702        self.seq_spans.clear();
703        self.set_spans.clear();
704        self.mset_spans.clear();
705        self.seq_pool.clear();
706        self.set_pool.clear();
707        self.mset_pool.clear();
708    }
709}
710
711// ---------------------------------------------------------------------------
712// MatchView — one access surface over an owned Match and a MatchSet row
713// ---------------------------------------------------------------------------
714
715/// The read-only binding-access surface consumed by RHS evaluation.
716///
717/// Comprehension locals are deliberately not stored in a query match; they
718/// live in `apply::RhsEnv`.
719pub trait MatchView<Cfg: EGraphConfig> {
720    fn get(&self, v: VarId) -> Cfg::G;
721    fn get_mult(&self, v: MultVarId) -> Cfg::M;
722    fn get_lit_val(&self, v: LitValVarId) -> Cfg::V;
723    fn seq_slice(&self, v: SeqVarId) -> &[Cfg::G];
724    fn set_slice(&self, v: SetVarId) -> &[Cfg::G];
725    fn mset_slice(&self, v: MsetVarId) -> &[Cfg::C];
726}
727
728impl<Cfg: EGraphConfig> MatchView<Cfg> for Match<Cfg> {
729    fn get(&self, v: VarId) -> Cfg::G {
730        Match::get(self, v)
731    }
732    fn get_mult(&self, v: MultVarId) -> Cfg::M {
733        Match::get_mult(self, v)
734    }
735    fn get_lit_val(&self, v: LitValVarId) -> Cfg::V {
736        Match::get_lit_val(self, v)
737    }
738    fn seq_slice(&self, v: SeqVarId) -> &[Cfg::G] {
739        Match::seq_slice(self, v)
740    }
741    fn set_slice(&self, v: SetVarId) -> &[Cfg::G] {
742        Match::set_slice(self, v)
743    }
744    fn mset_slice(&self, v: MsetVarId) -> &[Cfg::C] {
745        Match::mset_slice(self, v)
746    }
747}
748
749/// One match of a [`MatchSet`], by row index.
750pub struct MatchRow<'a, Cfg: EGraphConfig> {
751    set: &'a MatchSet<Cfg>,
752    j: usize,
753}
754
755impl<'a, Cfg: EGraphConfig> MatchView<Cfg> for MatchRow<'a, Cfg> {
756    fn get(&self, v: VarId) -> Cfg::G {
757        self.set.get_node(v, self.j)
758    }
759    fn get_mult(&self, v: MultVarId) -> Cfg::M {
760        self.set.get_mult(v, self.j)
761    }
762    fn get_lit_val(&self, v: LitValVarId) -> Cfg::V {
763        self.set.get_lit_val(v, self.j)
764    }
765    fn seq_slice(&self, v: SeqVarId) -> &[Cfg::G] {
766        self.set.seq_slice(v, self.j)
767    }
768    fn set_slice(&self, v: SetVarId) -> &[Cfg::G] {
769        self.set.set_slice(v, self.j)
770    }
771    fn mset_slice(&self, v: MsetVarId) -> &[Cfg::C] {
772        self.set.mset_slice(v, self.j)
773    }
774}
775
776// ---------------------------------------------------------------------------
777// Cloned iterator adapter
778// ---------------------------------------------------------------------------
779
780/// Adapter that wraps `MatchIterator` and yields owned `Match<Cfg>` clones.
781pub struct ClonedMatchIter<'a, Cfg: EGraphConfig, L: LitVal, S: Copy, const T: bool, const P: bool>
782{
783    inner: MatchIterator<'a, Cfg, L, S, T, P>,
784}
785
786impl<'a, Cfg, L, S: Copy, const T: bool, const P: bool> Iterator
787    for ClonedMatchIter<'a, Cfg, L, S, T, P>
788where
789    Cfg: EGraphConfig,
790    L: LitVal,
791    MSetCanon: VarCanon<Cfg::G, Cfg::C>,
792{
793    type Item = Match<Cfg>;
794    fn next(&mut self) -> Option<Match<Cfg>> {
795        if self.inner.next_match() {
796            Some(self.inner.env().clone())
797        } else {
798            None
799        }
800    }
801}
802
803// ---------------------------------------------------------------------------
804// Match iterator
805// ---------------------------------------------------------------------------
806
807/// Collects all matches of `plan` against `eg`/`index` into a fresh `Vec`.
808///
809/// Convenience wrapper over [`run_query_into`] for callers that run one query
810/// and do not care about allocation — tests, the REPL, `EGraph::run_query`. The
811/// saturation drivers use `run_query_into` with a persistent [`MatchPool`].
812pub fn run_query<Cfg, L, S: Copy, const TRACK: bool, const PROOFS: bool>(
813    plan: &QueryPlan<Cfg::O, Cfg::Index, L>,
814    eg: &EGraph<Cfg, L, TRACK, PROOFS>,
815    index: &VariantIndex<'_, Cfg>,
816    globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
817) -> Vec<Match<Cfg>>
818where
819    Cfg: EGraphConfig,
820    L: LitVal,
821    MSetCanon: VarCanon<Cfg::G, Cfg::C>,
822{
823    let mut pool = MatchPool::new();
824    run_query_into(plan, eg, index, globals, &mut pool);
825    (0..pool.len()).map(|j| pool.clone_match(j)).collect()
826}
827
828/// The round's class representative for `id` — the one the index snapshot was
829/// built with, not the e-graph's live one.
830///
831/// Matching is specified against the e-graph as of the round's index build
832/// (chapter 09). The e-graph keeps changing inside a round: every rule's
833/// actions merge classes and add nodes before the next rule matches, while the
834/// index buckets stay keyed by the reprs of the build. Canonicalizing with the
835/// live union-find and then probing a bucket keyed at build time therefore
836/// reads a bucket belonging to a different class — `ByRepr` and `ByChildPos`
837/// go wrong in opposite directions on the same merge — and `CheckChildEq`
838/// accepts pairs that the snapshot kept apart. Which of those a query performs
839/// is decided by the join order, so the defect made the match set a function of
840/// the plan. Focused regressions, rather than a workload percentage, pin it.
841/// Every canonicalization in the matcher goes through here instead.
842///
843/// The fallback covers ids the snapshot does not know: a delta store defers to
844/// its full index (which is where the mapping is kept), and a global may be
845/// bound to a node minted after the build. Bindings never need it — each one
846/// descends from a snapshot bucket.
847#[inline]
848fn canon<Cfg, L, const TRACK: bool, const PROOFS: bool>(
849    index: &VariantIndex<'_, Cfg>,
850    eg: &EGraph<Cfg, L, TRACK, PROOFS>,
851    id: Cfg::G,
852) -> Cfg::G
853where
854    Cfg: EGraphConfig,
855    L: LitVal,
856    MSetCanon: VarCanon<Cfg::G, Cfg::C>,
857{
858    match index.full.round_repr(id) {
859        Some(r) => r,
860        None => eg.find_const(id),
861    }
862}
863
864/// Collect all matches of `plan` into `pool`, reusing its storage.
865///
866/// The pool is cleared first, so a caller may hand the same pool to every query
867/// in a round; see [`MatchPool`] for why that is where the win is.
868pub fn run_query_into<Cfg, L, S: Copy, const TRACK: bool, const PROOFS: bool>(
869    plan: &QueryPlan<Cfg::O, Cfg::Index, L>,
870    eg: &EGraph<Cfg, L, TRACK, PROOFS>,
871    index: &VariantIndex<'_, Cfg>,
872    globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
873    pool: &mut MatchPool<Cfg>,
874) where
875    Cfg: EGraphConfig,
876    L: LitVal,
877    MSetCanon: VarCanon<Cfg::G, Cfg::C>,
878{
879    pool.reshape(&plan.shape);
880    pool.steps = 0;
881    pool.op_filter_policy = op_filter_policy();
882    let mut env = Match::new(&plan.shape);
883    let exec = Exec::<Cfg, L, S>::static_plan(&plan.steps);
884    run_step(&exec, 0, eg, index, globals, &mut env, pool);
885    add_match_steps(pool.steps);
886}
887
888/// Collect all matches of `rq` into `pool`, choosing the atom order at plan time
889/// (`plan`) or per binding, according to [`runtime_scheduling`].
890///
891/// `plan` is `rq` scheduled by [`schedule_with_stats`](crate::schedule::schedule_with_stats).
892/// It is what runs with the flag off, and it is also the fallback for a query
893/// too wide for the runtime scheduler's masks (see [`ADAPTIVE_MAX_WIDTH`]), so a
894/// caller passes both and gets the same match set either way.
895pub fn run_query_scheduled_into<Cfg, L, S: Copy, const TRACK: bool, const PROOFS: bool>(
896    rq: &crate::resolve::ResolvedQuery<Cfg::O, S, L>,
897    plan: &QueryPlan<Cfg::O, Cfg::Index, L>,
898    eg: &EGraph<Cfg, L, TRACK, PROOFS>,
899    index: &VariantIndex<'_, Cfg>,
900    globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
901    pool: &mut MatchPool<Cfg>,
902) where
903    Cfg: EGraphConfig,
904    L: LitVal,
905    MSetCanon: VarCanon<Cfg::G, Cfg::C>,
906{
907    if !runtime_scheduling() || !Adaptive::<Cfg, L, S>::fits(rq) {
908        run_query_into(plan, eg, index, globals, pool);
909        return;
910    }
911    pool.reshape(&rq.shape);
912    pool.steps = 0;
913    pool.op_filter_policy = op_filter_policy();
914    let mut env = Match::new(&rq.shape);
915    let adaptive = Adaptive::new(rq);
916    let exec = Exec::adaptive(&adaptive);
917    run_step(&exec, 0, eg, index, globals, &mut env, pool);
918    add_match_steps(pool.steps);
919}
920
921/// [`run_query_scheduled_into`] into a fresh `Vec`; the counterpart of
922/// [`run_query`] for callers that want the flag respected.
923pub fn run_query_scheduled<Cfg, L, S: Copy, const TRACK: bool, const PROOFS: bool>(
924    rq: &crate::resolve::ResolvedQuery<Cfg::O, S, L>,
925    plan: &QueryPlan<Cfg::O, Cfg::Index, L>,
926    eg: &EGraph<Cfg, L, TRACK, PROOFS>,
927    index: &VariantIndex<'_, Cfg>,
928    globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
929) -> Vec<Match<Cfg>>
930where
931    Cfg: EGraphConfig,
932    L: LitVal,
933    MSetCanon: VarCanon<Cfg::G, Cfg::C>,
934{
935    let mut pool = MatchPool::new();
936    run_query_scheduled_into(rq, plan, eg, index, globals, &mut pool);
937    (0..pool.len()).map(|j| pool.clone_match(j)).collect()
938}
939
940// ---------------------------------------------------------------------------
941// Runtime atom scheduling
942// ---------------------------------------------------------------------------
943
944thread_local! {
945    /// Whether the matcher picks the next atom per binding instead of once per
946    /// query. Off by default: the plan-time order stays the shipped one.
947    ///
948    /// Thread-local rather than process-wide like [`OP_FILTER_POLICY`], because
949    /// it is read once per query rather than once per join — so the argument
950    /// that made that one an atomic does not apply here — and because the
951    /// differential tests run one match set with the flag on against another
952    /// with it off, which a process-wide flag would make order-dependent under
953    /// the test harness's thread pool.
954    static RUNTIME_SCHEDULING: Cell<bool> = const { Cell::new(false) };
955}
956
957/// Turn runtime (per-binding) atom scheduling on or off for subsequent queries
958/// run through [`run_query_scheduled_into`]. Per thread, read at query start.
959pub fn set_runtime_scheduling(on: bool) {
960    RUNTIME_SCHEDULING.with(|c| c.set(on));
961}
962
963/// How the per-binding atom-order choice is selected (design chapter 20).
964///
965/// `Static` and `Runtime` fix [`runtime_scheduling`] for the whole run (the
966/// two existing flags). `Auto` decides per rule per round: the saturation
967/// driver measures each rule's worst access-path skew from the round's
968/// [`FanOuts`](crate::index::FanOuts) and sets the effective flag before the
969/// rule's queries run — skewed paths (a hub bucket) are where a static order
970/// is wrong for exactly the bindings that hit the hub, and flat paths are
971/// where the per-binding overhead buys nothing. The match set is identical in
972/// all three modes.
973#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
974pub enum SchedulingMode {
975    #[default]
976    Static,
977    Runtime,
978    Auto,
979}
980
981thread_local! {
982    static SCHEDULING_MODE: Cell<SchedulingMode> = const { Cell::new(SchedulingMode::Static) };
983}
984
985/// Select the scheduling mode (see [`SchedulingMode`]). `Static`/`Runtime`
986/// also pin the effective flag; `Auto` leaves it to the saturation driver.
987pub fn set_scheduling_mode(mode: SchedulingMode) {
988    SCHEDULING_MODE.with(|c| c.set(mode));
989    match mode {
990        SchedulingMode::Static => set_runtime_scheduling(false),
991        SchedulingMode::Runtime => set_runtime_scheduling(true),
992        SchedulingMode::Auto => {}
993    }
994}
995
996/// The selected scheduling mode.
997pub fn scheduling_mode() -> SchedulingMode {
998    SCHEDULING_MODE.with(|c| c.get())
999}
1000
1001/// Whether runtime atom scheduling is in force on this thread.
1002pub fn runtime_scheduling() -> bool {
1003    RUNTIME_SCHEDULING.with(|c| c.get())
1004}
1005
1006/// Atoms and node variables a runtime-scheduled query may have.
1007///
1008/// The scheduler state that the static scheduler keeps in two `Vec<bool>` —
1009/// which atoms are used and which variables are bound — is a pair of `u64` masks
1010/// here, because it is carried per continuation frame and keys the lowering memo. A
1011/// wider query falls back to its static plan, which is a performance decision
1012/// and not a correctness one: no rule in the corpus has more than a handful of
1013/// atoms.
1014pub const ADAPTIVE_MAX_WIDTH: usize = 64;
1015
1016/// Memo key for the eager block, in the slot that otherwise holds an atom index.
1017const EAGER: u32 = u32::MAX;
1018
1019/// One lowered block of steps, with the scheduler state it leaves behind.
1020///
1021/// `steps` is shared rather than owned because the same block is re-entered once
1022/// per partial match that reaches the same decision point, and re-lowering it
1023/// there was the whole cost this memo exists to avoid; an `Rc` clone is a
1024/// refcount bump and the borrow lives on the executing frame's stack.
1025struct Segment<Cfg: EGraphConfig, L: LitVal> {
1026    steps: std::rc::Rc<[Step<Cfg::O, Cfg::Index, L>]>,
1027    bound: u64,
1028    used: u64,
1029}
1030
1031impl<Cfg: EGraphConfig, L: LitVal> Clone for Segment<Cfg, L> {
1032    fn clone(&self) -> Self {
1033        Self {
1034            steps: self.steps.clone(),
1035            bound: self.bound,
1036            used: self.used,
1037        }
1038    }
1039}
1040
1041/// The query a runtime-scheduled execution schedules from, plus its lowering
1042/// memo.
1043///
1044/// `emit_atom`'s output is a function of the atom and of which variables are
1045/// bound when it is emitted, so a block is memoized under
1046/// `(atom, bound-mask, used-mask)` and computed once per distinct mask a run
1047/// reaches. There are few of those — a k-atom rule reaches at most the k! atom
1048/// prefixes, and in practice a handful — so the memo is a linear-scanned vector
1049/// rather than a hash map: three-word key comparisons over a few entries beat
1050/// hashing one on the per-partial-match path.
1051struct Adaptive<'q, Cfg: EGraphConfig, L: LitVal, S: Copy> {
1052    atoms: &'q [crate::resolve::RAtom<Cfg::O, S, L>],
1053    /// Atoms phase B ranges over: every atom that is not an equality. The
1054    /// equalities are the eager pass's business and are never costed, exactly
1055    /// as in the static loop's `min_by` filter.
1056    costed: u64,
1057    num_vars: usize,
1058    memo: std::cell::RefCell<Vec<((u32, u64, u64), Segment<Cfg, L>)>>,
1059}
1060
1061impl<'q, Cfg: EGraphConfig, L: LitVal, S: Copy> Adaptive<'q, Cfg, L, S> {
1062    /// Whether `rq` fits the mask width; see [`ADAPTIVE_MAX_WIDTH`].
1063    fn fits(rq: &crate::resolve::ResolvedQuery<Cfg::O, S, L>) -> bool {
1064        rq.atoms.len() <= ADAPTIVE_MAX_WIDTH && rq.shape.num_vars() <= ADAPTIVE_MAX_WIDTH
1065    }
1066
1067    fn new(rq: &'q crate::resolve::ResolvedQuery<Cfg::O, S, L>) -> Self {
1068        let mut costed = 0u64;
1069        for (i, atom) in rq.atoms.iter().enumerate() {
1070            if !matches!(
1071                atom,
1072                crate::resolve::RAtom::Eq(..)
1073                    | crate::resolve::RAtom::EqGlobal(..)
1074                    | crate::resolve::RAtom::Pred { .. }
1075            ) {
1076                costed |= 1 << i;
1077            }
1078        }
1079        Self {
1080            atoms: &rq.atoms,
1081            costed,
1082            num_vars: rq.shape.num_vars(),
1083            memo: std::cell::RefCell::new(Vec::new()),
1084        }
1085    }
1086
1087    /// The block `chosen` lowers to at `(bound, used)`: the eager fixpoint when
1088    /// `chosen` is [`EAGER`], otherwise that one atom's join and its reads.
1089    fn segment(&self, chosen: u32, bound: u64, used: u64) -> Segment<Cfg, L> {
1090        let key = (chosen, bound, used);
1091        if let Some((_, seg)) = self.memo.borrow().iter().find(|(k, _)| *k == key) {
1092            return seg.clone();
1093        }
1094        // `ADAPTIVE_MAX_WIDTH` bools of stack, in the two shapes the scheduler's
1095        // lowering takes its state in.
1096        let mut bound_buf = [false; ADAPTIVE_MAX_WIDTH];
1097        let mut used_buf = [false; ADAPTIVE_MAX_WIDTH];
1098        let bound_arr = &mut bound_buf[..self.num_vars];
1099        let used_arr = &mut used_buf[..self.atoms.len()];
1100        for (i, b) in bound_arr.iter_mut().enumerate() {
1101            *b = bound & (1 << i) != 0;
1102        }
1103        for (i, u) in used_arr.iter_mut().enumerate() {
1104            *u = used & (1 << i) != 0;
1105        }
1106        let mut steps = Vec::new();
1107        if chosen == EAGER {
1108            crate::schedule::lower_eager(self.atoms, used_arr, bound_arr, &mut steps);
1109        } else {
1110            let ai = chosen as usize;
1111            crate::schedule::emit_atom(&self.atoms[ai], ai, bound_arr, &mut steps);
1112            used_arr[ai] = true;
1113        }
1114        let seg = Segment {
1115            steps: steps.into(),
1116            bound: mask_of(bound_arr),
1117            used: mask_of(used_arr),
1118        };
1119        self.memo.borrow_mut().push((key, seg.clone()));
1120        seg
1121    }
1122}
1123
1124fn mask_of(flags: &[bool]) -> u64 {
1125    flags
1126        .iter()
1127        .enumerate()
1128        .fold(0u64, |m, (i, &b)| if b { m | (1 << i) } else { m })
1129}
1130
1131/// A position the matcher executes from: a slice of steps, and — under runtime
1132/// scheduling — what to do when it runs out.
1133///
1134/// Statically scheduled, `steps` is the whole plan and `adaptive` is `None`, so
1135/// this is the `&QueryPlan` the engine used to carry. Runtime-scheduled, `steps`
1136/// is one lowered block owned by the frame that chose it, and the masks are the
1137/// scheduler state at its end. The chain of frames on the stack is the order
1138/// chosen for the partial match under execution; a sibling binding at the same
1139/// depth may choose a different one.
1140struct Exec<'a, Cfg: EGraphConfig, L: LitVal, S: Copy> {
1141    steps: &'a [Step<Cfg::O, Cfg::Index, L>],
1142    adaptive: Option<&'a Adaptive<'a, Cfg, L, S>>,
1143    bound: u64,
1144    used: u64,
1145}
1146
1147impl<'a, Cfg: EGraphConfig, L: LitVal, S: Copy> Exec<'a, Cfg, L, S> {
1148    fn static_plan(steps: &'a [Step<Cfg::O, Cfg::Index, L>]) -> Self {
1149        Self {
1150            steps,
1151            adaptive: None,
1152            bound: 0,
1153            used: 0,
1154        }
1155    }
1156
1157    /// The empty prefix of a runtime-scheduled run: the first thing the engine
1158    /// does is hit the end of it, which is the first decision point.
1159    fn adaptive(ad: &'a Adaptive<'a, Cfg, L, S>) -> Self {
1160        Self {
1161            steps: &[],
1162            adaptive: Some(ad),
1163            bound: 0,
1164            used: 0,
1165        }
1166    }
1167}
1168
1169/// Decide what runs next, at the end of a runtime-scheduled block.
1170///
1171/// The two phases of the static scheduling loop (chapter 08), one iteration per
1172/// call, with the environment live: the eager pass to fixpoint, then the
1173/// cheapest remaining atom. The order is the same as the static one because it
1174/// is the same code lowering the same atoms; only the choice in phase B is made
1175/// from the bindings in hand rather than from a per-round average.
1176///
1177/// Both phases run against the state at the end of the current block, and the
1178/// block below is executed before the next decision, so every variable the
1179/// scheduler calls bound is actually set in `env` when phase B reads it.
1180fn advance<Cfg, L, S: Copy, const TRACK: bool, const PROOFS: bool>(
1181    ad: &Adaptive<'_, Cfg, L, S>,
1182    exec: &Exec<'_, Cfg, L, S>,
1183    eg: &EGraph<Cfg, L, TRACK, PROOFS>,
1184    index: &VariantIndex<'_, Cfg>,
1185    globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
1186    env: &mut Match<Cfg>,
1187    results: &mut MatchPool<Cfg>,
1188) where
1189    Cfg: EGraphConfig,
1190    L: LitVal,
1191    MSetCanon: VarCanon<Cfg::G, Cfg::C>,
1192{
1193    let eager = ad.segment(EAGER, exec.bound, exec.used);
1194    if !eager.steps.is_empty() {
1195        let next = Exec {
1196            steps: &eager.steps,
1197            adaptive: Some(ad),
1198            bound: eager.bound,
1199            used: eager.used,
1200        };
1201        run_step(&next, 0, eg, index, globals, env, results);
1202        return;
1203    }
1204
1205    // No atom left to schedule: every atom is used, or the ones left are
1206    // equalities between two unbound variables, which the static scheduler
1207    // leaves unenforced for the same reason (nothing else in the query binds
1208    // them). Either way the environment is a match.
1209    let Some(ai) = choose_atom(ad, exec, eg, index, globals, env) else {
1210        results.steps += 1;
1211        results.push(env);
1212        return;
1213    };
1214    let seg = ad.segment(ai as u32, exec.bound, exec.used);
1215    let next = Exec {
1216        steps: &seg.steps,
1217        adaptive: Some(ad),
1218        bound: seg.bound,
1219        used: seg.used,
1220    };
1221    run_step(&next, 0, eg, index, globals, env, results);
1222}
1223
1224/// The unused atom whose join opens the shortest cursor under the current
1225/// bindings, or `None` if none is schedulable.
1226///
1227/// Phase B of the scheduling loop with the estimator replaced by a measurement.
1228/// The static scheduler prices an atom by its relation scaled by one measured
1229/// mean fan-out per bound key (`schedule::estimate_cost`); those means are
1230/// averages over skewed distributions, so they are right about the workload and
1231/// wrong about the binding (chapter 20, Fact 2). Here the atom is priced by the
1232/// length of the shortest bucket its join would actually open, which is the
1233/// leapfrog intersection's own bound on the candidates it can propose: an upper
1234/// bound on the work, exact for a single-lookup join, and read from the buckets
1235/// the join is about to open anyway.
1236///
1237/// Ties keep the lowest atom index, so the choice is a function of the bindings
1238/// and the atom numbering and nothing else.
1239fn choose_atom<Cfg, L, S: Copy, const TRACK: bool, const PROOFS: bool>(
1240    ad: &Adaptive<'_, Cfg, L, S>,
1241    exec: &Exec<'_, Cfg, L, S>,
1242    eg: &EGraph<Cfg, L, TRACK, PROOFS>,
1243    index: &VariantIndex<'_, Cfg>,
1244    globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
1245    env: &Match<Cfg>,
1246) -> Option<usize>
1247where
1248    Cfg: EGraphConfig,
1249    L: LitVal,
1250    MSetCanon: VarCanon<Cfg::G, Cfg::C>,
1251{
1252    let candidates = ad.costed & !exec.used;
1253    // One candidate is its own minimum. Worth the branch because it is the
1254    // common case — the last atom of every rule, and both remaining atoms of a
1255    // two-atom one — and because the alternative is a bucket resolution per
1256    // lookup that `run_join` is about to repeat.
1257    if candidates.count_ones() == 1 {
1258        let ai = candidates.trailing_zeros() as usize;
1259        #[cfg(test)]
1260        ATOM_CHOICE_LOG.with(|l| l.borrow_mut().push((exec.used, ai)));
1261        return Some(ai);
1262    }
1263    let mut best: Option<(usize, usize)> = None;
1264    for ai in 0..ad.atoms.len() {
1265        if candidates & (1 << ai) == 0 {
1266            continue;
1267        }
1268        let seg = ad.segment(ai as u32, exec.bound, exec.used);
1269        let len = cursor_len(&seg, ai, eg, index, globals, env);
1270        if best.is_none_or(|(b, _)| len < b) {
1271            best = Some((len, ai));
1272        }
1273    }
1274    #[cfg(test)]
1275    if let Some((_, ai)) = best {
1276        ATOM_CHOICE_LOG.with(|l| l.borrow_mut().push((exec.used, ai)));
1277    }
1278    best.map(|(_, ai)| ai)
1279}
1280
1281#[cfg(test)]
1282thread_local! {
1283    /// One entry per phase-B decision: the atoms already scheduled, and the one
1284    /// chosen next. Drained by the tests that assert the choice is per binding;
1285    /// release has no probe on the path.
1286    static ATOM_CHOICE_LOG: std::cell::RefCell<Vec<(u64, usize)>> =
1287        const { std::cell::RefCell::new(Vec::new()) };
1288}
1289
1290/// Take and clear this thread's record of per-binding atom choices.
1291#[cfg(test)]
1292pub(crate) fn take_atom_choices() -> Vec<(u64, usize)> {
1293    ATOM_CHOICE_LOG.with(|l| std::mem::take(&mut *l.borrow_mut()))
1294}
1295
1296/// Shortest bucket the block's join would open, in the slice this atom's
1297/// semi-naive mode reads.
1298///
1299/// One `len` per lookup on buckets `run_join` is about to resolve again, which
1300/// is the same pair of reads the operator-restriction policy already makes per
1301/// binding (see [`demote_by_op`]). `FullMinusDelta` reads the full side, an
1302/// upper bound on `full ∖ delta`, for the reason given in `run_join`: a tighter
1303/// number would cost the overlap, which is the work being priced.
1304fn cursor_len<Cfg, L, S: Copy, const TRACK: bool, const PROOFS: bool>(
1305    seg: &Segment<Cfg, L>,
1306    atom_id: usize,
1307    eg: &EGraph<Cfg, L, TRACK, PROOFS>,
1308    index: &VariantIndex<'_, Cfg>,
1309    globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
1310    env: &Match<Cfg>,
1311) -> usize
1312where
1313    Cfg: EGraphConfig,
1314    L: LitVal,
1315    MSetCanon: VarCanon<Cfg::G, Cfg::C>,
1316{
1317    // Every atom phase B costs lowers to a `Join` first; the ones that do not
1318    // are the equalities, which are filtered out before this is called.
1319    let Some(Step::Join { lookups, .. }) = seg.steps.first() else {
1320        return usize::MAX;
1321    };
1322    let store = match index.mode(atom_id) {
1323        IndexMode::Delta => index.delta,
1324        IndexMode::Full | IndexMode::FullMinusDelta => index.full,
1325    };
1326    let mut best = usize::MAX;
1327    for l in lookups {
1328        let len = bucket_in(store, index, l, eg, globals, env).len();
1329        if len < best {
1330            best = len;
1331        }
1332    }
1333    best
1334}
1335
1336fn run_step<Cfg, L, S: Copy, const TRACK: bool, const PROOFS: bool>(
1337    exec: &Exec<'_, Cfg, L, S>,
1338    step_idx: usize,
1339    eg: &EGraph<Cfg, L, TRACK, PROOFS>,
1340    index: &VariantIndex<'_, Cfg>,
1341    globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
1342    env: &mut Match<Cfg>,
1343    results: &mut MatchPool<Cfg>,
1344) where
1345    Cfg: EGraphConfig,
1346    L: LitVal,
1347    MSetCanon: VarCanon<Cfg::G, Cfg::C>,
1348{
1349    if step_idx >= exec.steps.len() {
1350        // End of the step sequence. Statically scheduled, that is the whole
1351        // plan and the environment is a match; runtime-scheduled, it is a
1352        // decision point — `advance` either finds another atom to lower or
1353        // reaches the same conclusion. The step tally counts one per executed
1354        // step and one per emitted match in both modes, so the two are
1355        // comparable; the choice itself is not a step.
1356        match exec.adaptive {
1357            None => {
1358                results.steps += 1;
1359                results.push(env);
1360            }
1361            Some(ad) => advance(ad, exec, eg, index, globals, env, results),
1362        }
1363        return;
1364    }
1365    results.steps += 1;
1366
1367    match &exec.steps[step_idx] {
1368        Step::Join {
1369            target,
1370            lookups,
1371            atom_id,
1372        } => {
1373            run_join(
1374                exec, step_idx, *target, lookups, *atom_id, eg, index, globals, env, results,
1375            );
1376        }
1377        Step::ExtractChild {
1378            target,
1379            parent,
1380            pos,
1381        } => {
1382            let parent_id = env.get(*parent);
1383            let child = eg.child_at(parent_id, *pos);
1384            env.set(*target, child);
1385            run_step(exec, step_idx + 1, eg, index, globals, env, results);
1386            env.clear(*target);
1387        }
1388        Step::CheckChildEq {
1389            parent,
1390            pos,
1391            expected,
1392        } => {
1393            let parent_id = env.get(*parent);
1394            let child = eg.child_at(parent_id, *pos);
1395            let exp = env.resolve_pv(*expected, globals);
1396            if canon(index, eg, child) == canon(index, eg, exp) {
1397                run_step(exec, step_idx + 1, eg, index, globals, env, results);
1398            }
1399        }
1400        Step::CheckEq { a, b } => {
1401            if canon(index, eg, env.get(*a)) == canon(index, eg, env.get(*b)) {
1402                run_step(exec, step_idx + 1, eg, index, globals, env, results);
1403            }
1404        }
1405        Step::CheckEqGlobal { local, global } => {
1406            if canon(index, eg, env.get(*local)) == canon(index, eg, globals.binding(*global)) {
1407                run_step(exec, step_idx + 1, eg, index, globals, env, results);
1408            }
1409        }
1410        Step::BindGlobal { target, global } => {
1411            let val = canon(index, eg, globals.binding(*global));
1412            env.set(*target, val);
1413            run_step(exec, step_idx + 1, eg, index, globals, env, results);
1414            env.clear(*target);
1415        }
1416        Step::CopyBinding { target, other } => {
1417            let val = canon(index, eg, env.get(*other));
1418            env.set(*target, val);
1419            run_step(exec, step_idx + 1, eg, index, globals, env, results);
1420            env.clear(*target);
1421        }
1422        Step::ExpandA {
1423            node,
1424            children,
1425            pre,
1426            suf,
1427        } => {
1428            let node_id = env.get(*node);
1429            // Recycled through the pool: this step runs once per candidate node, so a
1430            // fresh `Vec` here was one allocation per match step (E14).
1431            let mut buf = results.take_id_buf();
1432            eg.seq_children(node_id, &mut buf);
1433            run_expand_a(
1434                exec, step_idx, children, *pre, *suf, &buf, eg, index, globals, env, results,
1435            );
1436            results.give_id_buf(buf);
1437        }
1438        Step::DecomposeAC {
1439            node,
1440            elems,
1441            rest,
1442            idempotent: _,
1443        } => {
1444            let node_id = env.get(*node);
1445            let mut residual = results.take_mset_buf();
1446            eg.mset_children(node_id, &mut residual);
1447            for entry in &mut residual {
1448                entry.0 = canon(index, eg, entry.0);
1449            }
1450            run_decompose_ac(
1451                exec,
1452                step_idx,
1453                elems,
1454                *rest,
1455                &mut residual,
1456                eg,
1457                index,
1458                globals,
1459                env,
1460                results,
1461            );
1462            results.give_mset_buf(residual);
1463        }
1464        Step::DecomposeACI { node, elems, rest } => {
1465            let node_id = env.get(*node);
1466            let mut residual = results.take_id_buf();
1467            eg.set_children(node_id, &mut residual);
1468            for entry in &mut residual {
1469                *entry = canon(index, eg, *entry);
1470            }
1471            run_decompose_aci(
1472                exec, step_idx, elems, *rest, &residual, eg, index, globals, env, results,
1473            );
1474            results.give_id_buf(residual);
1475        }
1476        Step::ExtractLitVal { node, val } => {
1477            let node_id = env.get(*node);
1478            if let Some(lit_val_id) = eg.get_lit_val_id(node_id) {
1479                env.set_lit_val(*val, lit_val_id);
1480                run_step(exec, step_idx + 1, eg, index, globals, env, results);
1481            }
1482        }
1483        Step::CheckLit { node, value } => {
1484            let node_id = env.get(*node);
1485            if eg.get_lit_val(node_id) == Some(value) {
1486                run_step(exec, step_idx + 1, eg, index, globals, env, results);
1487            }
1488        }
1489        Step::CheckPred { guard } => {
1490            if eval_guard(guard, eg, env) {
1491                run_step(exec, step_idx + 1, eg, index, globals, env, results);
1492            }
1493        }
1494    }
1495}
1496
1497/// Inline capacity for a guard's argument list; the primitives are arithmetic and
1498/// comparison, so two covers all of them (`apply::PRIM_ARGS`, same reasoning).
1499const GUARD_ARGS: usize = 2;
1500
1501/// Evaluate a guard against the current bindings.
1502///
1503/// The values come from the match's literal slots, which the guard's `deps` guarantee
1504/// are filled: the scheduler emits the check only after every `LitBind` atom feeding it
1505/// has run.
1506fn eval_guard<Cfg, L, const TRACK: bool, const PROOFS: bool>(
1507    guard: &crate::resolve::PredGuard<Cfg::O, L>,
1508    eg: &EGraph<Cfg, L, TRACK, PROOFS>,
1509    env: &Match<Cfg>,
1510) -> bool
1511where
1512    Cfg: EGraphConfig,
1513    L: LitVal,
1514    MSetCanon: VarCanon<Cfg::G, Cfg::C>,
1515{
1516    let v = eval_pred_expr(&guard.expr, eg, env);
1517    (guard.truthy)(&v)
1518}
1519
1520fn eval_pred_expr<Cfg, L, const TRACK: bool, const PROOFS: bool>(
1521    expr: &crate::resolve::RPredExpr<Cfg::O, L>,
1522    eg: &EGraph<Cfg, L, TRACK, PROOFS>,
1523    env: &Match<Cfg>,
1524) -> L
1525where
1526    Cfg: EGraphConfig,
1527    L: LitVal,
1528    MSetCanon: VarCanon<Cfg::G, Cfg::C>,
1529{
1530    use crate::resolve::RPredExpr;
1531    match expr {
1532        RPredExpr::Val(v) => eg.lits().get(env.get_lit_val(*v)).clone(),
1533        RPredExpr::Const(l) => l.clone(),
1534        RPredExpr::App { eval, args, .. } => {
1535            let vals: SmallVec<[L; GUARD_ARGS]> =
1536                args.iter().map(|a| eval_pred_expr(a, eg, env)).collect();
1537            let refs: SmallVec<[&L; GUARD_ARGS]> = vals.iter().collect();
1538            eval(&refs)
1539        }
1540    }
1541}
1542
1543// ---------------------------------------------------------------------------
1544// ExpandA — sequence (A) node decomposition
1545// ---------------------------------------------------------------------------
1546
1547fn run_expand_a<Cfg, L, S: Copy, const TRACK: bool, const PROOFS: bool>(
1548    exec: &Exec<'_, Cfg, L, S>,
1549    step_idx: usize,
1550    children: &[PatVar],
1551    pre: Option<SeqVarId>,
1552    suf: Option<SeqVarId>,
1553    seq: &[Cfg::G],
1554    eg: &EGraph<Cfg, L, TRACK, PROOFS>,
1555    index: &VariantIndex<'_, Cfg>,
1556    globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
1557    env: &mut Match<Cfg>,
1558    results: &mut MatchPool<Cfg>,
1559) where
1560    Cfg: EGraphConfig,
1561    L: LitVal,
1562    MSetCanon: VarCanon<Cfg::G, Cfg::C>,
1563{
1564    let nfixed = children.len();
1565    match (pre, suf) {
1566        (None, None) => {
1567            if seq.len() != nfixed {
1568                return;
1569            }
1570            bind_fixed_and_continue(
1571                exec, step_idx, children, seq, 0, eg, index, globals, env, results,
1572            );
1573        }
1574        (Some(p), None) => {
1575            if seq.len() < nfixed {
1576                return;
1577            }
1578            let split = seq.len() - nfixed;
1579            env.push_seq(p, &seq[..split]);
1580            bind_fixed_and_continue(
1581                exec, step_idx, children, seq, split, eg, index, globals, env, results,
1582            );
1583            env.pop_seq(p);
1584        }
1585        (None, Some(s)) => {
1586            if seq.len() < nfixed {
1587                return;
1588            }
1589            env.push_seq(s, &seq[nfixed..]);
1590            bind_fixed_and_continue(
1591                exec, step_idx, children, seq, 0, eg, index, globals, env, results,
1592            );
1593            env.pop_seq(s);
1594        }
1595        (Some(p), Some(s)) => {
1596            if seq.len() < nfixed {
1597                return;
1598            }
1599            let slack = seq.len() - nfixed;
1600            for offset in 0..=slack {
1601                env.push_seq(p, &seq[..offset]);
1602                env.push_seq(s, &seq[offset + nfixed..]);
1603                bind_fixed_and_continue(
1604                    exec, step_idx, children, seq, offset, eg, index, globals, env, results,
1605                );
1606                env.pop_seq(s);
1607                env.pop_seq(p);
1608            }
1609        }
1610    }
1611}
1612
1613/// The local variables a single fixed-child binding pass bound, in binding order.
1614/// Inline for the fixed children of a variadic pattern; a pattern with more than eight
1615/// spills to the heap.
1616type BoundHere = SmallVec<[VarId; 8]>;
1617
1618/// Unbind exactly the variables `bound` records.
1619///
1620/// A child variable already bound when a fixed-child pass runs is checked against the
1621/// node's child, not rebound: an earlier step bound it, and its value constrains this
1622/// node. Cleanup must therefore clear the variables that pass bound and no others, on
1623/// the failure path as well as after the continuation returns. Clearing every local
1624/// child instead unbinds a variable an enclosing step owns, with two consequences: a
1625/// later re-join keyed on that variable reads it as unbound and `Match::get` panics, and
1626/// the next candidate of an enclosing loop rebinds it from its own children rather than
1627/// checking it, which drops the constraint and admits matches that violate it.
1628fn unbind<Cfg: EGraphConfig>(env: &mut Match<Cfg>, bound: &BoundHere) {
1629    for &v in bound {
1630        env.clear(v);
1631    }
1632}
1633
1634fn bind_fixed_and_continue<Cfg, L, S: Copy, const TRACK: bool, const PROOFS: bool>(
1635    exec: &Exec<'_, Cfg, L, S>,
1636    step_idx: usize,
1637    children: &[PatVar],
1638    seq: &[Cfg::G],
1639    offset: usize,
1640    eg: &EGraph<Cfg, L, TRACK, PROOFS>,
1641    index: &VariantIndex<'_, Cfg>,
1642    globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
1643    env: &mut Match<Cfg>,
1644    results: &mut MatchPool<Cfg>,
1645) where
1646    Cfg: EGraphConfig,
1647    L: LitVal,
1648    MSetCanon: VarCanon<Cfg::G, Cfg::C>,
1649{
1650    let mut bound: BoundHere = BoundHere::new();
1651    for (i, &cv) in children.iter().enumerate() {
1652        let val = seq[offset + i];
1653        match cv {
1654            PatVar::Global(gid) => {
1655                if canon(index, eg, globals.binding(gid)) != canon(index, eg, val) {
1656                    unbind(env, &bound);
1657                    return;
1658                }
1659            }
1660            PatVar::Local(vid) => {
1661                if let Some(existing) = env.nodes[vid.idx()] {
1662                    if canon(index, eg, existing) != canon(index, eg, val) {
1663                        unbind(env, &bound);
1664                        return;
1665                    }
1666                } else {
1667                    env.set(vid, val);
1668                    bound.push(vid);
1669                }
1670            }
1671        }
1672    }
1673    run_step(exec, step_idx + 1, eg, index, globals, env, results);
1674    unbind(env, &bound);
1675}
1676
1677// ---------------------------------------------------------------------------
1678// DecomposeAC — multiset (AC/ACI) node decomposition
1679// ---------------------------------------------------------------------------
1680
1681/// Check whether `avail` satisfies a multiplicity requirement.
1682/// Exact(n): avail must equal n exactly.
1683/// Var with constraint: avail must be >= 1, satisfy the constraint,
1684/// and if the mult variable is already bound (non-zero), avail must
1685/// equal the bound value (non-linear variable consistency).
1686fn mult_matches(mult: &RMult, avail: u64, bound_mult: Option<u64>) -> bool {
1687    match mult {
1688        // Compared at the surface width. Narrowing `*n` to the configured
1689        // multiplicity width instead would make a literal above that width
1690        // alias onto a small multiplicity (`x:4294967297` matching 1); a
1691        // literal the configuration cannot represent simply never matches.
1692        RMult::Exact(n) => avail == *n,
1693        RMult::Var { constraint, .. } => {
1694            if avail < 1 {
1695                return false;
1696            }
1697            // Non-linear: if already bound, must match
1698            if let Some(prev) = bound_mult
1699                && prev > 0
1700                && avail != prev
1701            {
1702                return false;
1703            }
1704            match constraint {
1705                None => true,
1706                Some((op, val)) => {
1707                    let v = *val;
1708                    match op {
1709                        CmpOp::Ge => avail >= v,
1710                        CmpOp::Gt => avail > v,
1711                        CmpOp::Le => avail <= v,
1712                        CmpOp::Lt => avail < v,
1713                        CmpOp::Eq => avail == v,
1714                        CmpOp::Ne => avail != v,
1715                    }
1716                }
1717            }
1718        }
1719    }
1720}
1721
1722/// Get the currently bound multiplicity for a mult variable, if any.
1723/// Returns Some(val) where val > 0 if already bound, None otherwise.
1724fn bound_mult_val<Cfg: EGraphConfig>(mult: &RMult, env: &Match<Cfg>) -> Option<u64> {
1725    match mult {
1726        RMult::Exact(_) => None,
1727        RMult::Var { var, .. } => {
1728            let v = env.get_mult(*var).to_u64();
1729            if v > 0 { Some(v) } else { None }
1730        }
1731    }
1732}
1733fn run_decompose_ac<Cfg, L, S: Copy, const TRACK: bool, const PROOFS: bool>(
1734    exec: &Exec<'_, Cfg, L, S>,
1735    step_idx: usize,
1736    elems: &[(PatVar, RMult)],
1737    rest: Option<MsetVarId>,
1738    residual: &mut [(Cfg::G, Cfg::M)],
1739    eg: &EGraph<Cfg, L, TRACK, PROOFS>,
1740    index: &VariantIndex<'_, Cfg>,
1741    globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
1742    env: &mut Match<Cfg>,
1743    results: &mut MatchPool<Cfg>,
1744) where
1745    Cfg: EGraphConfig,
1746    L: LitVal,
1747    MSetCanon: VarCanon<Cfg::G, Cfg::C>,
1748{
1749    decompose_ac_elem(
1750        exec, step_idx, elems, 0, rest, residual, eg, index, globals, env, results,
1751    );
1752}
1753
1754fn decompose_ac_elem<Cfg, L, S: Copy, const TRACK: bool, const PROOFS: bool>(
1755    exec: &Exec<'_, Cfg, L, S>,
1756    step_idx: usize,
1757    elems: &[(PatVar, RMult)],
1758    ei: usize,
1759    rest: Option<MsetVarId>,
1760    residual: &mut [(Cfg::G, Cfg::M)],
1761    eg: &EGraph<Cfg, L, TRACK, PROOFS>,
1762    index: &VariantIndex<'_, Cfg>,
1763    globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
1764    env: &mut Match<Cfg>,
1765    results: &mut MatchPool<Cfg>,
1766) where
1767    Cfg: EGraphConfig,
1768    L: LitVal,
1769    MSetCanon: VarCanon<Cfg::G, Cfg::C>,
1770{
1771    let zero = Cfg::M::ZERO;
1772    if ei >= elems.len() {
1773        if let Some(rv) = rest {
1774            env.push_mset_residual(rv, residual);
1775            run_step(exec, step_idx + 1, eg, index, globals, env, results);
1776            env.pop_mset(rv);
1777        } else if residual.iter().all(|&(_, m)| m == zero) {
1778            run_step(exec, step_idx + 1, eg, index, globals, env, results);
1779        }
1780        return;
1781    }
1782
1783    let (var, mult) = &elems[ei];
1784
1785    let bound_repr = match *var {
1786        PatVar::Global(gid) => Some(canon(index, eg, globals.binding(gid))),
1787        PatVar::Local(vid) => env.nodes[vid.idx()].map(|v| canon(index, eg, v)),
1788    };
1789
1790    if let Some(repr) = bound_repr {
1791        if let Some(pos) = residual.iter().position(|&(r, m)| {
1792            r == repr && mult_matches(mult, m.to_u64(), bound_mult_val(mult, env))
1793        }) {
1794            let actual = residual[pos].1;
1795            let was_unbound = match mult {
1796                RMult::Var { var: mv, .. } => env.get_mult(*mv) == Cfg::M::ZERO,
1797                _ => false,
1798            };
1799            let take: Cfg::M = match mult {
1800                // `mult_matches` compared this entry against the literal at the
1801                // surface width, so an `Exact` match means the literal equals
1802                // `actual`; reuse it rather than narrowing the literal back
1803                // down, which is where the truncation used to happen.
1804                RMult::Exact(_) => actual,
1805                RMult::Var { var: mv, .. } => {
1806                    env.set_mult(*mv, actual);
1807                    actual
1808                }
1809            };
1810            let prev = residual[pos].1;
1811            residual[pos].1 = prev.saturating_sub(take);
1812            decompose_ac_elem(
1813                exec,
1814                step_idx,
1815                elems,
1816                ei + 1,
1817                rest,
1818                residual,
1819                eg,
1820                index,
1821                globals,
1822                env,
1823                results,
1824            );
1825            residual[pos].1 = prev;
1826            if was_unbound && let RMult::Var { var: mv, .. } = mult {
1827                env.set_mult(*mv, Cfg::M::ZERO);
1828            }
1829        }
1830        return;
1831    }
1832
1833    let n = residual.len();
1834    for ri in 0..n {
1835        let (repr, avail) = residual[ri];
1836        if !mult_matches(mult, avail.to_u64(), bound_mult_val(mult, env)) {
1837            continue;
1838        }
1839        let PatVar::Local(vid) = *var else {
1840            unreachable!()
1841        };
1842        env.set(vid, repr);
1843        let was_unbound = match mult {
1844            RMult::Var { var: mv, .. } => env.get_mult(*mv) == Cfg::M::ZERO,
1845            _ => false,
1846        };
1847        let take: Cfg::M = match mult {
1848            // See the bound-repr path above: an `Exact` match means the literal
1849            // equals `avail` at the surface width.
1850            RMult::Exact(_) => avail,
1851            RMult::Var { var: mv, .. } => {
1852                env.set_mult(*mv, avail);
1853                avail
1854            }
1855        };
1856        let prev = residual[ri].1;
1857        residual[ri].1 = prev.saturating_sub(take);
1858        decompose_ac_elem(
1859            exec,
1860            step_idx,
1861            elems,
1862            ei + 1,
1863            rest,
1864            residual,
1865            eg,
1866            index,
1867            globals,
1868            env,
1869            results,
1870        );
1871        residual[ri].1 = prev;
1872        env.clear(vid);
1873        if was_unbound && let RMult::Var { var: mv, .. } = mult {
1874            env.set_mult(*mv, Cfg::M::ZERO);
1875        }
1876    }
1877}
1878
1879// ---------------------------------------------------------------------------
1880// DecomposeACI — set node decomposition
1881// ---------------------------------------------------------------------------
1882
1883fn run_decompose_aci<Cfg, L, S: Copy, const TRACK: bool, const PROOFS: bool>(
1884    exec: &Exec<'_, Cfg, L, S>,
1885    step_idx: usize,
1886    elems: &[PatVar],
1887    rest: Option<SetVarId>,
1888    residual: &[Cfg::G],
1889    eg: &EGraph<Cfg, L, TRACK, PROOFS>,
1890    index: &VariantIndex<'_, Cfg>,
1891    globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
1892    env: &mut Match<Cfg>,
1893    results: &mut MatchPool<Cfg>,
1894) where
1895    Cfg: EGraphConfig,
1896    L: LitVal,
1897    MSetCanon: VarCanon<Cfg::G, Cfg::C>,
1898{
1899    let mut used = crate::containers::bitset::BitSet::new(residual.len());
1900    decompose_aci_elem(
1901        exec, step_idx, elems, 0, rest, residual, &mut used, eg, index, globals, env, results,
1902    );
1903}
1904
1905fn decompose_aci_elem<Cfg, L, S: Copy, const TRACK: bool, const PROOFS: bool>(
1906    exec: &Exec<'_, Cfg, L, S>,
1907    step_idx: usize,
1908    elems: &[PatVar],
1909    ei: usize,
1910    rest: Option<SetVarId>,
1911    residual: &[Cfg::G],
1912    used: &mut crate::containers::bitset::BitSet,
1913    eg: &EGraph<Cfg, L, TRACK, PROOFS>,
1914    index: &VariantIndex<'_, Cfg>,
1915    globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
1916    env: &mut Match<Cfg>,
1917    results: &mut MatchPool<Cfg>,
1918) where
1919    Cfg: EGraphConfig,
1920    L: LitVal,
1921    MSetCanon: VarCanon<Cfg::G, Cfg::C>,
1922{
1923    if ei >= elems.len() {
1924        if let Some(rv) = rest {
1925            env.push_set_residual(rv, residual, used);
1926            run_step(exec, step_idx + 1, eg, index, globals, env, results);
1927            env.pop_set(rv);
1928        } else if (0..residual.len()).all(|i| used.test(i)) {
1929            run_step(exec, step_idx + 1, eg, index, globals, env, results);
1930        }
1931        return;
1932    }
1933
1934    let var = elems[ei];
1935    let bound_repr = match var {
1936        PatVar::Global(gid) => Some(canon(index, eg, globals.binding(gid))),
1937        PatVar::Local(vid) => env.nodes[vid.idx()].map(|v| canon(index, eg, v)),
1938    };
1939
1940    if let Some(repr) = bound_repr {
1941        if let Some(pos) = residual
1942            .iter()
1943            .enumerate()
1944            .position(|(i, &r)| !used.test(i) && r == repr)
1945        {
1946            used.set(pos);
1947            decompose_aci_elem(
1948                exec,
1949                step_idx,
1950                elems,
1951                ei + 1,
1952                rest,
1953                residual,
1954                used,
1955                eg,
1956                index,
1957                globals,
1958                env,
1959                results,
1960            );
1961            used.clear(pos);
1962        }
1963        return;
1964    }
1965
1966    let PatVar::Local(vid) = var else {
1967        unreachable!()
1968    };
1969    for ri in 0..residual.len() {
1970        if used.test(ri) {
1971            continue;
1972        }
1973        env.set(vid, residual[ri]);
1974        used.set(ri);
1975        decompose_aci_elem(
1976            exec,
1977            step_idx,
1978            elems,
1979            ei + 1,
1980            rest,
1981            residual,
1982            used,
1983            eg,
1984            index,
1985            globals,
1986            env,
1987            results,
1988        );
1989        used.clear(ri);
1990        env.clear(vid);
1991    }
1992}
1993
1994// ---------------------------------------------------------------------------
1995// Join — leapfrog intersection of index lookups
1996// ---------------------------------------------------------------------------
1997
1998/// Relation size per candidate above which a join applies its operator
1999/// restriction as a per-candidate test rather than as a leapfrog operand, and
2000/// the ceiling that threshold stops climbing at.
2001///
2002/// The two mechanisms are priced by two lengths the join reads before it opens
2003/// anything: `m`, the smallest of the atom's other buckets, which bounds the
2004/// candidates the ring will propose, and `n = |by_op[op]|`. The test costs `m`
2005/// random loads into the round's `op` table. The operand costs a fixed start-up,
2006/// a sort of the ring plus a gallop of the `by_op` cursor to the bucket's first
2007/// key, plus one iteration per element of the smaller side, `min(m, n)`. The
2008/// rule is
2009///
2010/// ```text
2011/// filter  iff  n >= min(512 * m, 131_072)  and  m <= 2 * n
2012/// ```
2013///
2014/// The first condition prevents a per-candidate test when the operator relation
2015/// is small enough to be the better intersection driver. The second prevents
2016/// the test from scaling with an enormous candidate bucket after the relation
2017/// side has become the tighter bound. Chapter 20 records the design boundary;
2018/// deterministic tests pin the rule and set equivalence.
2019const OP_FILTER_RELATION_PER_CANDIDATE: usize = 512;
2020
2021/// Ceiling on the fitted threshold; see `OP_FILTER_RELATION_PER_CANDIDATE`.
2022pub const OP_FILTER_MIN_RELATION: usize = 131_072;
2023
2024/// Relative work bound used to stop filtering when the candidate bucket grows
2025/// beyond twice the operator relation.
2026const OP_FILTER_SEEK_COST: usize = 2;
2027
2028/// Which mechanism a join uses for its `ByOp` restriction.
2029#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2030pub enum OpFilterPolicy {
2031    /// Decide per binding from the two bucket lengths. The shipped policy; see
2032    /// [`OP_FILTER_MIN_RELATION`].
2033    Adaptive,
2034    /// Always demote `ByOp` to a per-candidate operator test.
2035    AlwaysFilter,
2036    /// Always keep `ByOp` in the leapfrog ring.
2037    AlwaysLeapfrog,
2038}
2039
2040/// The live policy. Tests can pin either equivalent mechanism. It is read once
2041/// per query into [`MatchPool`], never per join, so the atomic load stays off the
2042/// per-partial-match path.
2043static OP_FILTER_POLICY: AtomicUsize = AtomicUsize::new(0);
2044
2045/// Pin the operator-restriction policy for subsequent queries. Process-wide, and
2046/// read at query start.
2047pub fn set_op_filter_policy(p: OpFilterPolicy) {
2048    OP_FILTER_POLICY.store(
2049        match p {
2050            OpFilterPolicy::Adaptive => 0,
2051            OpFilterPolicy::AlwaysFilter => 1,
2052            OpFilterPolicy::AlwaysLeapfrog => 2,
2053        },
2054        Ordering::Relaxed,
2055    );
2056}
2057
2058/// The operator-restriction policy in force.
2059pub fn op_filter_policy() -> OpFilterPolicy {
2060    match OP_FILTER_POLICY.load(Ordering::Relaxed) {
2061        1 => OpFilterPolicy::AlwaysFilter,
2062        2 => OpFilterPolicy::AlwaysLeapfrog,
2063        _ => OpFilterPolicy::Adaptive,
2064    }
2065}
2066
2067/// Which mechanism a join applied its `ByOp` restriction with. Recorded per
2068/// join execution in test builds only; release has no probe on the path.
2069#[cfg(test)]
2070#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2071pub(crate) enum OpRestriction {
2072    /// `ByOp` stayed in the leapfrog ring as an intersection operand.
2073    Leapfrog,
2074    /// `ByOp` was demoted to a per-candidate `op[id]` test.
2075    Filter,
2076}
2077
2078#[cfg(test)]
2079thread_local! {
2080    /// One entry per join execution that had a `ByOp` restriction to place.
2081    /// Drained by the policy tests; see `op_restriction_log`.
2082    static OP_RESTRICTION_LOG: std::cell::RefCell<Vec<OpRestriction>> =
2083        const { std::cell::RefCell::new(Vec::new()) };
2084}
2085
2086/// Take and clear this thread's record of per-join restriction decisions.
2087#[cfg(test)]
2088pub(crate) fn take_op_restriction_log() -> Vec<OpRestriction> {
2089    OP_RESTRICTION_LOG.with(|l| std::mem::take(&mut *l.borrow_mut()))
2090}
2091
2092/// Decide how this join places its `ByOp` restriction: `true` to demote it to a
2093/// per-candidate operator test, `false` to keep it as a leapfrog operand.
2094///
2095/// `m` is the smallest of the atom's other buckets, `usize::MAX` when it has
2096/// none; `n` is `|by_op[op]|`, or `None` when the join has no `ByOp` to place,
2097/// which is a single-lookup `ByOp` scan: it has to stay a cursor because it is
2098/// the only thing enumerating anything. Two compares and a shift on values already
2099/// in registers; see [`OP_FILTER_RELATION_PER_CANDIDATE`] for where they come
2100/// from.
2101#[inline]
2102fn demote_by_op(m: usize, n: Option<usize>, policy: OpFilterPolicy) -> bool {
2103    let Some(n) = n else { return false };
2104    let demote = match policy {
2105        OpFilterPolicy::AlwaysFilter => true,
2106        OpFilterPolicy::AlwaysLeapfrog => false,
2107        OpFilterPolicy::Adaptive => {
2108            n >= OP_FILTER_MIN_RELATION.min(m.saturating_mul(OP_FILTER_RELATION_PER_CANDIDATE))
2109                && m <= n.saturating_mul(OP_FILTER_SEEK_COST)
2110        }
2111    };
2112    #[cfg(test)]
2113    OP_RESTRICTION_LOG.with(|l| {
2114        l.borrow_mut().push(if demote {
2115            OpRestriction::Filter
2116        } else {
2117            OpRestriction::Leapfrog
2118        })
2119    });
2120    demote
2121}
2122
2123/// Turn a resolved bucket into a cursor; an absent key resolves to the empty
2124/// slice, hence to an empty cursor.
2125///
2126/// The cursor type is [`Probed`], which is `SortedVecCursor` itself unless the
2127/// `seek-stats` feature is on; see `leapfrog::seek_stats`. This function and
2128/// [`cursor_in`] are the two places the push-based matcher opens an index
2129/// bucket, so wrapping them counts every seek the join layer issues.
2130#[inline]
2131fn cursor_of<G: crate::containers::DenseId>(b: &[G]) -> Probed<'_, G> {
2132    Probed::new(b)
2133}
2134
2135fn run_join<Cfg, L, S: Copy, const TRACK: bool, const PROOFS: bool>(
2136    exec: &Exec<'_, Cfg, L, S>,
2137    step_idx: usize,
2138    target: VarId,
2139    lookups: &[IndexLookup<Cfg::O, Cfg::Index>],
2140    atom_id: usize,
2141    eg: &EGraph<Cfg, L, TRACK, PROOFS>,
2142    index: &VariantIndex<'_, Cfg>,
2143    globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
2144    env: &mut Match<Cfg>,
2145    results: &mut MatchPool<Cfg>,
2146) where
2147    Cfg: EGraphConfig,
2148    L: LitVal,
2149    MSetCanon: VarCanon<Cfg::G, Cfg::C>,
2150{
2151    if lookups.is_empty() {
2152        // No constraints — preserve original behavior (no match emitted).
2153        return;
2154    }
2155    // Every `Step::Join` the scheduler emits carries exactly one `ByOp`: it is
2156    // the first lookup at all eight emission sites in `schedule.rs`, and none of
2157    // them appends a second. The demotion below relies on that: it takes one
2158    // `ByOp` out of the ring and covers it with the per-candidate test, so a
2159    // second one would silently stay a cursor while the first became a filter,
2160    // which is a different split, still sound but unpriced.
2161    debug_assert_eq!(
2162        lookups
2163            .iter()
2164            .filter(|l| matches!(l, IndexLookup::ByOp { .. }))
2165            .count(),
2166        1,
2167        "a join's lookups must carry exactly one ByOp"
2168    );
2169    // A `ByOp` lookup in a join that has a narrower lookup too can be applied
2170    // two ways, and which is cheaper depends on the binding, not on the atom.
2171    //
2172    // `IndexStore::build_from` files every non-subsumed node into `by_op` and
2173    // into its `by_repr` / `by_child_pos` / `by_contains` buckets from one id
2174    // stream, so for any other bucket `B` of the same store
2175    // `by_op[o] ∩ B = { n ∈ B : op(n) = o }`: the intersection and the test are
2176    // the same set. They are not the same cost. Demoting `by_op[o]` to a test
2177    // costs one `op[id]` load per element of `B`, whatever the intersection
2178    // turns out to be. Keeping it in the leapfrog ring costs one iteration per
2179    // element of the *smaller* of `B` and `by_op[o]`, because a seek from either
2180    // side clears every key of the other side below it in one step, and each is a
2181    // doubling gallop plus a bisection over the two vectors. So the ring wins when
2182    // `by_op[o]` is small, both because it does less work and because its
2183    // working set stays in cache, and `|B|` and `|by_op[o]|` are `len` reads on
2184    // buckets the join is opening anyway (see `OP_FILTER_RELATION_PER_CANDIDATE`
2185    // for the measured crossover and the rule fitted to it).
2186    //
2187    // The set identity holds in each of the three modes because the delta store
2188    // is built by the same `build_from` over the same e-graph: a node in
2189    // `full.B ∖ delta.B` cannot be in the delta id stream at all (if it were,
2190    // the same child/class/op reads that put it in `full.B` would have put it
2191    // in `delta.B`), so it is not in `delta.by_op[o]` either.
2192    let op_pos = if lookups.len() > 1 {
2193        lookups
2194            .iter()
2195            .position(|l| matches!(l, IndexLookup::ByOp { .. }))
2196    } else {
2197        None
2198    };
2199    let policy = results.op_filter_policy;
2200
2201    // One pass per mode: resolve the `ByOp` bucket for its length, then resolve
2202    // and open the other lookups while tracking the smallest of them, and put
2203    // the `ByOp` cursor back in the ring only if the decision keeps it. The ring
2204    // is sorted by key at construction, so appending it last is the same join.
2205    //
2206    // The mode is fixed for the whole atom (all its lookups read the same
2207    // flavor); see design doc "How a Variant Executes".
2208    macro_rules! dispatch {
2209        ($store:expr, $open:expr) => {{
2210            let store = $store;
2211            let mut m = usize::MAX;
2212            let mut cursors = CursorVec::new();
2213            for (i, l) in lookups.iter().enumerate() {
2214                if Some(i) == op_pos {
2215                    continue;
2216                }
2217                let b = bucket_in(store, index, l, eg, globals, env);
2218                let len = b.len();
2219                if len < m {
2220                    m = len;
2221                }
2222                cursors.push($open(b, l));
2223            }
2224            let op_bucket = op_pos.map(|p| bucket_in(store, index, &lookups[p], eg, globals, env));
2225            let op_filter = if demote_by_op(m, op_bucket.map(|b| b.len()), policy) {
2226                match &lookups[op_pos.expect("a demoted join has a ByOp lookup")] {
2227                    IndexLookup::ByOp { op } => Some(*op),
2228                    _ => unreachable!("op_pos indexes a ByOp lookup"),
2229                }
2230            } else {
2231                if let (Some(b), Some(p)) = (op_bucket, op_pos) {
2232                    cursors.push($open(b, &lookups[p]));
2233                }
2234                None
2235            };
2236            leapfrog_join(
2237                cursors, op_filter, exec, step_idx, target, eg, index, globals, env, results,
2238            );
2239        }};
2240    }
2241
2242    match index.mode(atom_id) {
2243        IndexMode::Full => dispatch!(index.full, |b, _l| cursor_of(b)),
2244        IndexMode::Delta => dispatch!(index.delta, |b, _l| cursor_of(b)),
2245        // The candidate set is `full ∖ delta`, so the full-side length is an
2246        // upper bound on it and the decision reads that. A tighter estimate
2247        // would need the delta bucket's overlap, which is the work being priced.
2248        IndexMode::FullMinusDelta => dispatch!(index.full, |b, l| Difference::new(
2249            cursor_of(b),
2250            cursor_in(index.delta, index, l, eg, globals, env)
2251        )),
2252    }
2253}
2254
2255/// Resolve one lookup's key against a single index store, returning the bucket
2256/// it selects (the empty slice if the key names no bucket of this build).
2257///
2258/// `store` is the slice this atom's mode reads (full or delta); `index` is the
2259/// round's view, consulted only for the canonicalization the buckets are keyed
2260/// by (see [`canon`]). Kept apart from [`cursor_of`] because `run_join` reads
2261/// each bucket's length before it decides which buckets become cursors, and
2262/// resolving twice would repeat the canonicalization and the hash probe.
2263fn bucket_in<'a, Cfg, L, S: Copy, const TRACK: bool, const PROOFS: bool>(
2264    store: &'a IndexStore<Cfg>,
2265    index: &VariantIndex<'_, Cfg>,
2266    l: &IndexLookup<Cfg::O, Cfg::Index>,
2267    eg: &EGraph<Cfg, L, TRACK, PROOFS>,
2268    globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
2269    env: &Match<Cfg>,
2270) -> &'a [Cfg::G]
2271where
2272    Cfg: EGraphConfig,
2273    L: LitVal,
2274    MSetCanon: VarCanon<Cfg::G, Cfg::C>,
2275{
2276    match l {
2277        IndexLookup::ByOp { op } => store.nodes_by_op(*op),
2278        IndexLookup::ByChildPos { child, pos } => {
2279            let r = canon(index, eg, env.resolve_pv(*child, globals));
2280            store.nodes_by_child_pos(r, *pos)
2281        }
2282        IndexLookup::ByRepr { repr } => {
2283            let r = canon(index, eg, env.get(*repr));
2284            store.nodes_by_repr(r)
2285        }
2286        IndexLookup::ByContains { child } => {
2287            let r = canon(index, eg, env.resolve_pv(*child, globals));
2288            store.nodes_by_contains(r)
2289        }
2290    }
2291}
2292
2293/// [`bucket_in`] followed by [`cursor_of`], for the one caller that needs no
2294/// length: the delta side of a `FullMinusDelta` cursor, which is subtracted
2295/// rather than enumerated.
2296fn cursor_in<'a, Cfg, L, S: Copy, const TRACK: bool, const PROOFS: bool>(
2297    store: &'a IndexStore<Cfg>,
2298    index: &VariantIndex<'_, Cfg>,
2299    l: &IndexLookup<Cfg::O, Cfg::Index>,
2300    eg: &EGraph<Cfg, L, TRACK, PROOFS>,
2301    globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
2302    env: &Match<Cfg>,
2303) -> Probed<'a, Cfg::G>
2304where
2305    Cfg: EGraphConfig,
2306    L: LitVal,
2307    MSetCanon: VarCanon<Cfg::G, Cfg::C>,
2308{
2309    cursor_of(bucket_in(store, index, l, eg, globals, env))
2310}
2311
2312/// Run a leapfrog intersection over `cursors` (any `SortedCursor` flavor),
2313/// binding `target` to each match and recursing into the next step.
2314///
2315/// `op_filter` carries the operator of a `ByOp` lookup that `run_join` left out
2316/// of `cursors`; a candidate whose operator differs is skipped without being
2317/// bound or counted as a match step (see `run_join` for why the two forms agree).
2318fn leapfrog_join<Cfg, L, S: Copy, C, const TRACK: bool, const PROOFS: bool>(
2319    cursors: CursorVec<C>,
2320    op_filter: Option<Cfg::O>,
2321    exec: &Exec<'_, Cfg, L, S>,
2322    step_idx: usize,
2323    target: VarId,
2324    eg: &EGraph<Cfg, L, TRACK, PROOFS>,
2325    index: &VariantIndex<'_, Cfg>,
2326    globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
2327    env: &mut Match<Cfg>,
2328    results: &mut MatchPool<Cfg>,
2329) where
2330    Cfg: EGraphConfig,
2331    L: LitVal,
2332    C: SortedCursor<Key = Cfg::G>,
2333    MSetCanon: VarCanon<Cfg::G, Cfg::C>,
2334{
2335    // `target` may already be bound: the bound-node re-join (`ByRepr ∩ ByOp`, emitted by
2336    // `emit_variadic_join`/`try_schedule_bound` when a variadic atom's node was bound by an
2337    // upstream `ExtractChild`) has `target` already set, and an enclosing step relies on
2338    // that binding. Save it and restore on exit, so this join's per-key `set`/`clear` does
2339    // not destroy a binding a sibling iteration of an upstream join still needs. (Plain
2340    // unbound joins have `prev == None`, so this reduces to the old set/clear.)
2341    let prev = env.get_opt(target);
2342    let mut join = LeapfrogJoin::new(cursors);
2343    while join.is_valid() {
2344        let id = join.key();
2345        if op_filter.is_none_or(|o| index.full.round_op(id).unwrap_or_else(|| eg.node_op(id)) == o)
2346        {
2347            env.set(target, id);
2348            run_step(exec, step_idx + 1, eg, index, globals, env, results);
2349        }
2350        join.next();
2351    }
2352    env.set_opt(target, prev);
2353}
2354
2355// ---------------------------------------------------------------------------
2356// MatchIterator — explicit DFS stack machine (lazy, pull-based)
2357// ---------------------------------------------------------------------------
2358
2359/// Resolve an `IndexLookup` to a bucket slice from the **full** index (the
2360/// pull-based engine runs naive only — see semi-naive design notes).
2361/// Returns the empty slice when the lookup key names no bucket (i.e. no matches).
2362fn resolve_lookup<'a, Cfg: EGraphConfig, L: LitVal, S: Copy, const T: bool, const P: bool>(
2363    l: &IndexLookup<Cfg::O, Cfg::Index>,
2364    eg: &EGraph<Cfg, L, T, P>,
2365    index: &'a VariantIndex<'a, Cfg>,
2366    globals: &crate::resolve::GlobalCtx<S, Cfg::G>,
2367    env: &Match<Cfg>,
2368) -> &'a [Cfg::G]
2369where
2370    MSetCanon: VarCanon<Cfg::G, Cfg::C>,
2371{
2372    match l {
2373        IndexLookup::ByOp { op } => index.full.nodes_by_op(*op),
2374        IndexLookup::ByChildPos { child, pos } => {
2375            let r = canon(index, eg, env.resolve_pv(*child, globals));
2376            index.full.nodes_by_child_pos(r, *pos)
2377        }
2378        IndexLookup::ByRepr { repr } => {
2379            let r = canon(index, eg, env.get(*repr));
2380            index.full.nodes_by_repr(r)
2381        }
2382        IndexLookup::ByContains { child } => {
2383            let r = canon(index, eg, env.resolve_pv(*child, globals));
2384            index.full.nodes_by_contains(r)
2385        }
2386    }
2387}
2388
2389enum FrameKind<'a, Cfg: EGraphConfig> {
2390    Join {
2391        target: VarId,
2392        join: LeapfrogJoin<SortedVecCursor<'a, Cfg::G>>,
2393    },
2394    SlidingWindow {
2395        children: Vec<PatVar>,
2396        pre: SeqVarId,
2397        suf: SeqVarId,
2398        seq: Vec<Cfg::G>,
2399        offset: usize,
2400        slack: usize,
2401        /// The local children the current offset's `bind_fixed` bound, which are the
2402        /// ones this frame unbinds when it advances or is dropped.
2403        bound: BoundHere,
2404    },
2405    ACDecompose {
2406        elems: Vec<(PatVar, RMult)>,
2407        rest: Option<MsetVarId>,
2408        residual: Vec<(Cfg::G, Cfg::M)>,
2409        ri_at: Vec<usize>,
2410        /// Per element, whether the scan bound its variable, which is the condition for
2411        /// the undo to unbind it.
2412        bound: Vec<bool>,
2413        ei: usize,
2414    },
2415    ACIDecompose {
2416        elems: Vec<PatVar>,
2417        rest: Option<SetVarId>,
2418        residual: Vec<Cfg::G>,
2419        used: crate::containers::bitset::BitSet,
2420        ri_at: Vec<usize>,
2421        /// Per element, whether the scan bound its variable.
2422        bound: Vec<bool>,
2423        ei: usize,
2424    },
2425}
2426
2427struct Frame<'a, Cfg: EGraphConfig> {
2428    kind: FrameKind<'a, Cfg>,
2429    step_idx: usize,
2430}
2431
2432pub struct MatchIterator<'a, Cfg: EGraphConfig, L: LitVal, S: Copy, const T: bool, const P: bool> {
2433    plan: &'a QueryPlan<Cfg::O, Cfg::Index, L>,
2434    eg: &'a EGraph<Cfg, L, T, P>,
2435    index: &'a VariantIndex<'a, Cfg>,
2436    globals: &'a crate::resolve::GlobalCtx<S, Cfg::G>,
2437    env: Match<Cfg>,
2438    frames: Vec<Frame<'a, Cfg>>,
2439    /// Next plan step to enter (usize::MAX = must backtrack after yield).
2440    cursor: usize,
2441    done: bool,
2442}
2443
2444impl<'a, Cfg, L, S: Copy, const T: bool, const P: bool> MatchIterator<'a, Cfg, L, S, T, P>
2445where
2446    Cfg: EGraphConfig,
2447    L: LitVal,
2448    MSetCanon: VarCanon<Cfg::G, Cfg::C>,
2449{
2450    pub fn new(
2451        plan: &'a QueryPlan<Cfg::O, Cfg::Index, L>,
2452        eg: &'a EGraph<Cfg, L, T, P>,
2453        index: &'a VariantIndex<'a, Cfg>,
2454        globals: &'a crate::resolve::GlobalCtx<S, Cfg::G>,
2455    ) -> Self {
2456        Self {
2457            plan,
2458            eg,
2459            index,
2460            globals,
2461            env: Match::new(&plan.shape),
2462            frames: Vec::new(),
2463            cursor: 0,
2464            done: false,
2465        }
2466    }
2467
2468    pub fn env(&self) -> &Match<Cfg> {
2469        &self.env
2470    }
2471
2472    /// Composable iterator that clones each match on yield.
2473    pub fn cloned_iter(self) -> ClonedMatchIter<'a, Cfg, L, S, T, P> {
2474        ClonedMatchIter { inner: self }
2475    }
2476
2477    /// Collect all remaining matches into a `MatchSet`.
2478    pub fn collect_set(&mut self, shape: &crate::resolve::MatchShape) -> MatchSet<Cfg> {
2479        let mut set = MatchSet::new(shape);
2480        while self.next_match() {
2481            set.push(&self.env);
2482        }
2483        set
2484    }
2485
2486    /// Advance to the next match. Returns true if found (read via `env()`).
2487    pub fn next_match(&mut self) -> bool {
2488        if self.done {
2489            return false;
2490        }
2491
2492        // If we just yielded, backtrack from the end.
2493        if self.cursor == usize::MAX && !self.backtrack() {
2494            self.done = true;
2495            return false;
2496        }
2497
2498        loop {
2499            // Complete match?
2500            if self.cursor >= self.plan.steps.len() {
2501                self.cursor = usize::MAX;
2502                return true;
2503            }
2504
2505            match self.enter() {
2506                Enter::Advanced => continue,
2507                Enter::Failed => {
2508                    if !self.backtrack() {
2509                        self.done = true;
2510                        return false;
2511                    }
2512                }
2513                Enter::Pushed(true) => {
2514                    self.cursor += 1;
2515                    continue;
2516                }
2517                Enter::Pushed(false) => {
2518                    self.frames.pop();
2519                    if !self.backtrack() {
2520                        self.done = true;
2521                        return false;
2522                    }
2523                }
2524            }
2525        }
2526    }
2527
2528    /// Try to enter `plan.steps[self.cursor]`.
2529    fn enter(&mut self) -> Enter {
2530        match &self.plan.steps[self.cursor] {
2531            Step::ExtractChild {
2532                target,
2533                parent,
2534                pos,
2535            } => {
2536                let child = self.eg.child_at(self.env.get(*parent), *pos);
2537                self.env.set(*target, child);
2538                self.cursor += 1;
2539                Enter::Advanced
2540            }
2541            Step::CheckChildEq {
2542                parent,
2543                pos,
2544                expected,
2545            } => {
2546                let child = self.eg.child_at(self.env.get(*parent), *pos);
2547                if canon(self.index, self.eg, child)
2548                    == canon(
2549                        self.index,
2550                        self.eg,
2551                        self.env.resolve_pv(*expected, self.globals),
2552                    )
2553                {
2554                    self.cursor += 1;
2555                    Enter::Advanced
2556                } else {
2557                    Enter::Failed
2558                }
2559            }
2560            Step::CheckEq { a, b } => {
2561                if canon(self.index, self.eg, self.env.get(*a))
2562                    == canon(self.index, self.eg, self.env.get(*b))
2563                {
2564                    self.cursor += 1;
2565                    Enter::Advanced
2566                } else {
2567                    Enter::Failed
2568                }
2569            }
2570            Step::BindGlobal { target, global } => {
2571                let val = canon(self.index, self.eg, self.globals.binding(*global));
2572                self.env.set(*target, val);
2573                self.cursor += 1;
2574                Enter::Advanced
2575            }
2576            Step::CheckEqGlobal { local, global } => {
2577                if canon(self.index, self.eg, self.env.get(*local))
2578                    == canon(self.index, self.eg, self.globals.binding(*global))
2579                {
2580                    self.cursor += 1;
2581                    Enter::Advanced
2582                } else {
2583                    Enter::Failed
2584                }
2585            }
2586            Step::CopyBinding { target, other } => {
2587                self.env
2588                    .set(*target, canon(self.index, self.eg, self.env.get(*other)));
2589                self.cursor += 1;
2590                Enter::Advanced
2591            }
2592            Step::Join {
2593                target, lookups, ..
2594            } => {
2595                let target = *target;
2596                let lookups = lookups.clone();
2597                self.enter_join(target, &lookups)
2598            }
2599            Step::ExpandA {
2600                node,
2601                children,
2602                pre,
2603                suf,
2604            } => {
2605                let node_id = self.env.get(*node);
2606                let mut seq = Vec::new();
2607                self.eg.seq_children(node_id, &mut seq);
2608                let children = children.clone();
2609                let pre = *pre;
2610                let suf = *suf;
2611                self.enter_expand_a(&children, pre, suf, seq)
2612            }
2613            Step::DecomposeAC {
2614                node, elems, rest, ..
2615            } => {
2616                let node_id = self.env.get(*node);
2617                let mut residual = Vec::new();
2618                self.eg.mset_children(node_id, &mut residual);
2619                for e in &mut residual {
2620                    e.0 = canon(self.index, self.eg, e.0);
2621                }
2622                let elems = elems.clone();
2623                let rest = *rest;
2624                self.enter_ac(&elems, rest, residual)
2625            }
2626            Step::DecomposeACI { node, elems, rest } => {
2627                let node_id = self.env.get(*node);
2628                let mut residual = Vec::new();
2629                self.eg.set_children(node_id, &mut residual);
2630                for e in &mut residual {
2631                    *e = canon(self.index, self.eg, *e);
2632                }
2633                let elems = elems.clone();
2634                let rest = *rest;
2635                self.enter_aci(&elems, rest, residual)
2636            }
2637            Step::ExtractLitVal { node, val } => {
2638                let node_id = self.env.get(*node);
2639                if let Some(lit_val_id) = self.eg.get_lit_val_id(node_id) {
2640                    self.env.set_lit_val(*val, lit_val_id);
2641                    self.cursor += 1;
2642                    Enter::Advanced
2643                } else {
2644                    Enter::Failed
2645                }
2646            }
2647            Step::CheckLit { node, value } => {
2648                let node_id = self.env.get(*node);
2649                if self.eg.get_lit_val(node_id) == Some(value) {
2650                    self.cursor += 1;
2651                    Enter::Advanced
2652                } else {
2653                    Enter::Failed
2654                }
2655            }
2656            Step::CheckPred { guard } => {
2657                if eval_guard(guard, self.eg, &self.env) {
2658                    self.cursor += 1;
2659                    Enter::Advanced
2660                } else {
2661                    Enter::Failed
2662                }
2663            }
2664        }
2665    }
2666
2667    fn enter_join(&mut self, target: VarId, lookups: &[IndexLookup<Cfg::O, Cfg::Index>]) -> Enter {
2668        // Collected straight into cursors: `resolve_lookup` borrows from the
2669        // index's pool, which outlives the frame, so there is no intermediate
2670        // vector of bucket references. An empty bucket short-circuits the whole
2671        // join, as the absent key it stands for did before the families became
2672        // dense: the intersection is empty either way, and failing here keeps
2673        // the frame off the stack.
2674        let mut iters: CursorVec<SortedVecCursor<'a, Cfg::G>> = CursorVec::new();
2675        for l in lookups {
2676            let b = resolve_lookup(l, self.eg, self.index, self.globals, &self.env);
2677            if b.is_empty() {
2678                return Enter::Failed;
2679            }
2680            iters.push(SortedVecCursor::new(b));
2681        }
2682        if iters.is_empty() {
2683            return Enter::Failed;
2684        }
2685        let join = LeapfrogJoin::new(iters);
2686        let valid = join.is_valid();
2687        if valid {
2688            self.env.set(target, join.key());
2689        }
2690        self.frames.push(Frame {
2691            kind: FrameKind::Join { target, join },
2692            step_idx: self.cursor,
2693        });
2694        Enter::Pushed(valid)
2695    }
2696
2697    fn enter_expand_a(
2698        &mut self,
2699        children: &[PatVar],
2700        pre: Option<SeqVarId>,
2701        suf: Option<SeqVarId>,
2702        seq: Vec<Cfg::G>,
2703    ) -> Enter {
2704        let nfixed = children.len();
2705        match (pre, suf) {
2706            (Some(p), Some(s)) => {
2707                if seq.len() < nfixed {
2708                    return Enter::Failed;
2709                }
2710                let slack = seq.len() - nfixed;
2711                // Scan to the first window the fixed children bind against, the same
2712                // search `backtrack` resumes. Entering at offset 0 and reporting failure
2713                // there instead drops the frame with the later offsets untried, which is
2714                // reachable as soon as a fixed child is pre-bound or global: then window
2715                // 0 can fail on a node whose later windows match.
2716                let mut bound = BoundHere::new();
2717                let mut offset = 0;
2718                let mut valid = false;
2719                while offset <= slack {
2720                    self.env.push_seq(p, &seq[..offset]);
2721                    self.env.push_seq(s, &seq[offset + nfixed..]);
2722                    if self.bind_fixed(children, &seq, offset, &mut bound) {
2723                        valid = true;
2724                        break;
2725                    }
2726                    self.env.pop_seq(s);
2727                    self.env.pop_seq(p);
2728                    offset += 1;
2729                }
2730                if !valid {
2731                    return Enter::Failed;
2732                }
2733                self.frames.push(Frame {
2734                    kind: FrameKind::SlidingWindow {
2735                        children: children.to_vec(),
2736                        pre: p,
2737                        suf: s,
2738                        seq,
2739                        offset,
2740                        slack,
2741                        bound,
2742                    },
2743                    step_idx: self.cursor,
2744                });
2745                Enter::Pushed(true)
2746            }
2747            _ => {
2748                // Single-shot cases: no generator needed.
2749                let mut bound = BoundHere::new();
2750                if pre.is_none() && suf.is_none() {
2751                    if seq.len() != nfixed {
2752                        return Enter::Failed;
2753                    }
2754                    if !self.bind_fixed(children, &seq, 0, &mut bound) {
2755                        return Enter::Failed;
2756                    }
2757                    self.cursor += 1;
2758                    Enter::Advanced
2759                } else if let (Some(p), None) = (pre, suf) {
2760                    if seq.len() < nfixed {
2761                        return Enter::Failed;
2762                    }
2763                    let split = seq.len() - nfixed;
2764                    self.env.push_seq(p, &seq[..split]);
2765                    if !self.bind_fixed(children, &seq, split, &mut bound) {
2766                        self.env.pop_seq(p);
2767                        return Enter::Failed;
2768                    }
2769                    self.cursor += 1;
2770                    Enter::Advanced
2771                } else {
2772                    // (None, Some(s))
2773                    let s = suf.unwrap();
2774                    if seq.len() < nfixed {
2775                        return Enter::Failed;
2776                    }
2777                    self.env.push_seq(s, &seq[nfixed..]);
2778                    if !self.bind_fixed(children, &seq, 0, &mut bound) {
2779                        self.env.pop_seq(s);
2780                        return Enter::Failed;
2781                    }
2782                    self.cursor += 1;
2783                    Enter::Advanced
2784                }
2785            }
2786        }
2787    }
2788
2789    fn enter_ac(
2790        &mut self,
2791        elems: &[(PatVar, RMult)],
2792        rest: Option<MsetVarId>,
2793        mut residual: Vec<(Cfg::G, Cfg::M)>,
2794    ) -> Enter {
2795        if elems.is_empty() {
2796            let zero = Cfg::M::ZERO;
2797            if let Some(rv) = rest {
2798                let rem: Vec<Cfg::C> = residual
2799                    .iter()
2800                    .filter(|&&(_, m)| m > zero)
2801                    .map(|&(g, m)| Cfg::mset_child_with_mult(g, m))
2802                    .collect();
2803                self.env.push_mset(rv, &rem);
2804                self.cursor += 1;
2805                return Enter::Advanced;
2806            } else if residual.iter().all(|&(_, m)| m == zero) {
2807                self.cursor += 1;
2808                return Enter::Advanced;
2809            } else {
2810                return Enter::Failed;
2811            }
2812        }
2813        let mut ri_at = vec![0usize; elems.len()];
2814        let mut bound = vec![false; elems.len()];
2815        let mut valid = self.ac_find_first(elems, &mut residual, &mut ri_at, &mut bound, 0);
2816        if valid {
2817            if let Some(rv) = rest {
2818                let zero = Cfg::M::ZERO;
2819                let rem: Vec<Cfg::C> = residual
2820                    .iter()
2821                    .filter(|&&(_, m)| m > zero)
2822                    .map(|&(g, m)| Cfg::mset_child_with_mult(g, m))
2823                    .collect();
2824                self.env.push_mset(rv, &rem);
2825            } else {
2826                // Exact: all residual must be consumed. Each element consumes one whole
2827                // entry, so an assignment that leaves an entry behind means there are
2828                // more entries than elements and no assignment consumes them all. Undo
2829                // this one rather than pushing a frame the caller drops, which would
2830                // leave the element variables bound for whatever runs next.
2831                let zero = Cfg::M::ZERO;
2832                if !residual.iter().all(|&(_, m)| m == zero) {
2833                    for e in (0..elems.len()).rev() {
2834                        self.ac_undo(elems, &mut residual, e, ri_at[e], &mut bound);
2835                    }
2836                    valid = false;
2837                }
2838            }
2839        }
2840        if !valid {
2841            return Enter::Failed;
2842        }
2843        let ei = elems.len();
2844        self.frames.push(Frame {
2845            kind: FrameKind::ACDecompose {
2846                elems: elems.to_vec(),
2847                rest,
2848                residual,
2849                ri_at,
2850                bound,
2851                ei,
2852            },
2853            step_idx: self.cursor,
2854        });
2855        Enter::Pushed(true)
2856    }
2857
2858    fn enter_aci(
2859        &mut self,
2860        elems: &[PatVar],
2861        rest: Option<SetVarId>,
2862        residual: Vec<Cfg::G>,
2863    ) -> Enter {
2864        if elems.is_empty() {
2865            if let Some(rv) = rest {
2866                self.env.push_set(rv, &residual);
2867                self.cursor += 1;
2868                return Enter::Advanced;
2869            } else if residual.is_empty() {
2870                self.cursor += 1;
2871                return Enter::Advanced;
2872            } else {
2873                return Enter::Failed;
2874            }
2875        }
2876        let mut used = crate::containers::bitset::BitSet::new(residual.len());
2877        let mut ri_at = vec![0usize; elems.len()];
2878        let mut bound = vec![false; elems.len()];
2879        let mut valid = self.aci_find_first(elems, &residual, &mut used, &mut ri_at, &mut bound, 0);
2880        if valid {
2881            if let Some(rv) = rest {
2882                let rem: Vec<Cfg::G> = residual
2883                    .iter()
2884                    .enumerate()
2885                    .filter(|&(i, _)| !used.test(i))
2886                    .map(|(_, &g)| g)
2887                    .collect();
2888                self.env.push_set(rv, &rem);
2889            } else if !(0..residual.len()).all(|i| used.test(i)) {
2890                // Exact: all must be used. See `enter_ac` for why this undoes the
2891                // assignment instead of pushing a frame the caller drops.
2892                for e in (0..elems.len()).rev() {
2893                    self.aci_undo(elems, &mut used, e, ri_at[e], &mut bound);
2894                }
2895                valid = false;
2896            }
2897        }
2898        if !valid {
2899            return Enter::Failed;
2900        }
2901        let ei = elems.len();
2902        self.frames.push(Frame {
2903            kind: FrameKind::ACIDecompose {
2904                elems: elems.to_vec(),
2905                rest,
2906                residual,
2907                used,
2908                ri_at,
2909                bound,
2910                ei,
2911            },
2912            step_idx: self.cursor,
2913        });
2914        Enter::Pushed(true)
2915    }
2916
2917    /// Bind the fixed children against `seq[offset..]`, recording in `bound` the local
2918    /// variables this call bound. On failure it unbinds them itself and leaves `bound`
2919    /// empty. See [`unbind`] for why a pre-bound child is checked rather than rebound and
2920    /// must survive the cleanup.
2921    fn bind_fixed(
2922        &mut self,
2923        children: &[PatVar],
2924        seq: &[Cfg::G],
2925        offset: usize,
2926        bound: &mut BoundHere,
2927    ) -> bool {
2928        bound.clear();
2929        for (i, &cv) in children.iter().enumerate() {
2930            let val = seq[offset + i];
2931            match cv {
2932                PatVar::Global(gid) => {
2933                    if canon(self.index, self.eg, self.globals.binding(gid))
2934                        != canon(self.index, self.eg, val)
2935                    {
2936                        unbind(&mut self.env, bound);
2937                        bound.clear();
2938                        return false;
2939                    }
2940                }
2941                PatVar::Local(vid) => {
2942                    if let Some(existing) = self.env.nodes[vid.idx()] {
2943                        if canon(self.index, self.eg, existing) != canon(self.index, self.eg, val) {
2944                            unbind(&mut self.env, bound);
2945                            bound.clear();
2946                            return false;
2947                        }
2948                    } else {
2949                        self.env.set(vid, val);
2950                        bound.push(vid);
2951                    }
2952                }
2953            }
2954        }
2955        true
2956    }
2957
2958    // -- Backtracking --
2959
2960    fn backtrack(&mut self) -> bool {
2961        loop {
2962            let mut frame = match self.frames.pop() {
2963                Some(f) => f,
2964                None => return false,
2965            };
2966            self.cursor = frame.step_idx;
2967
2968            match &mut frame.kind {
2969                FrameKind::Join { target, join } => {
2970                    self.env.clear(*target);
2971                    join.next();
2972                    if join.is_valid() {
2973                        self.env.set(*target, join.key());
2974                        self.cursor += 1;
2975                        self.frames.push(frame);
2976                        return true;
2977                    }
2978                    // exhausted, frame dropped
2979                }
2980                FrameKind::SlidingWindow {
2981                    children,
2982                    pre,
2983                    suf,
2984                    seq,
2985                    offset,
2986                    slack,
2987                    bound,
2988                } => {
2989                    unbind(&mut self.env, bound);
2990                    self.env.pop_seq(*suf);
2991                    self.env.pop_seq(*pre);
2992                    *offset += 1;
2993                    while *offset <= *slack {
2994                        let nfixed = children.len();
2995                        let o = *offset;
2996                        self.env.push_seq(*pre, &seq[..o]);
2997                        self.env.push_seq(*suf, &seq[o + nfixed..]);
2998                        if self.bind_fixed(children, seq, o, bound) {
2999                            self.cursor += 1;
3000                            self.frames.push(frame);
3001                            return true;
3002                        }
3003                        self.env.pop_seq(*suf);
3004                        self.env.pop_seq(*pre);
3005                        *offset += 1;
3006                    }
3007                    // exhausted
3008                }
3009                FrameKind::ACDecompose {
3010                    elems,
3011                    rest,
3012                    residual,
3013                    ri_at,
3014                    bound,
3015                    ei,
3016                } => {
3017                    if *ei == elems.len()
3018                        && let Some(rv) = *rest
3019                    {
3020                        self.env.pop_mset(rv);
3021                    }
3022                    loop {
3023                        if !self.ac_advance(elems, residual, ri_at, bound, ei) {
3024                            break;
3025                        }
3026                        if let Some(rv) = *rest {
3027                            let zero = Cfg::M::ZERO;
3028                            let rem: Vec<Cfg::C> = residual
3029                                .iter()
3030                                .filter(|&&(_, m)| m > zero)
3031                                .map(|&(g, m)| Cfg::mset_child_with_mult(g, m))
3032                                .collect();
3033                            self.env.push_mset(rv, &rem);
3034                            self.cursor += 1;
3035                            self.frames.push(frame);
3036                            return true;
3037                        } else {
3038                            let zero = Cfg::M::ZERO;
3039                            if residual.iter().all(|&(_, m)| m == zero) {
3040                                self.cursor += 1;
3041                                self.frames.push(frame);
3042                                return true;
3043                            }
3044                            // Not exact — keep advancing.
3045                        }
3046                    }
3047                    // exhausted
3048                }
3049                FrameKind::ACIDecompose {
3050                    elems,
3051                    rest,
3052                    residual,
3053                    used,
3054                    ri_at,
3055                    bound,
3056                    ei,
3057                } => {
3058                    if *ei == elems.len()
3059                        && let Some(rv) = *rest
3060                    {
3061                        self.env.pop_set(rv);
3062                    }
3063                    loop {
3064                        if !self.aci_advance(elems, residual, used, ri_at, bound, ei) {
3065                            break;
3066                        }
3067                        if let Some(rv) = *rest {
3068                            let rem: Vec<Cfg::G> = residual
3069                                .iter()
3070                                .enumerate()
3071                                .filter(|&(i, _)| !used.test(i))
3072                                .map(|(_, &g)| g)
3073                                .collect();
3074                            self.env.push_set(rv, &rem);
3075                            self.cursor += 1;
3076                            self.frames.push(frame);
3077                            return true;
3078                        } else if (0..residual.len()).all(|i| used.test(i)) {
3079                            self.cursor += 1;
3080                            self.frames.push(frame);
3081                            return true;
3082                        }
3083                    }
3084                    // exhausted
3085                }
3086            }
3087        }
3088    }
3089
3090    // -- AC helpers --
3091
3092    fn ac_find_first(
3093        &mut self,
3094        elems: &[(PatVar, RMult)],
3095        residual: &mut [(Cfg::G, Cfg::M)],
3096        ri_at: &mut [usize],
3097        bound: &mut [bool],
3098        from: usize,
3099    ) -> bool {
3100        let mut ei = from;
3101        while ei < elems.len() {
3102            let start = if ei == from { ri_at[ei] } else { 0 };
3103            match self.ac_scan(elems, residual, ei, start, bound) {
3104                Some(ri) => {
3105                    ri_at[ei] = ri;
3106                    ei += 1;
3107                }
3108                None => {
3109                    ri_at[ei] = 0;
3110                    if ei == 0 {
3111                        return false;
3112                    }
3113                    ei -= 1;
3114                    self.ac_undo(elems, residual, ei, ri_at[ei], bound);
3115                    ri_at[ei] += 1;
3116                }
3117            }
3118        }
3119        true
3120    }
3121
3122    /// Take one residual entry for element `ei`, recording in `bound[ei]` whether this
3123    /// scan bound the element variable. A variable already bound is matched against the
3124    /// residual and left alone, and [`Self::ac_undo`] must leave it alone too; see
3125    /// [`unbind`].
3126    fn ac_scan(
3127        &mut self,
3128        elems: &[(PatVar, RMult)],
3129        residual: &mut [(Cfg::G, Cfg::M)],
3130        ei: usize,
3131        start: usize,
3132        bound: &mut [bool],
3133    ) -> Option<usize> {
3134        let (var, mult) = &elems[ei];
3135        bound[ei] = false;
3136
3137        let bound_repr = match *var {
3138            PatVar::Global(gid) => Some(canon(self.index, self.eg, self.globals.binding(gid))),
3139            PatVar::Local(vid) => self.env.nodes[vid.idx()].map(|v| canon(self.index, self.eg, v)),
3140        };
3141
3142        if let Some(repr) = bound_repr {
3143            for ri in start..residual.len() {
3144                if residual[ri].0 == repr
3145                    && mult_matches(
3146                        mult,
3147                        residual[ri].1.to_u64(),
3148                        bound_mult_val(mult, &self.env),
3149                    )
3150                {
3151                    let take: Cfg::M = match mult {
3152                        // Matched at the surface width, so the literal equals
3153                        // this entry's multiplicity; reuse it.
3154                        RMult::Exact(_) => residual[ri].1,
3155                        RMult::Var { var: mv, .. } => {
3156                            self.env.set_mult(*mv, residual[ri].1);
3157                            residual[ri].1
3158                        }
3159                    };
3160                    residual[ri].1 = residual[ri].1.saturating_sub(take);
3161                    return Some(ri);
3162                }
3163            }
3164            return None;
3165        }
3166
3167        for ri in start..residual.len() {
3168            let (repr, avail) = residual[ri];
3169            if !mult_matches(mult, avail.to_u64(), bound_mult_val(mult, &self.env)) {
3170                continue;
3171            }
3172            let PatVar::Local(vid) = *var else {
3173                unreachable!()
3174            };
3175            self.env.set(vid, repr);
3176            bound[ei] = true;
3177            let take: Cfg::M = match mult {
3178                // See the bound-repr path above.
3179                RMult::Exact(_) => avail,
3180                RMult::Var { var: mv, .. } => {
3181                    self.env.set_mult(*mv, avail);
3182                    avail
3183                }
3184            };
3185            residual[ri].1 = avail.saturating_sub(take);
3186            return Some(ri);
3187        }
3188        None
3189    }
3190
3191    fn ac_undo(
3192        &mut self,
3193        elems: &[(PatVar, RMult)],
3194        residual: &mut [(Cfg::G, Cfg::M)],
3195        ei: usize,
3196        ri: usize,
3197        bound: &mut [bool],
3198    ) {
3199        let (var, mult) = &elems[ei];
3200        let restore: Cfg::M = match mult {
3201            // `ac_scan` only took this entry because the literal equalled its
3202            // stored multiplicity, so the literal is representable at the
3203            // configured width.
3204            RMult::Exact(n) => Cfg::M::try_from_u64(*n)
3205                .expect("Exact multiplicity matched a stored one, so it fits the configured width"),
3206            RMult::Var { var: mv, .. } => self.env.get_mult(*mv),
3207        };
3208        // Summation is checked: this undoes a subtraction `ac_scan` performed on
3209        // the same entry, so the sum cannot exceed the width — but a wrap here
3210        // would silently forge a multiplicity (possibly zero) and corrupt the
3211        // residual multiset rather than fail a match.
3212        residual[ri].1 = residual[ri].1.checked_add(restore).expect(
3213            "ac_undo restores a multiplicity previously subtracted from this entry, so the sum fits",
3214        );
3215        if let PatVar::Local(vid) = *var
3216            && bound[ei]
3217        {
3218            self.env.clear(vid);
3219        }
3220        bound[ei] = false;
3221        if let RMult::Var { var: mv, .. } = mult {
3222            // Only clear if no earlier element uses the same mult variable
3223            let earlier_uses = elems[..ei]
3224                .iter()
3225                .any(|(_, m)| matches!(m, RMult::Var { var: v, .. } if *v == *mv));
3226            if !earlier_uses {
3227                self.env.set_mult(*mv, Cfg::M::ZERO);
3228            }
3229        }
3230    }
3231
3232    fn ac_advance(
3233        &mut self,
3234        elems: &[(PatVar, RMult)],
3235        residual: &mut [(Cfg::G, Cfg::M)],
3236        ri_at: &mut [usize],
3237        bound: &mut [bool],
3238        ei: &mut usize,
3239    ) -> bool {
3240        if elems.is_empty() || *ei != elems.len() {
3241            return false;
3242        }
3243        // Undo last element, try next residual entry. If exhausted, undo previous, etc.
3244        let mut e = elems.len() - 1;
3245        loop {
3246            self.ac_undo(elems, residual, e, ri_at[e], bound);
3247            ri_at[e] += 1;
3248            // Try to find a valid entry for element e and all subsequent elements.
3249            // ac_scan only looks at element e; if it succeeds we try e+1.. from scratch.
3250            if let Some(ri) = self.ac_scan(elems, residual, e, ri_at[e], bound) {
3251                ri_at[e] = ri;
3252                // Now try to bind e+1..end from scratch.
3253                let mut ok = true;
3254                for e2 in (e + 1)..elems.len() {
3255                    ri_at[e2] = 0;
3256                    match self.ac_scan(elems, residual, e2, 0, bound) {
3257                        Some(ri2) => ri_at[e2] = ri2,
3258                        None => {
3259                            // Undo e2-1..=e+1 that we just bound, then undo e and try next.
3260                            for undo in (e + 1..e2).rev() {
3261                                self.ac_undo(elems, residual, undo, ri_at[undo], bound);
3262                            }
3263                            ok = false;
3264                            break;
3265                        }
3266                    }
3267                }
3268                if ok {
3269                    *ei = elems.len();
3270                    return true;
3271                }
3272                // ac_scan for e succeeded but downstream failed. Undo e and try next ri.
3273                self.ac_undo(elems, residual, e, ri_at[e], bound);
3274                ri_at[e] += 1;
3275                continue;
3276            }
3277            // No more entries for element e. Backtrack to e-1.
3278            ri_at[e] = 0;
3279            if e == 0 {
3280                *ei = 0;
3281                return false;
3282            }
3283            e -= 1;
3284        }
3285    }
3286
3287    // -- ACI helpers --
3288
3289    fn aci_find_first(
3290        &mut self,
3291        elems: &[PatVar],
3292        residual: &[Cfg::G],
3293        used: &mut crate::containers::bitset::BitSet,
3294        ri_at: &mut [usize],
3295        bound: &mut [bool],
3296        from: usize,
3297    ) -> bool {
3298        let mut ei = from;
3299        while ei < elems.len() {
3300            let start = if ei == from { ri_at[ei] } else { 0 };
3301            match self.aci_scan(elems, residual, used, ei, start, bound) {
3302                Some(ri) => {
3303                    ri_at[ei] = ri;
3304                    ei += 1;
3305                }
3306                None => {
3307                    ri_at[ei] = 0;
3308                    if ei == 0 {
3309                        return false;
3310                    }
3311                    ei -= 1;
3312                    self.aci_undo(elems, used, ei, ri_at[ei], bound);
3313                    ri_at[ei] += 1;
3314                }
3315            }
3316        }
3317        true
3318    }
3319
3320    /// Take one residual element for `ei`, recording in `bound[ei]` whether this scan
3321    /// bound the element variable. See [`Self::ac_scan`].
3322    fn aci_scan(
3323        &mut self,
3324        elems: &[PatVar],
3325        residual: &[Cfg::G],
3326        used: &mut crate::containers::bitset::BitSet,
3327        ei: usize,
3328        start: usize,
3329        bound: &mut [bool],
3330    ) -> Option<usize> {
3331        let var = elems[ei];
3332        bound[ei] = false;
3333        let bound_repr = match var {
3334            PatVar::Global(gid) => Some(canon(self.index, self.eg, self.globals.binding(gid))),
3335            PatVar::Local(vid) => self.env.nodes[vid.idx()].map(|v| canon(self.index, self.eg, v)),
3336        };
3337        if let Some(repr) = bound_repr {
3338            for ri in start..residual.len() {
3339                if !used.test(ri) && residual[ri] == repr {
3340                    used.set(ri);
3341                    return Some(ri);
3342                }
3343            }
3344            return None;
3345        }
3346        let PatVar::Local(vid) = var else {
3347            unreachable!()
3348        };
3349        for ri in start..residual.len() {
3350            if used.test(ri) {
3351                continue;
3352            }
3353            self.env.set(vid, residual[ri]);
3354            bound[ei] = true;
3355            used.set(ri);
3356            return Some(ri);
3357        }
3358        None
3359    }
3360
3361    fn aci_undo(
3362        &mut self,
3363        elems: &[PatVar],
3364        used: &mut crate::containers::bitset::BitSet,
3365        ei: usize,
3366        ri: usize,
3367        bound: &mut [bool],
3368    ) {
3369        used.clear(ri);
3370        if let PatVar::Local(vid) = elems[ei]
3371            && bound[ei]
3372        {
3373            self.env.clear(vid);
3374        }
3375        bound[ei] = false;
3376    }
3377
3378    fn aci_advance(
3379        &mut self,
3380        elems: &[PatVar],
3381        residual: &[Cfg::G],
3382        used: &mut crate::containers::bitset::BitSet,
3383        ri_at: &mut [usize],
3384        bound: &mut [bool],
3385        ei: &mut usize,
3386    ) -> bool {
3387        if elems.is_empty() || *ei != elems.len() {
3388            return false;
3389        }
3390        let mut e = elems.len() - 1;
3391        loop {
3392            self.aci_undo(elems, used, e, ri_at[e], bound);
3393            ri_at[e] += 1;
3394            if let Some(ri) = self.aci_scan(elems, residual, used, e, ri_at[e], bound) {
3395                ri_at[e] = ri;
3396                let mut ok = true;
3397                for e2 in (e + 1)..elems.len() {
3398                    ri_at[e2] = 0;
3399                    match self.aci_scan(elems, residual, used, e2, 0, bound) {
3400                        Some(ri2) => ri_at[e2] = ri2,
3401                        None => {
3402                            for undo in (e + 1..e2).rev() {
3403                                self.aci_undo(elems, used, undo, ri_at[undo], bound);
3404                            }
3405                            ok = false;
3406                            break;
3407                        }
3408                    }
3409                }
3410                if ok {
3411                    *ei = elems.len();
3412                    return true;
3413                }
3414                self.aci_undo(elems, used, e, ri_at[e], bound);
3415                ri_at[e] += 1;
3416                continue;
3417            }
3418            ri_at[e] = 0;
3419            if e == 0 {
3420                *ei = 0;
3421                return false;
3422            }
3423            e -= 1;
3424        }
3425    }
3426}
3427
3428enum Enter {
3429    Advanced,
3430    Failed,
3431    Pushed(bool),
3432}
3433
3434/// Convenience: collect all matches using the iterator.
3435pub fn run_query_iter<Cfg, L, const T: bool, const P: bool>(
3436    plan: &QueryPlan<Cfg::O, Cfg::Index, L>,
3437    eg: &EGraph<Cfg, L, T, P>,
3438    index: &VariantIndex<'_, Cfg>,
3439) -> Vec<Match<Cfg>>
3440where
3441    Cfg: EGraphConfig,
3442    L: LitVal,
3443    MSetCanon: VarCanon<Cfg::G, Cfg::C>,
3444{
3445    let empty: crate::resolve::GlobalCtx<(), Cfg::G> = crate::resolve::GlobalCtx::new();
3446    let mut it = MatchIterator::new(plan, eg, index, &empty);
3447    let mut out = Vec::new();
3448    while it.next_match() {
3449        out.push(it.env().clone());
3450    }
3451    out
3452}
3453
3454#[cfg(test)]
3455mod tests {
3456    use super::*;
3457    use crate::id::{ENodeId, OpId, SortId};
3458    use crate::literal::{NiraLitVal, NiraModel};
3459    use crate::nodes::DefaultConfig;
3460    use crate::registry::{OpRegistry, SortRegistry};
3461    use crate::resolve::MatchShape;
3462    use crate::resolve::resolve;
3463    use crate::schedule::schedule;
3464    use crate::sortcheck::flatten_surface as flatten;
3465    use crate::test_helpers::parse_pattern;
3466
3467    type EG = EGraph<DefaultConfig, NiraLitVal, false, false>;
3468
3469    fn make_eg() -> EG {
3470        let mut eg = EG::from_model(&NiraModel);
3471        let e = eg.intern_sort("IExpr");
3472        eg.register_op2("f", e, e, e);
3473        eg.register_op1("g", e, e);
3474        eg.register_op2("h", e, e, e);
3475        eg.register_op0("a", e);
3476        eg.register_op0("b", e);
3477        eg.register_op0("c", e);
3478        eg.register_a("concat", e, e, crate::registry::AssocDir::Right);
3479        eg.register_mset("add", e, e);
3480        eg.register_set("union", e, e);
3481        eg
3482    }
3483
3484    fn query<const TRACK: bool>(
3485        eg: &EGraph<DefaultConfig, NiraLitVal, TRACK, false>,
3486        ops: &OpRegistry<OpId, SortId, TRACK>,
3487        sorts: &SortRegistry<SortId, TRACK>,
3488        srcs: &[&str],
3489    ) -> Vec<Match<DefaultConfig>> {
3490        let model = NiraModel;
3491        let pats: Vec<_> = srcs.iter().map(|s| parse_pattern(s)).collect();
3492        let fq = flatten(&pats, ops).unwrap();
3493        let rq = resolve(
3494            &fq,
3495            ops,
3496            sorts,
3497            &model,
3498            &crate::resolve::GlobalCtx::<_, ()>::new(),
3499        )
3500        .unwrap();
3501        let plan = schedule(&rq);
3502        let index = IndexStore::build(eg);
3503        let index = VariantIndex::naive(&index);
3504        run_query(
3505            &plan,
3506            eg,
3507            &index,
3508            &crate::resolve::GlobalCtx::<(), _>::new(),
3509        )
3510    }
3511
3512    #[test]
3513    fn empty_egraph_no_matches() {
3514        let eg = make_eg();
3515        let matches = query(&eg, eg.ops(), eg.sorts(), &["(f x y)"]);
3516        assert!(matches.is_empty());
3517    }
3518
3519    /// A pool reused across queries yields the same matches as a fresh one.
3520    ///
3521    /// This is the property the pool's recycled storage could break and nothing
3522    /// else would catch: the match slots and the decompose child buffers both
3523    /// survive `clear()`, so a query that reads a buffer before filling it, or
3524    /// reads a match slot past `len`, would see the *previous* query's data.
3525    /// Every pattern shape that owns recycled storage is driven twice, in an
3526    /// order that guarantees each second run inherits a non-empty pool.
3527    #[test]
3528    fn reused_pool_matches_a_fresh_pool() {
3529        let mut eg = make_eg();
3530        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
3531        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
3532        let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
3533        eg.add(eg.ops().id_by_name("f").unwrap(), &[a, b]);
3534        eg.add(eg.ops().id_by_name("add").unwrap(), &[a, b, c]);
3535        eg.add(eg.ops().id_by_name("union").unwrap(), &[a, b, c]);
3536        eg.add(eg.ops().id_by_name("concat").unwrap(), &[a, b, c]);
3537        eg.rebuild();
3538
3539        // ExpandA (`concat`), DecomposeAC (`add`), DecomposeACI (`union`) and a
3540        // plain join — one per recycled-storage kind.
3541        let shapes = [
3542            "(f x y)",
3543            "(add x:1 ..rest)",
3544            "(union x ..rest)",
3545            "(concat x y ..rest)",
3546        ];
3547
3548        let index = IndexStore::build(&eg);
3549        let index = VariantIndex::naive(&index);
3550        let ng = crate::resolve::GlobalCtx::<(), _>::new();
3551
3552        let plans: Vec<_> = shapes
3553            .iter()
3554            .map(|src| {
3555                let pats = [parse_pattern(src)];
3556                let fq = flatten(&pats, eg.ops()).unwrap();
3557                let rq = resolve(
3558                    &fq,
3559                    eg.ops(),
3560                    eg.sorts(),
3561                    &NiraModel,
3562                    &crate::resolve::GlobalCtx::<_, ()>::new(),
3563                )
3564                .unwrap();
3565                schedule(&rq)
3566            })
3567            .collect();
3568
3569        let mut shared = MatchPool::new();
3570        // Two passes, so the second sees a pool warmed by all four shapes.
3571        for _ in 0..2 {
3572            for plan in &plans {
3573                let mut fresh = MatchPool::new();
3574                run_query_into(plan, &eg, &index, &ng, &mut fresh);
3575                run_query_into(plan, &eg, &index, &ng, &mut shared);
3576
3577                assert_eq!(shared.len(), fresh.len(), "match count diverged");
3578                let expect: Vec<_> = (0..fresh.len())
3579                    .map(|j| env_key(&fresh.clone_match(j), &eg))
3580                    .collect();
3581                let got: Vec<_> = (0..shared.len())
3582                    .map(|j| env_key(&shared.clone_match(j), &eg))
3583                    .collect();
3584                assert_eq!(got, expect, "reused pool produced different bindings");
3585            }
3586        }
3587    }
3588
3589    #[test]
3590    fn single_node_match() {
3591        let mut eg = make_eg();
3592        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
3593        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
3594        let _f = eg.add(eg.ops().id_by_name("f").unwrap(), &[a, b]);
3595        let matches = query(&eg, eg.ops(), eg.sorts(), &["(f x y)"]);
3596        assert_eq!(matches.len(), 1);
3597    }
3598
3599    #[test]
3600    fn two_f_nodes() {
3601        let mut eg = make_eg();
3602        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
3603        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
3604        let _f1 = eg.add(eg.ops().id_by_name("f").unwrap(), &[a, b]);
3605        let _f2 = eg.add(eg.ops().id_by_name("f").unwrap(), &[b, a]);
3606        let matches = query(&eg, eg.ops(), eg.sorts(), &["(f x y)"]);
3607        assert_eq!(matches.len(), 2);
3608    }
3609
3610    #[test]
3611    fn nested_pattern() {
3612        let mut eg = make_eg();
3613        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
3614        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
3615        let g_a = eg.add(eg.ops().id_by_name("g").unwrap(), &[a]);
3616        let _f = eg.add(eg.ops().id_by_name("f").unwrap(), &[b, g_a]);
3617        // (f x (g y)) should match
3618        let matches = query(&eg, eg.ops(), eg.sorts(), &["(f x (g y))"]);
3619        assert_eq!(matches.len(), 1);
3620    }
3621
3622    #[test]
3623    fn nested_no_match() {
3624        let mut eg = make_eg();
3625        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
3626        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
3627        let _f = eg.add(eg.ops().id_by_name("f").unwrap(), &[a, b]);
3628        // (f x (g y)) should NOT match — second child is b, not a g-node
3629        let matches = query(&eg, eg.ops(), eg.sorts(), &["(f x (g y))"]);
3630        assert!(matches.is_empty());
3631    }
3632
3633    #[test]
3634    fn nonlinear_match() {
3635        let mut eg = make_eg();
3636        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
3637        let _f = eg.add(eg.ops().id_by_name("f").unwrap(), &[a, a]);
3638        // (f x x) — same var both positions
3639        let matches = query(&eg, eg.ops(), eg.sorts(), &["(f x x)"]);
3640        assert_eq!(matches.len(), 1);
3641    }
3642
3643    #[test]
3644    fn nonlinear_no_match() {
3645        let mut eg = make_eg();
3646        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
3647        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
3648        let _f = eg.add(eg.ops().id_by_name("f").unwrap(), &[a, b]);
3649        // (f x x) — a != b, should not match
3650        let matches = query(&eg, eg.ops(), eg.sorts(), &["(f x x)"]);
3651        assert!(matches.is_empty());
3652    }
3653
3654    #[test]
3655    fn multi_pattern() {
3656        let mut eg = make_eg();
3657        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
3658        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
3659        let _f = eg.add(eg.ops().id_by_name("f").unwrap(), &[a, b]);
3660        let _g = eg.add(eg.ops().id_by_name("g").unwrap(), &[b]);
3661        // (f x y), (g y) — y shared, b must appear in both
3662        let matches = query(&eg, eg.ops(), eg.sorts(), &["(f x y)", "(g y)"]);
3663        assert_eq!(matches.len(), 1);
3664    }
3665
3666    #[test]
3667    fn multi_pattern_no_match() {
3668        let mut eg = make_eg();
3669        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
3670        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
3671        let _f = eg.add(eg.ops().id_by_name("f").unwrap(), &[a, b]);
3672        let _g = eg.add(eg.ops().id_by_name("g").unwrap(), &[a]); // g(a), not g(b)
3673        // (f x y), (g y) — y=b from f, but g(b) doesn't exist
3674        let matches = query(&eg, eg.ops(), eg.sorts(), &["(f x y)", "(g y)"]);
3675        assert!(matches.is_empty());
3676    }
3677
3678    #[test]
3679    fn binding_values_correct() {
3680        let mut eg = make_eg();
3681        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
3682        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
3683        let _f = eg.add(eg.ops().id_by_name("f").unwrap(), &[a, b]);
3684
3685        let model = NiraModel;
3686        let pat = parse_pattern("(f x y)");
3687        let fq = flatten(&[pat], eg.ops()).unwrap();
3688        let rq = resolve(
3689            &fq,
3690            eg.ops(),
3691            eg.sorts(),
3692            &model,
3693            &crate::resolve::GlobalCtx::<_, ()>::new(),
3694        )
3695        .unwrap();
3696        let plan = schedule(&rq);
3697        let index = IndexStore::build(&eg);
3698        let index = VariantIndex::naive(&index);
3699        let matches = run_query(
3700            &plan,
3701            &eg,
3702            &index,
3703            &crate::resolve::GlobalCtx::<(), _>::new(),
3704        );
3705
3706        assert_eq!(matches.len(), 1);
3707        let x = rq.shape.find_var("x").unwrap();
3708        let y = rq.shape.find_var("y").unwrap();
3709        assert_eq!(eg.find_const(matches[0].get(x)), eg.find_const(a));
3710        assert_eq!(eg.find_const(matches[0].get(y)), eg.find_const(b));
3711    }
3712
3713    #[test]
3714    fn deep_nesting() {
3715        let mut eg = make_eg();
3716        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
3717        let g_a = eg.add(eg.ops().id_by_name("g").unwrap(), &[a]);
3718        let g_g_a = eg.add(eg.ops().id_by_name("g").unwrap(), &[g_a]);
3719        let _f = eg.add(eg.ops().id_by_name("f").unwrap(), &[a, g_g_a]);
3720        let matches = query(&eg, eg.ops(), eg.sorts(), &["(f x (g (g y)))"]);
3721        assert_eq!(matches.len(), 1);
3722    }
3723
3724    // -- AC matching --
3725
3726    #[test]
3727    fn ac_exact_match() {
3728        let mut eg = make_eg();
3729        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
3730        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
3731        let _add = eg.add(eg.ops().id_by_name("add").unwrap(), &[a, b]);
3732        // {x:1 y:1} exact — should match, binding x and y to a,b in some order
3733        let matches = query(&eg, eg.ops(), eg.sorts(), &["(add x:1 y:1)"]);
3734        assert_eq!(matches.len(), 2); // x=a,y=b and x=b,y=a
3735    }
3736
3737    #[test]
3738    fn ac_exact_no_match_extra() {
3739        let mut eg = make_eg();
3740        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
3741        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
3742        let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
3743        let _add = eg.add(eg.ops().id_by_name("add").unwrap(), &[a, b, c]);
3744        // {x:1 y:1} exact — 3 elements, only 2 pattern vars → no match
3745        let matches = query(&eg, eg.ops(), eg.sorts(), &["(add x:1 y:1)"]);
3746        assert!(matches.is_empty());
3747    }
3748
3749    #[test]
3750    fn ac_subset_match() {
3751        let mut eg = make_eg();
3752        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
3753        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
3754        let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
3755        let _add = eg.add(eg.ops().id_by_name("add").unwrap(), &[a, b, c]);
3756        // {x:1 ..rest} — should match 3 times (x=a, x=b, x=c)
3757        let matches = query(&eg, eg.ops(), eg.sorts(), &["(add x:1 ..rest)"]);
3758        assert_eq!(matches.len(), 3);
3759    }
3760
3761    #[test]
3762    fn ac_mult_exact() {
3763        let mut eg = make_eg();
3764        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
3765        // add(a, a, a) → AC node {a:3}
3766        let _add = eg.add(eg.ops().id_by_name("add").unwrap(), &[a, a, a]);
3767        // {x:2 ..rest} — x:2 means multiplicity must be exactly 2. a has 3 → no match.
3768        let matches = query(&eg, eg.ops(), eg.sorts(), &["(add x:2 ..rest)"]);
3769        assert_eq!(matches.len(), 0);
3770        // {x:3 ..rest} — a has exactly 3 → match
3771        let matches = query(&eg, eg.ops(), eg.sorts(), &["(add x:3 ..rest)"]);
3772        assert_eq!(matches.len(), 1);
3773        // {x:k>=2 ..rest} — a has 3 >= 2 → match, k=3
3774        let matches = query(&eg, eg.ops(), eg.sorts(), &["(add x:k>=2 ..rest)"]);
3775        assert_eq!(matches.len(), 1);
3776    }
3777
3778    #[test]
3779    fn ac_mult_exact_no_match() {
3780        let mut eg = make_eg();
3781        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
3782        // add(a) → AC node {a:1}
3783        let _add = eg.add(eg.ops().id_by_name("add").unwrap(), &[a]);
3784        // {x:2 ..rest} — need mult ≥ 2, only have 1
3785        let matches = query(&eg, eg.ops(), eg.sorts(), &["(add x:2 ..rest)"]);
3786        assert!(matches.is_empty());
3787    }
3788
3789    // -- A (sequence) matching --
3790
3791    #[test]
3792    fn a_exact_match() {
3793        let mut eg = make_eg();
3794        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
3795        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
3796        let _cat = eg.add(eg.ops().id_by_name("concat").unwrap(), &[a, b]);
3797        // [x y] exact
3798        let matches = query(&eg, eg.ops(), eg.sorts(), &["(concat x y)"]);
3799        assert_eq!(matches.len(), 1);
3800    }
3801
3802    #[test]
3803    fn a_exact_wrong_length() {
3804        let mut eg = make_eg();
3805        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
3806        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
3807        let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
3808        let _cat = eg.add(eg.ops().id_by_name("concat").unwrap(), &[a, b, c]);
3809        // [x y] exact — 3 children, 2 vars → no match
3810        let matches = query(&eg, eg.ops(), eg.sorts(), &["(concat x y)"]);
3811        assert!(matches.is_empty());
3812    }
3813
3814    #[test]
3815    fn a_prefix_match() {
3816        let mut eg = make_eg();
3817        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
3818        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
3819        let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
3820        let _cat = eg.add(eg.ops().id_by_name("concat").unwrap(), &[a, b, c]);
3821        // [..pre x] — x = last element (c), pre = [a, b]
3822        let matches = query(&eg, eg.ops(), eg.sorts(), &["(concat ..pre x)"]);
3823        assert_eq!(matches.len(), 1);
3824    }
3825
3826    #[test]
3827    fn a_sliding_window() {
3828        let mut eg = make_eg();
3829        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
3830        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
3831        let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
3832        let _cat = eg.add(eg.ops().id_by_name("concat").unwrap(), &[a, b, c]);
3833        // [..pre x ..suf] — x slides over a, b, c → 3 matches
3834        let matches = query(&eg, eg.ops(), eg.sorts(), &["(concat ..pre x ..suf)"]);
3835        assert_eq!(matches.len(), 3);
3836    }
3837
3838    fn query_named<const TRACK: bool>(
3839        eg: &EGraph<DefaultConfig, NiraLitVal, TRACK, false>,
3840        ops: &OpRegistry<OpId, SortId, TRACK>,
3841        sorts: &SortRegistry<SortId, TRACK>,
3842        srcs: &[&str],
3843    ) -> (Vec<Match<DefaultConfig>>, MatchShape) {
3844        let model = NiraModel;
3845        let pats: Vec<_> = srcs.iter().map(|s| parse_pattern(s)).collect();
3846        let fq = flatten(&pats, ops).unwrap();
3847        let rq = resolve(
3848            &fq,
3849            ops,
3850            sorts,
3851            &model,
3852            &crate::resolve::GlobalCtx::<_, ()>::new(),
3853        )
3854        .unwrap();
3855        let plan = schedule(&rq);
3856        let index = IndexStore::build(eg);
3857        let index = VariantIndex::naive(&index);
3858        (
3859            run_query(
3860                &plan,
3861                eg,
3862                &index,
3863                &crate::resolve::GlobalCtx::<(), _>::new(),
3864            ),
3865            rq.shape,
3866        )
3867    }
3868
3869    /// Extract (var_name → node_op_name) map from a binding, filtering out internal vars.
3870    fn binding_map<const TRACK: bool>(
3871        m: &Match<DefaultConfig>,
3872        vars: &MatchShape,
3873        eg: &EGraph<DefaultConfig, NiraLitVal, TRACK, false>,
3874    ) -> Vec<(String, String)> {
3875        vars.nodes
3876            .iter()
3877            .enumerate()
3878            .filter(|(_, name)| !name.starts_with('#')) // skip internal vars
3879            .filter_map(|(vi, name)| {
3880                m.nodes[vi].map(|g| (name.clone(), eg.node_op_name(g).to_string()))
3881            })
3882            .collect()
3883    }
3884
3885    fn has_binding<const TRACK: bool>(
3886        matches: &[Match<DefaultConfig>],
3887        vars: &MatchShape,
3888        eg: &EGraph<DefaultConfig, NiraLitVal, TRACK, false>,
3889        expected: &[(&str, &str)],
3890    ) -> bool {
3891        matches.iter().any(|m| {
3892            let bm = binding_map(m, vars, eg);
3893            expected
3894                .iter()
3895                .all(|&(var, op)| bm.iter().any(|(v, o)| v == var && o == op))
3896        })
3897    }
3898
3899    #[test]
3900    fn verify_plain_f_x_y() {
3901        let mut eg = make_eg();
3902        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
3903        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
3904        let g_a = eg.add(eg.ops().id_by_name("g").unwrap(), &[a]);
3905        eg.add(eg.ops().id_by_name("f").unwrap(), &[a, b]);
3906        eg.add(eg.ops().id_by_name("f").unwrap(), &[b, g_a]);
3907
3908        let (matches, vars) = query_named(&eg, eg.ops(), eg.sorts(), &["(f x y)"]);
3909        assert_eq!(matches.len(), 2);
3910        assert!(has_binding(&matches, &vars, &eg, &[("x", "a"), ("y", "b")]));
3911        assert!(has_binding(&matches, &vars, &eg, &[("x", "b"), ("y", "g")]));
3912    }
3913
3914    #[test]
3915    fn verify_nested_f_x_g_y() {
3916        let mut eg = make_eg();
3917        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
3918        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
3919        let g_a = eg.add(eg.ops().id_by_name("g").unwrap(), &[a]);
3920        eg.add(eg.ops().id_by_name("f").unwrap(), &[a, b]);
3921        eg.add(eg.ops().id_by_name("f").unwrap(), &[b, g_a]);
3922
3923        let (matches, vars) = query_named(&eg, eg.ops(), eg.sorts(), &["(f x (g y))"]);
3924        assert_eq!(matches.len(), 1);
3925        assert!(has_binding(&matches, &vars, &eg, &[("x", "b"), ("y", "a")]));
3926    }
3927
3928    #[test]
3929    fn verify_ac_subset() {
3930        let mut eg = make_eg();
3931        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
3932        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
3933        let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
3934        eg.add(eg.ops().id_by_name("add").unwrap(), &[a, b, c]);
3935
3936        let (matches, vars) = query_named(&eg, eg.ops(), eg.sorts(), &["(add x:1 ..rest)"]);
3937        assert_eq!(matches.len(), 3);
3938        assert!(has_binding(&matches, &vars, &eg, &[("x", "a")]));
3939        assert!(has_binding(&matches, &vars, &eg, &[("x", "b")]));
3940        assert!(has_binding(&matches, &vars, &eg, &[("x", "c")]));
3941    }
3942
3943    #[test]
3944    fn verify_ac_exact_two_of_three() {
3945        let mut eg = make_eg();
3946        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
3947        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
3948        eg.add(eg.ops().id_by_name("add").unwrap(), &[a, b]);
3949
3950        let (matches, vars) = query_named(&eg, eg.ops(), eg.sorts(), &["(add x:1 y:1)"]);
3951        assert_eq!(matches.len(), 2);
3952        assert!(has_binding(&matches, &vars, &eg, &[("x", "a"), ("y", "b")]));
3953        assert!(has_binding(&matches, &vars, &eg, &[("x", "b"), ("y", "a")]));
3954    }
3955
3956    #[test]
3957    fn verify_ac_mult() {
3958        let mut eg = make_eg();
3959        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
3960        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
3961        // add(a, a, a, b) → {a:3, b:1}
3962        eg.add(eg.ops().id_by_name("add").unwrap(), &[a, a, a, b]);
3963
3964        // x:2 means exactly 2. a has 3, b has 1 → no match.
3965        let (matches, _vars) = query_named(&eg, eg.ops(), eg.sorts(), &["(add x:2 ..rest)"]);
3966        assert_eq!(matches.len(), 0);
3967
3968        // x:k>=2 means at least 2. a has 3 → match.
3969        let (matches, vars) = query_named(&eg, eg.ops(), eg.sorts(), &["(add x:k>=2 ..rest)"]);
3970        assert_eq!(matches.len(), 1);
3971        assert!(has_binding(&matches, &vars, &eg, &[("x", "a")]));
3972    }
3973
3974    #[test]
3975    fn verify_a_exact() {
3976        let mut eg = make_eg();
3977        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
3978        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
3979        let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
3980        eg.add(eg.ops().id_by_name("concat").unwrap(), &[a, b, c]);
3981
3982        let (matches, vars) = query_named(&eg, eg.ops(), eg.sorts(), &["(concat x y z)"]);
3983        assert_eq!(matches.len(), 1);
3984        assert!(has_binding(
3985            &matches,
3986            &vars,
3987            &eg,
3988            &[("x", "a"), ("y", "b"), ("z", "c")]
3989        ));
3990    }
3991
3992    #[test]
3993    fn verify_a_sliding_window() {
3994        let mut eg = make_eg();
3995        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
3996        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
3997        let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
3998        eg.add(eg.ops().id_by_name("concat").unwrap(), &[a, b, c]);
3999
4000        let (matches, vars) = query_named(&eg, eg.ops(), eg.sorts(), &["(concat ..pre x ..suf)"]);
4001        assert_eq!(matches.len(), 3);
4002        assert!(has_binding(&matches, &vars, &eg, &[("x", "a")]));
4003        assert!(has_binding(&matches, &vars, &eg, &[("x", "b")]));
4004        assert!(has_binding(&matches, &vars, &eg, &[("x", "c")]));
4005    }
4006
4007    #[test]
4008    fn verify_a_suffix() {
4009        let mut eg = make_eg();
4010        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
4011        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
4012        let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
4013        eg.add(eg.ops().id_by_name("concat").unwrap(), &[a, b, c]);
4014
4015        // [x y ..suf] — x=a, y=b, suf=rest
4016        let (matches, vars) = query_named(&eg, eg.ops(), eg.sorts(), &["(concat x y ..suf)"]);
4017        assert_eq!(matches.len(), 1);
4018        assert!(has_binding(&matches, &vars, &eg, &[("x", "a"), ("y", "b")]));
4019    }
4020
4021    #[test]
4022    fn verify_multi_pattern_bindings() {
4023        let mut eg = make_eg();
4024        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
4025        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
4026        eg.add(eg.ops().id_by_name("f").unwrap(), &[a, b]);
4027        eg.add(eg.ops().id_by_name("g").unwrap(), &[b]);
4028
4029        let (matches, vars) = query_named(&eg, eg.ops(), eg.sorts(), &["(f x y)", "(g y)"]);
4030        assert_eq!(matches.len(), 1);
4031        assert!(has_binding(&matches, &vars, &eg, &[("x", "a"), ("y", "b")]));
4032    }
4033
4034    /// Run a query, print the e-graph contents, pattern, and all matches with bindings.
4035    /// Then assert exact match count and check each expected binding is present.
4036    fn fmt_match<const TRACK: bool>(
4037        m: &Match<DefaultConfig>,
4038        vars: &MatchShape,
4039        eg: &EGraph<DefaultConfig, NiraLitVal, TRACK, false>,
4040        shape: &crate::resolve::MatchShape,
4041    ) -> String {
4042        let mut parts = Vec::new();
4043        // Node vars
4044        for (vi, name) in vars.nodes.iter().enumerate() {
4045            if name.starts_with('#') {
4046                continue;
4047            }
4048            if let Some(g) = m.nodes[vi] {
4049                parts.push(format!("{}={}", name, eg.node_op_name(g)));
4050            }
4051        }
4052        // Seq rests
4053        for i in 0..shape.num_seq_vars() {
4054            let s = m.seq_slice(SeqVarId(i as u16));
4055            let elems: Vec<&str> = s.iter().map(|&g| eg.node_op_name(g)).collect();
4056            parts.push(format!("seq{}=[{}]", i, elems.join(", ")));
4057        }
4058        // Set rests
4059        for i in 0..shape.num_set_vars() {
4060            let s = m.set_slice(SetVarId(i as u16));
4061            let elems: Vec<&str> = s.iter().map(|&g| eg.node_op_name(g)).collect();
4062            parts.push(format!("set{}={{{}}}", i, elems.join(", ")));
4063        }
4064        // Mset rests
4065        for i in 0..shape.num_mset_vars() {
4066            let s = m.mset_slice(MsetVarId(i as u16));
4067            let elems: Vec<String> = s
4068                .iter()
4069                .map(|c| {
4070                    format!(
4071                        "{}:{}",
4072                        eg.node_op_name(DefaultConfig::mset_child_id(c)),
4073                        DefaultConfig::mset_child_mult(c)
4074                    )
4075                })
4076                .collect();
4077            parts.push(format!("mset{}={{{}}}", i, elems.join(", ")));
4078        }
4079        // Mult vars
4080        for i in 0..shape.num_mult_vars() {
4081            parts.push(format!("mult{}={}", i, m.mults[i]));
4082        }
4083        parts.join(", ")
4084    }
4085
4086    fn check<const TRACK: bool>(
4087        eg: &EGraph<DefaultConfig, NiraLitVal, TRACK, false>,
4088        ops: &OpRegistry<OpId, SortId, TRACK>,
4089        sorts: &SortRegistry<SortId, TRACK>,
4090        label: &str,
4091        srcs: &[&str],
4092        expected_count: usize,
4093        expected: &[&[(&str, &str)]],
4094    ) {
4095        let model = NiraModel;
4096        let pats: Vec<_> = srcs.iter().map(|s| parse_pattern(s)).collect();
4097        let fq = flatten(&pats, ops).unwrap();
4098        let rq = resolve(
4099            &fq,
4100            ops,
4101            sorts,
4102            &model,
4103            &crate::resolve::GlobalCtx::<_, ()>::new(),
4104        )
4105        .unwrap();
4106        let plan = schedule(&rq);
4107        let index = IndexStore::build(eg);
4108        let index = VariantIndex::naive(&index);
4109        let matches = run_query(
4110            &plan,
4111            eg,
4112            &index,
4113            &crate::resolve::GlobalCtx::<(), _>::new(),
4114        );
4115
4116        println!("\n--- {label} ---");
4117        println!("  pattern: {}", srcs.join(" , "));
4118        println!("{} got match(es):", matches.len());
4119        for (i, m) in matches.iter().enumerate() {
4120            println!("    [{i}] {{ {} }}", fmt_match(m, &rq.shape, eg, &rq.shape));
4121        }
4122        assert_eq!(matches.len(), expected_count, "{label}: wrong match count");
4123        for (ei, exp) in expected.iter().enumerate() {
4124            assert!(
4125                has_binding(&matches, &rq.shape, eg, exp),
4126                "{label}: expected binding [{ei}] {:?} not found",
4127                exp
4128            );
4129        }
4130    }
4131
4132    // ===================================================================
4133    // AC (multiset) comprehensive tests
4134    // ===================================================================
4135
4136    #[test]
4137    fn ac_comprehensive() {
4138        let mut eg = make_eg();
4139        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
4140        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
4141        let _c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
4142
4143        // add(a,b) → {a:1, b:1}
4144        eg.add(eg.ops().id_by_name("add").unwrap(), &[a, b]);
4145        println!("\n=== AC node: add(a,b) = a:1, b:1 ===");
4146
4147        // Exact 2 vars, 2 elems
4148        check(
4149            &eg,
4150            eg.ops(),
4151            eg.sorts(),
4152            "AC exact {x:1 y:1} vs {a:1,b:1}",
4153            &["(add x:1 y:1)"],
4154            2,
4155            &[&[("x", "a"), ("y", "b")], &[("x", "b"), ("y", "a")]],
4156        );
4157
4158        // Subset 1 var + rest
4159        check(
4160            &eg,
4161            eg.ops(),
4162            eg.sorts(),
4163            "AC subset {x:1 ..rest} vs {a:1,b:1}",
4164            &["(add x:1 ..rest)"],
4165            2,
4166            &[&[("x", "a")], &[("x", "b")]],
4167        );
4168
4169        // Exact 1 var, 2 elems → no match (leftover)
4170        check(
4171            &eg,
4172            eg.ops(),
4173            eg.sorts(),
4174            "AC exact {x:1} vs {a:1,b:1}",
4175            &["(add x:1)"],
4176            0,
4177            &[],
4178        );
4179    }
4180
4181    #[test]
4182    fn ac_with_multiplicities() {
4183        let mut eg = make_eg();
4184        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
4185        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
4186
4187        // add(a,a,a,b,b) → {a:3, b:2}
4188        eg.add(eg.ops().id_by_name("add").unwrap(), &[a, a, a, b, b]);
4189        println!("\n=== AC node: add(a,a,a,b,b) = a:3, b:2 ===");
4190
4191        // x:2 ..rest → exact mult 2. b has 2 → match. a has 3 → no.
4192        check(
4193            &eg,
4194            eg.ops(),
4195            eg.sorts(),
4196            "AC {x:2 ..rest} vs {a:3,b:2}",
4197            &["(add x:2 ..rest)"],
4198            1,
4199            &[&[("x", "b")]],
4200        );
4201
4202        // x:3 ..rest → only a
4203        check(
4204            &eg,
4205            eg.ops(),
4206            eg.sorts(),
4207            "AC {x:3 ..rest} vs {a:3,b:2}",
4208            &["(add x:3 ..rest)"],
4209            1,
4210            &[&[("x", "a")]],
4211        );
4212
4213        // x:4 ..rest → nobody has mult==4
4214        check(
4215            &eg,
4216            eg.ops(),
4217            eg.sorts(),
4218            "AC {x:4 ..rest} vs {a:3,b:2}",
4219            &["(add x:4 ..rest)"],
4220            0,
4221            &[],
4222        );
4223
4224        // x:2 y:1 ..rest → x must have mult exactly 2, y exactly 1.
4225        // x=b(2), y=a? a has 3≠1 → no. x=b(2), y=? no other with mult 1 → no match.
4226        // Actually no other child has mult 1 either. So 0 matches.
4227        check(
4228            &eg,
4229            eg.ops(),
4230            eg.sorts(),
4231            "AC {x:2 y:1 ..rest} vs {a:3,b:2}",
4232            &["(add x:2 y:1 ..rest)"],
4233            0,
4234            &[],
4235        );
4236
4237        // Exact: x:3 y:2 → a:3,b:2 consumed exactly
4238        check(
4239            &eg,
4240            eg.ops(),
4241            eg.sorts(),
4242            "AC exact {x:3 y:2} vs {a:3,b:2}",
4243            &["(add x:3 y:2)"],
4244            1,
4245            &[&[("x", "a"), ("y", "b")]],
4246        );
4247    }
4248
4249    // ===================================================================
4250    // ACI (set / idempotent) comprehensive tests
4251    // ===================================================================
4252
4253    #[test]
4254    fn aci_comprehensive() {
4255        let mut eg = make_eg();
4256        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
4257        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
4258        let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
4259
4260        // union(a,b,c,a) → {a, b, c} (idempotent, deduped)
4261        eg.add(eg.ops().id_by_name("union").unwrap(), &[a, b, c, a]);
4262        println!("\n=== ACI node: union(a,b,c,a) = a, b, c ===");
4263
4264        // Exact 3 vars
4265        check(
4266            &eg,
4267            eg.ops(),
4268            eg.sorts(),
4269            "ACI exact {x y z} vs {a,b,c}",
4270            &["(union x y z)"],
4271            6,
4272            &[
4273                &[("x", "a"), ("y", "b"), ("z", "c")],
4274                &[("x", "a"), ("y", "c"), ("z", "b")],
4275                &[("x", "b"), ("y", "a"), ("z", "c")],
4276                &[("x", "b"), ("y", "c"), ("z", "a")],
4277                &[("x", "c"), ("y", "a"), ("z", "b")],
4278                &[("x", "c"), ("y", "b"), ("z", "a")],
4279            ],
4280        );
4281
4282        // Subset 1 var + rest
4283        check(
4284            &eg,
4285            eg.ops(),
4286            eg.sorts(),
4287            "ACI {x ..rest} vs {a,b,c}",
4288            &["(union x ..rest)"],
4289            3,
4290            &[&[("x", "a")], &[("x", "b")], &[("x", "c")]],
4291        );
4292
4293        // Subset 2 vars + rest
4294        check(
4295            &eg,
4296            eg.ops(),
4297            eg.sorts(),
4298            "ACI {x y ..rest} vs {a,b,c}",
4299            &["(union x y ..rest)"],
4300            6,
4301            &[
4302                &[("x", "a"), ("y", "b")],
4303                &[("x", "a"), ("y", "c")],
4304                &[("x", "b"), ("y", "a")],
4305                &[("x", "b"), ("y", "c")],
4306                &[("x", "c"), ("y", "a")],
4307                &[("x", "c"), ("y", "b")],
4308            ],
4309        );
4310
4311        // Just rest — match everything
4312        check(
4313            &eg,
4314            eg.ops(),
4315            eg.sorts(),
4316            "ACI {..rest} vs {a,b,c}",
4317            &["(union ..rest)"],
4318            1,
4319            &[],
4320        );
4321    }
4322
4323    #[test]
4324    fn aci_x_rest_printed() {
4325        let mut eg = make_eg();
4326        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
4327        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
4328        let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
4329        let d = eg.add(eg.ops().id_by_name("g").unwrap(), &[a]);
4330
4331        eg.add(eg.ops().id_by_name("union").unwrap(), &[a, b, c, d]);
4332
4333        let (matches, vars) = query_named(&eg, eg.ops(), eg.sorts(), &["(union x ..rest)"]);
4334
4335        println!("\n=== (union x ..rest) vs ACI node a, b, c, g(a) ===");
4336        println!("  {} matches:", matches.len());
4337
4338        let x_var = vars.find_var("x").unwrap();
4339        // rest is SetVarId(0) — the first (and only) set rest variable
4340        let rest_id = SetVarId(0);
4341        for (i, m) in matches.iter().enumerate() {
4342            let x_name = eg.node_op_name(m.get(x_var));
4343            let rest_slice = m.set_slice(rest_id);
4344            let rest_names: Vec<&str> = rest_slice.iter().map(|&g| eg.node_op_name(g)).collect();
4345            println!("  [{i}] x={x_name}  rest={{{}}}", rest_names.join(", "));
4346            // Rest should have exactly 3 elements
4347            assert_eq!(rest_slice.len(), 3, "rest should have 3 elements");
4348        }
4349
4350        assert_eq!(matches.len(), 4);
4351        let mut x_ops: Vec<String> = matches
4352            .iter()
4353            .map(|m| eg.node_op_name(m.get(x_var)).to_string())
4354            .collect();
4355        x_ops.sort();
4356        assert_eq!(x_ops, ["a", "b", "c", "g"]);
4357    }
4358
4359    // ===================================================================
4360    // A (sequence) comprehensive tests
4361    // ===================================================================
4362
4363    #[test]
4364    fn a_comprehensive() {
4365        let mut eg = make_eg();
4366        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
4367        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
4368        let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
4369
4370        // concat(a, b, c) → [a, b, c]
4371        eg.add(eg.ops().id_by_name("concat").unwrap(), &[a, b, c]);
4372        println!("\n=== A node: concat(a, b, c) = a, b, c ===");
4373
4374        // Exact [x y z]
4375        check(
4376            &eg,
4377            eg.ops(),
4378            eg.sorts(),
4379            "A exact [x y z] vs [a,b,c]",
4380            &["(concat x y z)"],
4381            1,
4382            &[&[("x", "a"), ("y", "b"), ("z", "c")]],
4383        );
4384
4385        // Exact wrong length [x y]
4386        check(
4387            &eg,
4388            eg.ops(),
4389            eg.sorts(),
4390            "A exact [x y] vs [a,b,c]",
4391            &["(concat x y)"],
4392            0,
4393            &[],
4394        );
4395
4396        // Prefix [..pre x]  — x = last elem
4397        check(
4398            &eg,
4399            eg.ops(),
4400            eg.sorts(),
4401            "A prefix [..pre x] vs [a,b,c]",
4402            &["(concat ..pre x)"],
4403            1,
4404            &[&[("x", "c")]],
4405        );
4406
4407        // Suffix [x ..suf]  — x = first elem
4408        check(
4409            &eg,
4410            eg.ops(),
4411            eg.sorts(),
4412            "A suffix [x ..suf] vs [a,b,c]",
4413            &["(concat x ..suf)"],
4414            1,
4415            &[&[("x", "a")]],
4416        );
4417
4418        // Suffix [x y ..suf]
4419        check(
4420            &eg,
4421            eg.ops(),
4422            eg.sorts(),
4423            "A suffix [x y ..suf] vs [a,b,c]",
4424            &["(concat x y ..suf)"],
4425            1,
4426            &[&[("x", "a"), ("y", "b")]],
4427        );
4428
4429        // Sliding [..pre x ..suf]  — 3 positions
4430        check(
4431            &eg,
4432            eg.ops(),
4433            eg.sorts(),
4434            "A sliding [..pre x ..suf] vs [a,b,c]",
4435            &["(concat ..pre x ..suf)"],
4436            3,
4437            &[&[("x", "a")], &[("x", "b")], &[("x", "c")]],
4438        );
4439
4440        // Sliding [..pre x y ..suf]  — 2 positions
4441        check(
4442            &eg,
4443            eg.ops(),
4444            eg.sorts(),
4445            "A sliding [..pre x y ..suf] vs [a,b,c]",
4446            &["(concat ..pre x y ..suf)"],
4447            2,
4448            &[&[("x", "a"), ("y", "b")], &[("x", "b"), ("y", "c")]],
4449        );
4450
4451        // Just rests [..pre ..suf]
4452        check(
4453            &eg,
4454            eg.ops(),
4455            eg.sorts(),
4456            "A [..pre ..suf] vs [a,b,c]",
4457            &["(concat ..pre ..suf)"],
4458            4,
4459            &[],
4460        ); // 4 split points: 0|3, 1|2, 2|1, 3|0
4461    }
4462
4463    // ===================================================================
4464    // Multi-variable + rest: AC, ACI, A
4465    // ===================================================================
4466
4467    #[test]
4468    fn aci_two_vars_plus_rest() {
4469        let mut eg = make_eg();
4470        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
4471        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
4472        let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
4473        let d = eg.add(eg.ops().id_by_name("g").unwrap(), &[a]);
4474        // union(a,b,c,g(a)) → {a, b, c, g(a)}
4475        eg.add(eg.ops().id_by_name("union").unwrap(), &[a, b, c, d]);
4476
4477        let (matches, vars) = query_named(&eg, eg.ops(), eg.sorts(), &["(union x y ..rest)"]);
4478        let x_var = vars.find_var("x").unwrap();
4479        let y_var = vars.find_var("y").unwrap();
4480
4481        println!("\n=== (union x y ..rest) vs a, b, c, g(a) ===");
4482        let rest_id = SetVarId(0);
4483        for (i, m) in matches.iter().enumerate() {
4484            let xn = eg.node_op_name(m.get(x_var));
4485            let yn = eg.node_op_name(m.get(y_var));
4486            let rest: Vec<&str> = m
4487                .set_slice(rest_id)
4488                .iter()
4489                .map(|&g| eg.node_op_name(g))
4490                .collect();
4491            println!("  [{i}] x={xn}, y={yn}, rest={{{}}}", rest.join(", "));
4492        }
4493
4494        // 4 elements, pick 2 ordered = 4*3 = 12
4495        assert_eq!(matches.len(), 12);
4496        // Every ordered pair of distinct elements should appear
4497        let names = ["a", "b", "c", "g"];
4498        for &x in &names {
4499            for &y in &names {
4500                if x == y {
4501                    continue;
4502                }
4503                assert!(
4504                    has_binding(&matches, &vars, &eg, &[("x", x), ("y", y)]),
4505                    "missing x={x}, y={y}"
4506                );
4507            }
4508        }
4509    }
4510
4511    #[test]
4512    fn ac_two_vars_plus_rest() {
4513        let mut eg = make_eg();
4514        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
4515        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
4516        let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
4517        // add(a, b, c) → {a:1, b:1, c:1}
4518        eg.add(eg.ops().id_by_name("add").unwrap(), &[a, b, c]);
4519
4520        let (matches, vars) = query_named(&eg, eg.ops(), eg.sorts(), &["(add x:1 y:1 ..rest)"]);
4521        let x_var = vars.find_var("x").unwrap();
4522        let y_var = vars.find_var("y").unwrap();
4523
4524        println!("\n=== (add x:1 y:1 ..rest) vs a:1, b:1, c:1 ===");
4525        let rest_id = MsetVarId(0);
4526        for (i, m) in matches.iter().enumerate() {
4527            let xn = eg.node_op_name(m.get(x_var));
4528            let yn = eg.node_op_name(m.get(y_var));
4529            let rest: Vec<String> = m
4530                .mset_slice(rest_id)
4531                .iter()
4532                .map(|c| {
4533                    let g = DefaultConfig::mset_child_id(c);
4534                    let k = DefaultConfig::mset_child_mult(c);
4535                    format!("{}:{}", eg.node_op_name(g), k)
4536                })
4537                .collect();
4538            println!("  [{i}] x={xn}, y={yn}, rest={{{}}}", rest.join(", "));
4539        }
4540
4541        // 3 elements, pick 2 ordered = 3*2 = 6
4542        assert_eq!(matches.len(), 6);
4543        let names = ["a", "b", "c"];
4544        for &x in &names {
4545            for &y in &names {
4546                if x == y {
4547                    continue;
4548                }
4549                assert!(
4550                    has_binding(&matches, &vars, &eg, &[("x", x), ("y", y)]),
4551                    "missing x={x}, y={y}"
4552                );
4553            }
4554        }
4555    }
4556
4557    #[test]
4558    fn ac_two_vars_with_mult_plus_rest() {
4559        let mut eg = make_eg();
4560        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
4561        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
4562        let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
4563        // add(a,a,a, b,b, c) → {a:3, b:2, c:1}
4564        eg.add(eg.ops().id_by_name("add").unwrap(), &[a, a, a, b, b, c]);
4565
4566        let (matches, vars) = query_named(&eg, eg.ops(), eg.sorts(), &["(add x:2 y:1 ..rest)"]);
4567        let x_var = vars.find_var("x").unwrap();
4568        let y_var = vars.find_var("y").unwrap();
4569
4570        println!("\n=== (add x:2 y:1 ..rest) vs a:3, b:2, c:1 ===");
4571        let rest_id = MsetVarId(0);
4572        for (i, m) in matches.iter().enumerate() {
4573            let xn = eg.node_op_name(m.get(x_var));
4574            let yn = eg.node_op_name(m.get(y_var));
4575            let rest: Vec<String> = m
4576                .mset_slice(rest_id)
4577                .iter()
4578                .map(|c| {
4579                    let g = DefaultConfig::mset_child_id(c);
4580                    let k = DefaultConfig::mset_child_mult(c);
4581                    format!("{}:{}", eg.node_op_name(g), k)
4582                })
4583                .collect();
4584            println!("  [{i}] x={xn}, y={yn}, rest={{{}}}", rest.join(", "));
4585        }
4586
4587        // x:2 means exactly mult 2. Against {a:3, b:2, c:1}:
4588        // x=b(mult==2) → residual {a:3, c:1}, y:1 → y=c(mult==1) → 1 match
4589        // x=a? a has 3≠2 → no. x=c? c has 1≠2 → no.
4590        // Total: 1
4591        assert_eq!(matches.len(), 1);
4592        assert!(has_binding(&matches, &vars, &eg, &[("x", "b"), ("y", "c")]));
4593    }
4594
4595    // ===================================================================
4596    // A (sequence) splits
4597    // ===================================================================
4598
4599    #[test]
4600    fn a_prefix_suffix_all_splits() {
4601        let mut eg = make_eg();
4602        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
4603        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
4604        let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
4605        let d = eg.add(eg.ops().id_by_name("g").unwrap(), &[a]);
4606        // concat(a, b, c, g(a)) → [a, b, c, g(a)]
4607        eg.add(eg.ops().id_by_name("concat").unwrap(), &[a, b, c, d]);
4608
4609        let (matches, _vars) = query_named(&eg, eg.ops(), eg.sorts(), &["(concat ..pre ..suf)"]);
4610
4611        println!("\n=== (concat ..pre ..suf) vs a, b, c, g(a) ===");
4612        println!("{} matches (split points):", matches.len());
4613        let pre_id = SeqVarId(0);
4614        let suf_id = SeqVarId(1);
4615        for (i, m) in matches.iter().enumerate() {
4616            let pre: Vec<&str> = m
4617                .seq_slice(pre_id)
4618                .iter()
4619                .map(|&g| eg.node_op_name(g))
4620                .collect();
4621            let suf: Vec<&str> = m
4622                .seq_slice(suf_id)
4623                .iter()
4624                .map(|&g| eg.node_op_name(g))
4625                .collect();
4626            println!("  [{i}] pre=[{}], suf=[{}]", pre.join(", "), suf.join(", "));
4627        }
4628
4629        // 4 elements → 5 split points: 0|4, 1|3, 2|2, 3|1, 4|0
4630        assert_eq!(matches.len(), 5);
4631    }
4632
4633    #[test]
4634    fn a_prefix_xy_suffix_all_positions() {
4635        let mut eg = make_eg();
4636        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
4637        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
4638        let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
4639        let d = eg.add(eg.ops().id_by_name("g").unwrap(), &[a]);
4640        // concat(a, b, c, g(a)) → [a, b, c, g(a)]
4641        eg.add(eg.ops().id_by_name("concat").unwrap(), &[a, b, c, d]);
4642
4643        let (matches, vars) = query_named(&eg, eg.ops(), eg.sorts(), &["(concat ..pre x y ..suf)"]);
4644        let x_var = vars.find_var("x").unwrap();
4645        let y_var = vars.find_var("y").unwrap();
4646
4647        println!("\n=== (concat ..pre x y ..suf) vs a, b, c, g(a) ===");
4648        let pre_id = SeqVarId(0);
4649        let suf_id = SeqVarId(1);
4650        for (i, m) in matches.iter().enumerate() {
4651            let xn = eg.node_op_name(m.get(x_var));
4652            let yn = eg.node_op_name(m.get(y_var));
4653            let pre: Vec<&str> = m
4654                .seq_slice(pre_id)
4655                .iter()
4656                .map(|&g| eg.node_op_name(g))
4657                .collect();
4658            let suf: Vec<&str> = m
4659                .seq_slice(suf_id)
4660                .iter()
4661                .map(|&g| eg.node_op_name(g))
4662                .collect();
4663            println!(
4664                "  [{i}] pre=[{}], x={xn}, y={yn}, suf=[{}]",
4665                pre.join(", "),
4666                suf.join(", ")
4667            );
4668        }
4669
4670        // 4 elements, window of 2 → 3 positions
4671        assert_eq!(matches.len(), 3);
4672        assert!(has_binding(&matches, &vars, &eg, &[("x", "a"), ("y", "b")])); // offset 0
4673        assert!(has_binding(&matches, &vars, &eg, &[("x", "b"), ("y", "c")])); // offset 1
4674        assert!(has_binding(&matches, &vars, &eg, &[("x", "c"), ("y", "g")])); // offset 2
4675    }
4676
4677    // ===================================================================
4678    // Iterator vs recursive comparison
4679    // ===================================================================
4680
4681    fn query_both<const TRACK: bool>(
4682        eg: &EGraph<DefaultConfig, NiraLitVal, TRACK, false>,
4683        ops: &OpRegistry<OpId, SortId, TRACK>,
4684        sorts: &SortRegistry<SortId, TRACK>,
4685        srcs: &[&str],
4686    ) -> (Vec<Match<DefaultConfig>>, Vec<Match<DefaultConfig>>) {
4687        let model = NiraModel;
4688        let pats: Vec<_> = srcs.iter().map(|s| parse_pattern(s)).collect();
4689        let fq = flatten(&pats, ops).unwrap();
4690        let rq = resolve(
4691            &fq,
4692            ops,
4693            sorts,
4694            &model,
4695            &crate::resolve::GlobalCtx::<_, ()>::new(),
4696        )
4697        .unwrap();
4698        let plan = schedule(&rq);
4699        let index = IndexStore::build(eg);
4700        let index = VariantIndex::naive(&index);
4701        let recursive = run_query(
4702            &plan,
4703            eg,
4704            &index,
4705            &crate::resolve::GlobalCtx::<(), _>::new(),
4706        );
4707        let iter = run_query_iter(&plan, eg, &index);
4708        (recursive, iter)
4709    }
4710
4711    fn env_key(m: &Match<DefaultConfig>, eg: &EG) -> Vec<Option<u32>> {
4712        m.nodes
4713            .iter()
4714            .map(|o| o.map(|g| eg.find_const(g).raw()))
4715            .collect()
4716    }
4717
4718    fn assert_same(
4719        label: &str,
4720        recursive: &[Match<DefaultConfig>],
4721        iter: &[Match<DefaultConfig>],
4722        eg: &EG,
4723    ) {
4724        assert_eq!(
4725            recursive.len(),
4726            iter.len(),
4727            "{label}: count mismatch (recursive={}, iter={})",
4728            recursive.len(),
4729            iter.len()
4730        );
4731        let mut rkeys: Vec<_> = recursive.iter().map(|m| env_key(m, eg)).collect();
4732        let mut ikeys: Vec<_> = iter.iter().map(|m| env_key(m, eg)).collect();
4733        rkeys.sort();
4734        ikeys.sort();
4735        assert_eq!(rkeys, ikeys, "{label}: binding mismatch");
4736    }
4737
4738    #[test]
4739    fn iter_vs_recursive_plain() {
4740        let mut eg = make_eg();
4741        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
4742        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
4743        let g_a = eg.add(eg.ops().id_by_name("g").unwrap(), &[a]);
4744        eg.add(eg.ops().id_by_name("f").unwrap(), &[a, b]);
4745        eg.add(eg.ops().id_by_name("f").unwrap(), &[b, g_a]);
4746
4747        for pat in &["(f x y)", "(f x (g y))", "(f x x)"] {
4748            let (r, i) = query_both(&eg, eg.ops(), eg.sorts(), &[pat]);
4749            assert_same(pat, &r, &i, &eg);
4750        }
4751    }
4752
4753    #[test]
4754    fn iter_vs_recursive_multi_pattern() {
4755        let mut eg = make_eg();
4756        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
4757        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
4758        eg.add(eg.ops().id_by_name("f").unwrap(), &[a, b]);
4759        eg.add(eg.ops().id_by_name("g").unwrap(), &[b]);
4760        let (r, i) = query_both(&eg, eg.ops(), eg.sorts(), &["(f x y)", "(g y)"]);
4761        assert_same("multi", &r, &i, &eg);
4762    }
4763
4764    #[test]
4765    fn iter_vs_recursive_ac() {
4766        let mut eg = make_eg();
4767        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
4768        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
4769        let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
4770        eg.add(eg.ops().id_by_name("add").unwrap(), &[a, b, c]);
4771        eg.add(eg.ops().id_by_name("add").unwrap(), &[a, a, a, b, b]);
4772
4773        for pat in &[
4774            "(add x:1 y:1)",
4775            "(add x:1 ..rest)",
4776            "(add x:2 ..rest)",
4777            "(add x:2 y:1 ..rest)",
4778            "(add x:3 y:2)",
4779        ] {
4780            let (r, i) = query_both(&eg, eg.ops(), eg.sorts(), &[pat]);
4781            assert_same(pat, &r, &i, &eg);
4782        }
4783    }
4784
4785    #[test]
4786    fn iter_vs_recursive_aci() {
4787        let mut eg = make_eg();
4788        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
4789        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
4790        let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
4791        let d = eg.add(eg.ops().id_by_name("g").unwrap(), &[a]);
4792        eg.add(eg.ops().id_by_name("union").unwrap(), &[a, b, c, d]);
4793
4794        for pat in &[
4795            "(union x y z)",
4796            "(union x ..rest)",
4797            "(union x y ..rest)",
4798            "(union ..rest)",
4799        ] {
4800            let (r, i) = query_both(&eg, eg.ops(), eg.sorts(), &[pat]);
4801            assert_same(pat, &r, &i, &eg);
4802        }
4803    }
4804
4805    #[test]
4806    fn iter_vs_recursive_a() {
4807        let mut eg = make_eg();
4808        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
4809        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
4810        let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
4811        eg.add(eg.ops().id_by_name("concat").unwrap(), &[a, b, c]);
4812
4813        for pat in &[
4814            "(concat x y z)",
4815            "(concat ..pre x)",
4816            "(concat x ..suf)",
4817            "(concat ..pre x ..suf)",
4818            "(concat ..pre x y ..suf)",
4819            "(concat ..pre ..suf)",
4820        ] {
4821            let (r, i) = query_both(&eg, eg.ops(), eg.sorts(), &[pat]);
4822            assert_same(pat, &r, &i, &eg);
4823        }
4824    }
4825
4826    // ===================================================================
4827    // Benchmark: recursive vs iterator
4828    // ===================================================================
4829
4830    #[test]
4831    fn bench_recursive_vs_iterator() {
4832        use crate::registry::AssocDir;
4833        // Build a dedicated registry with many nullary ops for distinct leaves.
4834        let model = NiraModel;
4835        let mut eg = EGraph::<DefaultConfig, NiraLitVal, false, false>::from_model(&model);
4836        let e = eg.intern_sort("IExpr");
4837        // 200 distinct nullary ops
4838        let leaf_names: Vec<String> = (0..200).map(|i| format!("n{i}")).collect();
4839        for name in &leaf_names {
4840            eg.register_op0(name, e);
4841        }
4842        eg.register_op2("f", e, e, e);
4843        eg.register_op1("g", e, e);
4844        eg.register_op2("h", e, e, e);
4845        eg.register_a("concat", e, e, AssocDir::Right);
4846        eg.register_mset("add", e, e);
4847        eg.register_set("union", e, e);
4848
4849        let mut leaves = Vec::new();
4850        for name in &leaf_names {
4851            leaves.push(eg.add(eg.ops().id_by_name(name).unwrap(), &[]));
4852        }
4853        for i in 0..100 {
4854            let a = leaves[i];
4855            let b = leaves[i + 100];
4856            eg.add(eg.ops().id_by_name("f").unwrap(), &[a, b]);
4857            eg.add(eg.ops().id_by_name("g").unwrap(), &[a]);
4858            eg.add(eg.ops().id_by_name("h").unwrap(), &[a, b]);
4859        }
4860        for i in 0..50 {
4861            eg.add(
4862                eg.ops().id_by_name("add").unwrap(),
4863                &[
4864                    leaves[i],
4865                    leaves[i + 50],
4866                    leaves[i + 100],
4867                    leaves[i],
4868                    leaves[i + 50],
4869                ],
4870            );
4871        }
4872        for i in 0..50 {
4873            eg.add(
4874                eg.ops().id_by_name("union").unwrap(),
4875                &[leaves[i], leaves[i + 50], leaves[i + 100], leaves[i + 150]],
4876            );
4877        }
4878        for i in 0..50 {
4879            eg.add(
4880                eg.ops().id_by_name("concat").unwrap(),
4881                &[leaves[i], leaves[i + 50], leaves[i + 100]],
4882            );
4883        }
4884
4885        let patterns: &[&str] = &[
4886            "(f x y)",
4887            "(f x (g y))",
4888            "(add x:1 ..rest)",
4889            "(add x:1 y:1 ..rest)",
4890            "(union x ..rest)",
4891            "(union x y ..rest)",
4892            "(concat ..pre x ..suf)",
4893            "(concat ..pre x y ..suf)",
4894        ];
4895
4896        let model = NiraModel;
4897        let index = IndexStore::build(&eg);
4898        let index = VariantIndex::naive(&index);
4899
4900        for pat in patterns {
4901            let p = parse_pattern(pat);
4902            let fq = flatten(&[p], eg.ops()).unwrap();
4903            let rq = resolve(
4904                &fq,
4905                eg.ops(),
4906                eg.sorts(),
4907                &model,
4908                &crate::resolve::GlobalCtx::<_, ()>::new(),
4909            )
4910            .unwrap();
4911            let plan = schedule(&rq);
4912
4913            let iters = 100;
4914
4915            let t0 = std::time::Instant::now();
4916            let mut n_rec = 0;
4917            for _ in 0..iters {
4918                n_rec = run_query(
4919                    &plan,
4920                    &eg,
4921                    &index,
4922                    &crate::resolve::GlobalCtx::<(), _>::new(),
4923                )
4924                .len();
4925            }
4926            let d_rec = t0.elapsed();
4927
4928            let t1 = std::time::Instant::now();
4929            let mut n_iter = 0;
4930            for _ in 0..iters {
4931                n_iter = run_query_iter(&plan, &eg, &index).len();
4932            }
4933            let d_iter = t1.elapsed();
4934
4935            assert_eq!(n_rec, n_iter);
4936            let us_rec = d_rec.as_micros() as f64 / iters as f64;
4937            let us_iter = d_iter.as_micros() as f64 / iters as f64;
4938            let ratio = us_iter / us_rec;
4939            println!(
4940                "{pat:40} matches={n_rec:5}  rec={us_rec:8.1}µs  iter={us_iter:8.1}µs  ratio={ratio:.2}x"
4941            );
4942        }
4943    }
4944
4945    // ===================================================================
4946    // MatchSet tests
4947    // ===================================================================
4948
4949    fn make_match_set<const TRACK: bool>(
4950        eg: &EGraph<DefaultConfig, NiraLitVal, TRACK, false>,
4951        ops: &OpRegistry<OpId, SortId, TRACK>,
4952        sorts: &SortRegistry<SortId, TRACK>,
4953        srcs: &[&str],
4954    ) -> (MatchSet<DefaultConfig>, crate::resolve::MatchShape) {
4955        let model = NiraModel;
4956        let pats: Vec<_> = srcs.iter().map(|s| parse_pattern(s)).collect();
4957        let fq = flatten(&pats, ops).unwrap();
4958        let rq = resolve(
4959            &fq,
4960            ops,
4961            sorts,
4962            &model,
4963            &crate::resolve::GlobalCtx::<_, ()>::new(),
4964        )
4965        .unwrap();
4966        let shape = rq.shape.clone();
4967        let plan = schedule(&rq);
4968        let index = IndexStore::build(eg);
4969        let index = VariantIndex::naive(&index);
4970        let ng = crate::resolve::GlobalCtx::<(), _>::new();
4971        let mut iter = MatchIterator::new(&plan, eg, &index, &ng);
4972        let set = iter.collect_set(&shape);
4973        (set, shape)
4974    }
4975
4976    /// Find VarId by name in a MatchShape.
4977    fn ni(shape: &crate::resolve::MatchShape, name: &str) -> VarId {
4978        let i = shape.nodes.iter().position(|n| n == name).unwrap();
4979        VarId::new(i as u16)
4980    }
4981
4982    #[test]
4983    fn matchset_plain_bindings() {
4984        let mut eg = make_eg();
4985        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
4986        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
4987        eg.add(eg.ops().id_by_name("f").unwrap(), &[a, b]);
4988        eg.add(eg.ops().id_by_name("f").unwrap(), &[b, a]);
4989
4990        let (set, shape) = make_match_set(&eg, eg.ops(), eg.sorts(), &["(f x y)"]);
4991        assert_eq!(set.count, 2);
4992        let xi = ni(&shape, "x");
4993        let yi = ni(&shape, "y");
4994        let mut pairs: Vec<_> = (0..set.count)
4995            .map(|j| {
4996                (
4997                    eg.find_const(set.get_node(xi, j)).raw(),
4998                    eg.find_const(set.get_node(yi, j)).raw(),
4999                )
5000            })
5001            .collect();
5002        pairs.sort();
5003        let a_r = eg.find_const(a).raw();
5004        let b_r = eg.find_const(b).raw();
5005        let mut expected = vec![(a_r, b_r), (b_r, a_r)];
5006        expected.sort();
5007        assert_eq!(pairs, expected);
5008    }
5009
5010    #[test]
5011    fn matchset_ac_with_mset_rest() {
5012        let mut eg = make_eg();
5013        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
5014        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
5015        let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
5016        eg.add(eg.ops().id_by_name("add").unwrap(), &[a, b, c]);
5017
5018        let (set, shape) = make_match_set(&eg, eg.ops(), eg.sorts(), &["(add x:1 ..rest)"]);
5019        assert_eq!(set.count, 3);
5020        assert_eq!(shape.msets.len(), 1);
5021        let xi = ni(&shape, "x");
5022        for j in 0..set.count {
5023            let rest_slice = set.mset_slice(MsetVarId(0), j);
5024            // x takes 1 element, rest has 2
5025            assert_eq!(
5026                rest_slice.len(),
5027                2,
5028                "match {j}: rest should have 2 elements"
5029            );
5030            // x + rest should recompose to {a, b, c}
5031            let mut ids: Vec<u32> = rest_slice
5032                .iter()
5033                .map(|c| eg.find_const(DefaultConfig::mset_child_id(c)).raw())
5034                .collect();
5035            ids.push(eg.find_const(set.get_node(xi, j)).raw());
5036            ids.sort();
5037            let mut orig = vec![
5038                eg.find_const(a).raw(),
5039                eg.find_const(b).raw(),
5040                eg.find_const(c).raw(),
5041            ];
5042            orig.sort();
5043            assert_eq!(ids, orig, "match {j}: recomposition failed");
5044        }
5045    }
5046
5047    #[test]
5048    fn matchset_aci_with_set_rest() {
5049        let mut eg = make_eg();
5050        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
5051        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
5052        let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
5053        eg.add(eg.ops().id_by_name("union").unwrap(), &[a, b, c]);
5054
5055        let (set, shape) = make_match_set(&eg, eg.ops(), eg.sorts(), &["(union x ..rest)"]);
5056        assert_eq!(set.count, 3);
5057        assert_eq!(shape.sets.len(), 1);
5058        let xi = ni(&shape, "x");
5059        for j in 0..set.count {
5060            let rest_slice = set.set_slice(SetVarId(0), j);
5061            assert_eq!(rest_slice.len(), 2);
5062            let mut ids: Vec<u32> = rest_slice.iter().map(|&g| eg.find_const(g).raw()).collect();
5063            ids.push(eg.find_const(set.get_node(xi, j)).raw());
5064            ids.sort();
5065            let mut orig = vec![
5066                eg.find_const(a).raw(),
5067                eg.find_const(b).raw(),
5068                eg.find_const(c).raw(),
5069            ];
5070            orig.sort();
5071            assert_eq!(ids, orig, "match {j}: recomposition failed");
5072        }
5073    }
5074
5075    #[test]
5076    fn matchset_a_sliding_window() {
5077        let mut eg = make_eg();
5078        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
5079        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
5080        let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
5081        eg.add(eg.ops().id_by_name("concat").unwrap(), &[a, b, c]);
5082
5083        let (set, shape) = make_match_set(&eg, eg.ops(), eg.sorts(), &["(concat ..pre x ..suf)"]);
5084        assert_eq!(set.count, 3);
5085        assert_eq!(shape.seqs.len(), 2);
5086        let xi = ni(&shape, "x");
5087        for j in 0..set.count {
5088            let pre_s = set.seq_slice(SeqVarId(0), j);
5089            let suf_s = set.seq_slice(SeqVarId(1), j);
5090            // pre + [x] + suf should recompose to [a, b, c]
5091            let mut recomp: Vec<u32> = pre_s.iter().map(|&g| eg.find_const(g).raw()).collect();
5092            recomp.push(eg.find_const(set.get_node(xi, j)).raw());
5093            recomp.extend(suf_s.iter().map(|&g| eg.find_const(g).raw()));
5094            let orig: Vec<u32> = [a, b, c].iter().map(|&g| eg.find_const(g).raw()).collect();
5095            assert_eq!(recomp, orig, "match {j}: recomposition failed");
5096        }
5097    }
5098
5099    #[test]
5100    fn matchset_agrees_with_vec_match() {
5101        // Verify MatchSet contents match Vec<Match> from recursive engine.
5102        let mut eg = make_eg();
5103        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
5104        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
5105        let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
5106        eg.add(eg.ops().id_by_name("add").unwrap(), &[a, a, b, c]);
5107
5108        let model = NiraModel;
5109        let pat = parse_pattern("(add x:1 y:1 ..rest)");
5110        let fq = flatten(&[pat], eg.ops()).unwrap();
5111        let rq = resolve(
5112            &fq,
5113            eg.ops(),
5114            eg.sorts(),
5115            &model,
5116            &crate::resolve::GlobalCtx::<_, ()>::new(),
5117        )
5118        .unwrap();
5119        let plan = schedule(&rq);
5120        let index = IndexStore::build(&eg);
5121        let index = VariantIndex::naive(&index);
5122
5123        let ng = crate::resolve::GlobalCtx::<(), _>::new();
5124        let vec_matches = run_query(&plan, &eg, &index, &ng);
5125        let shape = rq.shape.clone();
5126        let mut iter = MatchIterator::new(&plan, &eg, &index, &ng);
5127        let set = iter.collect_set(&shape);
5128
5129        assert_eq!(vec_matches.len(), set.count);
5130        let xi = ni(&shape, "x");
5131        let yi = ni(&shape, "y");
5132        let x_vid = shape.find_var("x").unwrap();
5133        let y_vid = shape.find_var("y").unwrap();
5134        for j in 0..set.count {
5135            assert_eq!(
5136                eg.find_const(set.get_node(xi, j)),
5137                eg.find_const(vec_matches[j].get(x_vid))
5138            );
5139            assert_eq!(
5140                eg.find_const(set.get_node(yi, j)),
5141                eg.find_const(vec_matches[j].get(y_vid))
5142            );
5143            assert_eq!(
5144                set.mset_slice(MsetVarId(0), j).len(),
5145                vec_matches[j].mset_slice(MsetVarId(0)).len()
5146            );
5147        }
5148    }
5149
5150    #[test]
5151    fn matchset_empty() {
5152        let eg = make_eg();
5153        let (set, _) = make_match_set(&eg, eg.ops(), eg.sorts(), &["(f x y)"]);
5154        assert_eq!(set.count, 0);
5155    }
5156
5157    #[test]
5158    fn cloned_iter_filter_take() {
5159        let mut eg = make_eg();
5160        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
5161        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
5162        let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
5163        eg.add(eg.ops().id_by_name("union").unwrap(), &[a, b, c]);
5164
5165        let model = NiraModel;
5166        let pat = parse_pattern("(union x ..rest)");
5167        let fq = flatten(&[pat], eg.ops()).unwrap();
5168        let rq = resolve(
5169            &fq,
5170            eg.ops(),
5171            eg.sorts(),
5172            &model,
5173            &crate::resolve::GlobalCtx::<_, ()>::new(),
5174        )
5175        .unwrap();
5176        let plan = schedule(&rq);
5177        let index = IndexStore::build(&eg);
5178        let index = VariantIndex::naive(&index);
5179
5180        let x = rq.shape.find_var("x").unwrap();
5181        // Use cloned_iter with filter + take
5182        let ng = crate::resolve::GlobalCtx::<(), _>::new();
5183        let iter = MatchIterator::new(&plan, &eg, &index, &ng);
5184        let filtered: Vec<Match<DefaultConfig>> = iter
5185            .cloned_iter()
5186            .filter(|m| eg.find_const(m.get(x)) != eg.find_const(a))
5187            .take(2)
5188            .collect();
5189        // 3 total matches (x=a, x=b, x=c), filter out x=a → 2 remain, take(2) gets both
5190        assert_eq!(filtered.len(), 2);
5191        for m in &filtered {
5192            assert_ne!(eg.find_const(m.get(x)), eg.find_const(a));
5193        }
5194    }
5195
5196    #[test]
5197    fn ac_concrete_with_higher_mult() {
5198        // (Add (a) (a) (b)) → AC node {a:2, b:1}
5199        // Pattern: (add (a) ..rest) — concrete (a) with implicit :1
5200        // Question: does this match when a has multiplicity 2?
5201        let mut eg = make_eg();
5202        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
5203        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
5204        let _add = eg.add(eg.ops().id_by_name("add").unwrap(), &[a, a, b]);
5205
5206        let (matches, shape) = query_named(&eg, eg.ops(), eg.sorts(), &["(add (a) ..rest)"]);
5207        eprintln!("=== (add (a) ..rest) against {{a:2, b:1}} ===");
5208        eprintln!("match count: {}", matches.len());
5209        for (i, m) in matches.iter().enumerate() {
5210            let bindings = binding_map(m, &shape, &eg);
5211            eprintln!("  match {i}: {bindings:?}");
5212            for (mi, name) in shape.msets.iter().enumerate() {
5213                let (start, len) = m.mset_spans[mi];
5214                let rest: Vec<_> = m.mset_pool[start as usize..(start + len) as usize]
5215                    .iter()
5216                    .map(|c| format!("{:?}", c))
5217                    .collect();
5218                eprintln!("    {name} = [{rest}]", rest = rest.join(", "));
5219            }
5220        }
5221
5222        // Also test: (add (a):k ..rest) — bind k to multiplicity
5223        let (matches2, shape2) = query_named(&eg, eg.ops(), eg.sorts(), &["(add (a):k ..rest)"]);
5224        eprintln!("\n=== (add (a):k ..rest) against {{a:2, b:1}} ===");
5225        eprintln!("match count: {}", matches2.len());
5226        for (i, m) in matches2.iter().enumerate() {
5227            let bindings = binding_map(m, &shape2, &eg);
5228            eprintln!("  match {i}: {bindings:?}");
5229            for (mi, name) in shape2.msets.iter().enumerate() {
5230                let (start, len) = m.mset_spans[mi];
5231                let rest: Vec<_> = m.mset_pool[start as usize..(start + len) as usize]
5232                    .iter()
5233                    .map(|c| format!("{:?}", c))
5234                    .collect();
5235                eprintln!("    {name} = [{rest}]", rest = rest.join(", "));
5236            }
5237            for (mi, name) in shape2.mults.iter().enumerate() {
5238                eprintln!("    {name} = {}", m.mults[mi]);
5239            }
5240        }
5241    }
5242
5243    #[test]
5244    fn ac_constraint_ge() {
5245        // {a:3, b:1, c:2}
5246        let mut eg = make_eg();
5247        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
5248        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
5249        let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
5250        eg.add(eg.ops().id_by_name("add").unwrap(), &[a, a, a, b, c, c]);
5251
5252        // x:k>=2 ..rest → matches a (k=3) and c (k=2), not b (k=1)
5253        let (matches, vars) = query_named(&eg, eg.ops(), eg.sorts(), &["(add x:k>=2 ..rest)"]);
5254        eprintln!("\n=== (add x:k>=2 ..rest) against {{a:3, b:1, c:2}} ===");
5255        for (i, m) in matches.iter().enumerate() {
5256            let bindings = binding_map(m, &vars, &eg);
5257            let k = m.mults[0];
5258            eprintln!("  match {i}: {bindings:?}, k={k}");
5259        }
5260        assert_eq!(matches.len(), 2);
5261        assert!(has_binding(&matches, &vars, &eg, &[("x", "a")]));
5262        assert!(has_binding(&matches, &vars, &eg, &[("x", "c")]));
5263    }
5264
5265    #[test]
5266    fn ac_constraint_le() {
5267        // {a:3, b:1, c:2}
5268        let mut eg = make_eg();
5269        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
5270        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
5271        let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
5272        eg.add(eg.ops().id_by_name("add").unwrap(), &[a, a, a, b, c, c]);
5273
5274        // x:k<=2 ..rest → matches b (k=1) and c (k=2), not a (k=3)
5275        let (matches, vars) = query_named(&eg, eg.ops(), eg.sorts(), &["(add x:k<=2 ..rest)"]);
5276        eprintln!("\n=== (add x:k<=2 ..rest) against {{a:3, b:1, c:2}} ===");
5277        for (i, m) in matches.iter().enumerate() {
5278            let bindings = binding_map(m, &vars, &eg);
5279            let k = m.mults[0];
5280            eprintln!("  match {i}: {bindings:?}, k={k}");
5281        }
5282        assert_eq!(matches.len(), 2);
5283        assert!(has_binding(&matches, &vars, &eg, &[("x", "b")]));
5284        assert!(has_binding(&matches, &vars, &eg, &[("x", "c")]));
5285    }
5286
5287    #[test]
5288    fn ac_nonlinear_mult_same_count() {
5289        // {a:2, b:2, c:3}
5290        // Pattern: (add x:k y:k ..rest) — x and y must have the SAME multiplicity
5291        let mut eg = make_eg();
5292        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
5293        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
5294        let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
5295        eg.add(eg.ops().id_by_name("add").unwrap(), &[a, a, b, b, c, c, c]);
5296
5297        let (matches, vars) = query_named(&eg, eg.ops(), eg.sorts(), &["(add x:k y:k ..rest)"]);
5298        eprintln!("\n=== (add x:k y:k ..rest) against {{a:2, b:2, c:3}} ===");
5299        for (i, m) in matches.iter().enumerate() {
5300            let bindings = binding_map(m, &vars, &eg);
5301            let k = m.mults[0];
5302            eprintln!("  match {i}: {bindings:?}, k={k}");
5303        }
5304        // x and y must have the same multiplicity k.
5305        // a:2 and b:2 both have mult 2 → x=a,y=b and x=b,y=a (k=2)
5306        // c:3 has no partner with mult 3 → no match involving c
5307        // Expected: 2 matches
5308        assert_eq!(matches.len(), 2);
5309        assert!(has_binding(&matches, &vars, &eg, &[("x", "a"), ("y", "b")]));
5310        assert!(has_binding(&matches, &vars, &eg, &[("x", "b"), ("y", "a")]));
5311    }
5312
5313    #[test]
5314    fn ac_nonlinear_mult_no_match() {
5315        // {a:1, b:2, c:3} — all different multiplicities
5316        // Pattern: (add x:k y:k ..rest) — no two elements have the same mult
5317        let mut eg = make_eg();
5318        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
5319        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
5320        let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
5321        eg.add(eg.ops().id_by_name("add").unwrap(), &[a, b, b, c, c, c]);
5322
5323        let (matches, vars) = query_named(&eg, eg.ops(), eg.sorts(), &["(add x:k y:k ..rest)"]);
5324        eprintln!("\n=== (add x:k y:k ..rest) against {{a:1, b:2, c:3}} ===");
5325        for (i, m) in matches.iter().enumerate() {
5326            let bindings = binding_map(m, &vars, &eg);
5327            let k = m.mults[0];
5328            eprintln!("  match {i}: {bindings:?}, k={k}");
5329        }
5330        // No two elements share the same multiplicity → 0 matches
5331        assert_eq!(matches.len(), 0);
5332    }
5333
5334    #[test]
5335    fn ac_nonlinear_empty_interval() {
5336        // Pattern: (add x:k>=3 y:k<=1 ..rest)
5337        // Interval for k: [3, ∞) ∩ (-∞, 1] = [3, 1] = empty
5338        // This should be rejected at resolve time as unsatisfiable.
5339        let mut eg = make_eg();
5340        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
5341        eg.add(eg.ops().id_by_name("add").unwrap(), &[a, a, a]);
5342
5343        let model = NiraModel;
5344        let pats: Vec<_> = ["(add x:k>=3 y:k<=1 ..rest)"]
5345            .iter()
5346            .map(|s| parse_pattern(s))
5347            .collect();
5348        let fq = flatten(&pats, eg.ops()).unwrap();
5349        let result = resolve(
5350            &fq,
5351            eg.ops(),
5352            eg.sorts(),
5353            &model,
5354            &crate::resolve::GlobalCtx::<_, ()>::new(),
5355        );
5356        eprintln!("\n=== (add x:k>=3 y:k<=1 ..rest) — empty interval ===");
5357        eprintln!("resolve result: {result:?}");
5358        // Should be an error: unsatisfiable multiplicity
5359        assert!(result.is_err(), "expected unsatisfiable interval error");
5360    }
5361
5362    #[test]
5363    fn ac_nonlinear_narrow_interval() {
5364        // Pattern: (add x:k>=2 y:k<=3 ..rest)
5365        // Interval for k: [2, 3]. Only elements with mult 2 or 3 qualify.
5366        // Against {a:1, b:2, c:3, d:4}: only b(2) and c(3) are in [2,3]
5367        // x:k>=2 y:k<=3 with same k → x and y must have the SAME mult in [2,3]
5368        // b:2 and c:3 have different mults → no pair matches
5369        // But b:2 and b:2 would match if b appeared twice... it doesn't.
5370        // So: 0 matches.
5371        let mut eg = make_eg();
5372        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
5373        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
5374        let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
5375        eg.add(eg.ops().id_by_name("add").unwrap(), &[a, b, b, c, c, c]);
5376
5377        let (matches, vars) =
5378            query_named(&eg, eg.ops(), eg.sorts(), &["(add x:k>=2 y:k<=3 ..rest)"]);
5379        eprintln!("\n=== (add x:k>=2 y:k<=3 ..rest) against {{a:1, b:2, c:3}} ===");
5380        for (i, m) in matches.iter().enumerate() {
5381            let bindings = binding_map(m, &vars, &eg);
5382            let k = m.mults[0];
5383            eprintln!("  match {i}: {bindings:?}, k={k}");
5384        }
5385        // b has mult 2 (in [2,3]), c has mult 3 (in [2,3]), but 2≠3 → non-linear fails
5386        // a has mult 1 (not in [2,3])
5387        assert_eq!(matches.len(), 0);
5388    }
5389
5390    // -----------------------------------------------------------------------
5391    // Snapshot semantics: the match set does not depend on the join order
5392    // -----------------------------------------------------------------------
5393
5394    /// Schedule `srcs` with `first`'s operator forced to the front of the
5395    /// greedy order, by handing the scheduler a cardinality of 0 for it.
5396    /// The other operators get an equal, large cardinality, so nothing but the
5397    /// pin decides the first atom.
5398    fn plan_driven_from(
5399        eg: &EG,
5400        srcs: &[&str],
5401        first: &str,
5402        ops_in_query: &[&str],
5403    ) -> (RQ, QueryPlan<OpId, u32, NiraLitVal>) {
5404        let rq = resolve_srcs(eg, srcs);
5405        let mut stats = crate::schedule::IndexStats::<OpId>::new();
5406        for name in ops_in_query {
5407            stats
5408                .op_card
5409                .insert(eg.ops().id_by_name(name).unwrap(), 1000);
5410        }
5411        stats.op_card.insert(eg.ops().id_by_name(first).unwrap(), 0);
5412        let plan = crate::schedule::schedule_with_stats(&rq, &stats);
5413        (rq, plan)
5414    }
5415
5416    type RQ = crate::resolve::ResolvedQuery<OpId, SortId, NiraLitVal>;
5417
5418    /// Compile and resolve `srcs` against `eg`'s registries.
5419    fn resolve_srcs(eg: &EG, srcs: &[&str]) -> RQ {
5420        let pats: Vec<_> = srcs.iter().map(|s| parse_pattern(s)).collect();
5421        let fq = flatten(&pats, eg.ops()).unwrap();
5422        resolve(
5423            &fq,
5424            eg.ops(),
5425            eg.sorts(),
5426            &NiraModel,
5427            &crate::resolve::GlobalCtx::<SortId, ()>::new(),
5428        )
5429        .unwrap()
5430    }
5431
5432    /// Run the query through all three engines and return the match set as a
5433    /// sorted list of binding keys.
5434    ///
5435    /// The three must agree. Static push against static pull is the check that
5436    /// was already here: two independent walks of one plan. Runtime-scheduled
5437    /// push against static pull is the oracle for the scheduling flag, and it is
5438    /// the strongest one available, because the pull engine shares nothing with
5439    /// the flag — it is a different control structure (an explicit stack, not
5440    /// recursion) walking a different atom order (the plan's, fixed) — so an
5441    /// agreement between them is not two copies of the same mistake.
5442    ///
5443    /// A divergence here is a bug in its own right, so it is asserted rather
5444    /// than returned.
5445    fn match_keys(
5446        eg: &EG,
5447        rq: &RQ,
5448        plan: &QueryPlan<OpId, u32, NiraLitVal>,
5449        index: &IndexStore<DefaultConfig>,
5450    ) -> Vec<Vec<Option<u32>>> {
5451        let vindex = VariantIndex::naive(index);
5452        let ng = crate::resolve::GlobalCtx::<SortId, _>::new();
5453
5454        let key = |m: &Match<DefaultConfig>| -> Vec<Option<u32>> {
5455            m.nodes
5456                .iter()
5457                .map(|o| o.map(|g| index.round_repr(g).unwrap_or(g).raw()))
5458                .collect()
5459        };
5460
5461        let mut recursive: Vec<_> = run_query(plan, eg, &vindex, &ng).iter().map(key).collect();
5462        let mut it = MatchIterator::new(plan, eg, &vindex, &ng);
5463        let mut pull = Vec::new();
5464        while it.next_match() {
5465            pull.push(key(it.env()));
5466        }
5467        set_runtime_scheduling(true);
5468        let mut adaptive: Vec<_> = run_query_scheduled(rq, plan, eg, &vindex, &ng)
5469            .iter()
5470            .map(key)
5471            .collect();
5472        set_runtime_scheduling(false);
5473        recursive.sort();
5474        pull.sort();
5475        adaptive.sort();
5476        assert_eq!(recursive, pull, "the two matcher engines disagree");
5477        assert_eq!(
5478            adaptive, pull,
5479            "runtime atom scheduling changed the match set"
5480        );
5481        recursive
5482    }
5483
5484    /// `(f b c)` and `(g a)`, with `c` and `(g a)` in different classes at the
5485    /// index build and merged afterwards — the shape of a mid-round merge by an
5486    /// earlier rule's actions. `tall_g_class` decides which of the two classes
5487    /// the union-find keeps as representative, by giving the `g`-node's class a
5488    /// second member (hence a taller tree) before the build.
5489    ///
5490    /// The snapshot answer for `(f x (g y))` is *no match*: at the build,
5491    /// `(f b c)`'s second child was alone in its class and that class held no
5492    /// `g`-node.
5493    fn mid_round_merge(tall_g_class: bool) -> (EG, IndexStore<DefaultConfig>) {
5494        let mut eg = make_eg();
5495        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
5496        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
5497        let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
5498        let ga = eg.add(eg.ops().id_by_name("g").unwrap(), &[a]);
5499        let _fbc = eg.add(eg.ops().id_by_name("f").unwrap(), &[b, c]);
5500        if tall_g_class {
5501            let haa = eg.add(eg.ops().id_by_name("h").unwrap(), &[a, a]);
5502            eg.merge(ga, haa);
5503        }
5504        eg.rebuild();
5505
5506        // The round's index. Everything after this point is what a rule's
5507        // actions do to the e-graph while later rules of the same round match.
5508        let index = IndexStore::build(&eg);
5509        eg.merge(c, ga);
5510        (eg, index)
5511    }
5512
5513    /// The match set is a function of the e-graph the round's index was built
5514    /// from, not of the join order the scheduler happened to choose.
5515    ///
5516    /// Both orders below reach the `g` atom by a different access path — from
5517    /// the `f` atom it is `ByRepr` on the extracted child, from the `g` atom it
5518    /// is `ByChildPos` on the bound `g`-node — and a mid-round merge moves the
5519    /// two paths in opposite directions: whichever class the union-find keeps,
5520    /// exactly one of the two paths lands on a bucket that the merge made
5521    /// reachable. Canonicalizing with the live union-find therefore made one
5522    /// order report a match and the other none, on the same e-graph. Both
5523    /// parameterizations are here because they disagree in opposite directions;
5524    /// which one a given union-by-rank policy produces is not this test's
5525    /// business.
5526    #[test]
5527    fn match_set_is_independent_of_join_order() {
5528        for tall_g_class in [false, true] {
5529            let (eg, index) = mid_round_merge(tall_g_class);
5530            let from_f = plan_driven_from(&eg, &["(f x (g y))"], "f", &["f", "g"]);
5531            let from_g = plan_driven_from(&eg, &["(f x (g y))"], "g", &["f", "g"]);
5532
5533            // The pin is worth nothing if both orders compile to the same plan.
5534            assert_ne!(
5535                from_f.1.steps, from_g.1.steps,
5536                "the two pins produced the same plan (tall_g_class={tall_g_class})"
5537            );
5538
5539            let mf = match_keys(&eg, &from_f.0, &from_f.1, &index);
5540            let mg = match_keys(&eg, &from_g.0, &from_g.1, &index);
5541            assert_eq!(
5542                mf, mg,
5543                "join order changed the match set (tall_g_class={tall_g_class})"
5544            );
5545            assert!(
5546                mf.is_empty(),
5547                "matched a class membership the round's index does not have \
5548                 (tall_g_class={tall_g_class}): {mf:?}"
5549            );
5550        }
5551    }
5552
5553    /// The other half of the same contract, on the equality-check path rather
5554    /// than the index path: two children that the round's index kept apart do
5555    /// not satisfy a non-linear pattern just because a later merge joined them.
5556    /// `CheckChildEq` used to test live equality, which admitted the match.
5557    #[test]
5558    fn nonlinear_check_uses_the_rounds_classes() {
5559        let mut eg = make_eg();
5560        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
5561        let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
5562        let _fbc = eg.add(eg.ops().id_by_name("f").unwrap(), &[b, c]);
5563        eg.merge(b, c);
5564        eg.rebuild();
5565
5566        let index = IndexStore::build(&eg);
5567        let driven = plan_driven_from(&eg, &["(f x x)"], "f", &["f"]);
5568        assert_eq!(
5569            match_keys(&eg, &driven.0, &driven.1, &index).len(),
5570            1,
5571            "control: a merge the index build can see does make the pattern match"
5572        );
5573
5574        let mut eg = make_eg();
5575        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
5576        let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
5577        let _fbc = eg.add(eg.ops().id_by_name("f").unwrap(), &[b, c]);
5578        eg.rebuild();
5579        let index = IndexStore::build(&eg);
5580        eg.merge(b, c);
5581        let driven = plan_driven_from(&eg, &["(f x x)"], "f", &["f"]);
5582        let matches = match_keys(&eg, &driven.0, &driven.1, &index);
5583        assert!(
5584            matches.is_empty(),
5585            "a merge after the index build made `(f x x)` match: {matches:?}"
5586        );
5587    }
5588
5589    // -----------------------------------------------------------------------
5590    // Pre-bound children of a variadic, multiset or set pattern
5591    // -----------------------------------------------------------------------
5592    //
5593    // Each of the three decompositions binds the pattern's children one at a
5594    // time and backtracks over the alternatives. A child variable an earlier
5595    // atom already bound is a constraint on the node's children, so the
5596    // decomposition checks it and its cleanup leaves it bound. `plan_driven_from`
5597    // pins the atom that binds it to the front of the plan, which is what makes
5598    // the variable pre-bound when the decomposition runs.
5599
5600    /// `(g x)` pins `x`, so `(concat ..pre x ..suf)` matches only at the windows
5601    /// where `x`'s class sits: two positions per `concat` node, four in total.
5602    /// Cleanup that unbinds `x` after a window leaves the next window free to
5603    /// rebind it, which admits every position of both nodes.
5604    #[test]
5605    fn expand_a_checks_a_prebound_fixed_child() {
5606        let mut eg = make_eg();
5607        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
5608        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
5609        let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
5610        eg.add(eg.ops().id_by_name("g").unwrap(), &[a]);
5611        eg.add(eg.ops().id_by_name("g").unwrap(), &[c]);
5612        let cat = eg.ops().id_by_name("concat").unwrap();
5613        eg.add(cat, &[a, b, c]);
5614        eg.add(cat, &[c, a, b]);
5615        eg.rebuild();
5616
5617        let index = IndexStore::build(&eg);
5618        let driven = plan_driven_from(
5619            &eg,
5620            &["(g x)", "(concat ..pre x ..suf)"],
5621            "g",
5622            &["g", "concat"],
5623        );
5624        let matches = match_keys(&eg, &driven.0, &driven.1, &index);
5625        assert_eq!(
5626            matches.len(),
5627            4,
5628            "expected x=a and x=c once per concat node: {matches:?}"
5629        );
5630
5631        // The same plan through the push engine, checked at the binding level:
5632        // `b` is a member of both sequences and of neither `g` node, so it is
5633        // the class an unbound window admits.
5634        let vindex = VariantIndex::naive(&index);
5635        let ms = run_query(
5636            &driven.1,
5637            &eg,
5638            &vindex,
5639            &crate::resolve::GlobalCtx::<(), _>::new(),
5640        );
5641        assert_eq!(ms.len(), 4);
5642        assert!(has_binding(&ms, &driven.0.shape, &eg, &[("x", "a")]));
5643        assert!(has_binding(&ms, &driven.0.shape, &eg, &[("x", "c")]));
5644        assert!(!has_binding(&ms, &driven.0.shape, &eg, &[("x", "b")]));
5645    }
5646
5647    /// The same shape at its minimum: one `g` node and one `concat` node, which is
5648    /// the case both engines got wrong in the same direction. Before the fix all
5649    /// three engines returned three matches, one per window, and the differential
5650    /// assertion in [`match_keys`] passed on that answer: the push and pull engines
5651    /// carried the same defect, so their agreement was not evidence. The count below
5652    /// is the assertion that fails.
5653    #[test]
5654    fn expand_a_prebound_child_oracle_blind_spot() {
5655        let mut eg = make_eg();
5656        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
5657        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
5658        let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
5659        eg.add(eg.ops().id_by_name("g").unwrap(), &[a]);
5660        eg.add(eg.ops().id_by_name("concat").unwrap(), &[a, b, c]);
5661        eg.rebuild();
5662
5663        let index = IndexStore::build(&eg);
5664        let driven = plan_driven_from(
5665            &eg,
5666            &["(g x)", "(concat ..pre x ..suf)"],
5667            "g",
5668            &["g", "concat"],
5669        );
5670        let matches = match_keys(&eg, &driven.0, &driven.1, &index);
5671        assert_eq!(
5672            matches.len(),
5673            1,
5674            "only the window at `a` matches: {matches:?}"
5675        );
5676    }
5677
5678    /// The multiset counterpart: `(g x)` pins `x`, so `(add x:1 ..rest)` matches
5679    /// once per `add` node holding that class, not once per element.
5680    #[test]
5681    fn decompose_ac_checks_a_prebound_element() {
5682        let mut eg = make_eg();
5683        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
5684        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
5685        let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
5686        eg.add(eg.ops().id_by_name("g").unwrap(), &[a]);
5687        eg.add(eg.ops().id_by_name("g").unwrap(), &[c]);
5688        let add = eg.ops().id_by_name("add").unwrap();
5689        eg.add(add, &[a, b, c]);
5690        eg.add(add, &[a, b]);
5691        eg.rebuild();
5692
5693        let index = IndexStore::build(&eg);
5694        let driven = plan_driven_from(&eg, &["(g x)", "(add x:1 ..rest)"], "g", &["g", "add"]);
5695        let matches = match_keys(&eg, &driven.0, &driven.1, &index);
5696        assert_eq!(
5697            matches.len(),
5698            3,
5699            "expected x=a in both add nodes and x=c in the first: {matches:?}"
5700        );
5701
5702        let vindex = VariantIndex::naive(&index);
5703        let ms = run_query(
5704            &driven.1,
5705            &eg,
5706            &vindex,
5707            &crate::resolve::GlobalCtx::<(), _>::new(),
5708        );
5709        assert_eq!(ms.len(), 3);
5710        assert!(!has_binding(&ms, &driven.0.shape, &eg, &[("x", "b")]));
5711    }
5712
5713    /// The set counterpart of [`decompose_ac_checks_a_prebound_element`].
5714    #[test]
5715    fn decompose_aci_checks_a_prebound_element() {
5716        let mut eg = make_eg();
5717        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
5718        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
5719        let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
5720        eg.add(eg.ops().id_by_name("g").unwrap(), &[a]);
5721        eg.add(eg.ops().id_by_name("g").unwrap(), &[c]);
5722        let un = eg.ops().id_by_name("union").unwrap();
5723        eg.add(un, &[a, b, c]);
5724        eg.add(un, &[a, b]);
5725        eg.rebuild();
5726
5727        let index = IndexStore::build(&eg);
5728        let driven = plan_driven_from(&eg, &["(g x)", "(union x ..rest)"], "g", &["g", "union"]);
5729        let matches = match_keys(&eg, &driven.0, &driven.1, &index);
5730        assert_eq!(
5731            matches.len(),
5732            3,
5733            "expected x=a in both union nodes and x=c in the first: {matches:?}"
5734        );
5735
5736        let vindex = VariantIndex::naive(&index);
5737        let ms = run_query(
5738            &driven.1,
5739            &eg,
5740            &vindex,
5741            &crate::resolve::GlobalCtx::<(), _>::new(),
5742        );
5743        assert_eq!(ms.len(), 3);
5744        assert!(!has_binding(&ms, &driven.0.shape, &eg, &[("x", "b")]));
5745    }
5746
5747    // -----------------------------------------------------------------------
5748    // Runtime atom scheduling
5749    // -----------------------------------------------------------------------
5750
5751    /// An e-graph holding one node of every shape the lowering can emit, so the
5752    /// sweep below reaches every branch of `emit_atom` and `try_eager_lower`.
5753    fn every_shape() -> EG {
5754        let mut eg = make_eg();
5755        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
5756        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
5757        let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
5758        let ga = eg.add(eg.ops().id_by_name("g").unwrap(), &[a]);
5759        let gb = eg.add(eg.ops().id_by_name("g").unwrap(), &[b]);
5760        let f = eg.ops().id_by_name("f").unwrap();
5761        let fab = eg.add(f, &[a, b]);
5762        eg.add(f, &[ga, b]);
5763        eg.add(f, &[a, a]);
5764        eg.add(f, &[gb, ga]);
5765        eg.add(eg.ops().id_by_name("h").unwrap(), &[fab, gb]);
5766        eg.add(eg.ops().id_by_name("concat").unwrap(), &[a, b, c]);
5767        eg.add(eg.ops().id_by_name("add").unwrap(), &[a, b, c]);
5768        eg.add(eg.ops().id_by_name("union").unwrap(), &[a, b, c]);
5769        eg.rebuild();
5770        eg
5771    }
5772
5773    /// The flag does not change the match set, on every atom shape.
5774    ///
5775    /// `match_keys` runs the query three ways and asserts all three agree, so
5776    /// this is the sweep of shapes rather than the comparison itself. The
5777    /// property is not an accident of these patterns: the match set is a
5778    /// function of the round's index and the query (chapter 09, "Which
5779    /// Snapshot"), which is exactly what makes an order change a performance
5780    /// change. This is that guarantee held to the strongest oracle available.
5781    #[test]
5782    fn runtime_scheduling_matches_the_static_plan() {
5783        let eg = every_shape();
5784        let index = IndexStore::build(&eg);
5785        let shapes: &[&[&str]] = &[
5786            &["(f x y)"],
5787            &["(f (g x) y)"],
5788            &["(f x x)"],
5789            &["(h (f x y) (g y))"],
5790            &["(concat x y ..rest)"],
5791            &["(add x:1 ..rest)"],
5792            &["(union x ..rest)"],
5793            // Disconnected conjuncts: two atoms with no variable in common, so
5794            // the order is decided by cost alone.
5795            &["(f x y)", "(g z)"],
5796            // Three atoms joined through child variables — the shape whose
5797            // order the flag can change per binding.
5798            &["(f x y)", "(g x)", "(g y)"],
5799        ];
5800        for srcs in shapes {
5801            let rq = resolve_srcs(&eg, srcs);
5802            let plan = schedule(&rq);
5803            let m = match_keys(&eg, &rq, &plan, &index);
5804            assert!(!m.is_empty(), "{srcs:?}: shape must match something");
5805        }
5806    }
5807
5808    /// Two bindings of one query, at the same depth, schedule different atoms.
5809    ///
5810    /// The counterpart of `op_restriction_policy_is_taken_per_binding` for the
5811    /// atom choice: it asserts the mechanism ran, not just that the answer came
5812    /// out right. `(f x y)` binds a pair of child classes; the `g` atom over `x`
5813    /// and the `h` atom over `y` have their bucket sizes swapped between the two
5814    /// `f` nodes, so a plan-time order is wrong on one of them and the per-binding
5815    /// choice is right on both.
5816    #[test]
5817    fn atom_order_is_chosen_per_binding() {
5818        let mut eg = make_eg();
5819        let (f, g, h) = (
5820            eg.ops().id_by_name("f").unwrap(),
5821            eg.ops().id_by_name("g").unwrap(),
5822            eg.ops().id_by_name("h").unwrap(),
5823        );
5824        let a = eg.add(eg.ops().id_by_name("a").unwrap(), &[]);
5825        let b = eg.add(eg.ops().id_by_name("b").unwrap(), &[]);
5826        let c = eg.add(eg.ops().id_by_name("c").unwrap(), &[]);
5827        // Two `f` nodes over four leaf classes. `x` is read by the `h` atom at
5828        // position 1 and `y` by the `g` atom at position 0, neither of which is
5829        // where `f` puts them, so the two buckets hold only the probe nodes.
5830        let x0 = eg.add(g, &[a]);
5831        let y0 = eg.add(g, &[b]);
5832        let x1 = eg.add(g, &[c]);
5833        let y1 = eg.add(h, &[a, b]);
5834        eg.add(f, &[x0, y0]);
5835        eg.add(f, &[x1, y1]);
5836        // Binding 0: `x0` has two `h` parents, `y0` has none — the `g` atom is
5837        // the empty one. Binding 1: the other way round.
5838        eg.add(h, &[a, x0]);
5839        eg.add(h, &[b, x0]);
5840        eg.add(g, &[y1]);
5841        eg.rebuild();
5842
5843        let index = IndexStore::build(&eg);
5844        let rq = resolve_srcs(&eg, &["(f x y)", "(h w x)", "(g y)"]);
5845        let plan = schedule(&rq);
5846        let _ = take_atom_choices();
5847        match_keys(&eg, &rq, &plan, &index);
5848        let choices = take_atom_choices();
5849
5850        // The first choice is made with nothing bound and is the same for every
5851        // binding; what this test is about is the ones after it.
5852        let after_f: Vec<usize> = choices
5853            .iter()
5854            .filter(|(used, _)| *used != 0)
5855            .map(|(_, ai)| *ai)
5856            .collect();
5857        assert!(
5858            after_f.contains(&1) && after_f.contains(&2),
5859            "both atoms must be chosen second on some binding, got {choices:?}"
5860        );
5861    }
5862
5863    // -----------------------------------------------------------------------
5864    // Operator-restriction policy
5865    // -----------------------------------------------------------------------
5866
5867    /// The policy is process-wide, so the tests that pin it take turns.
5868    static OP_FILTER_PIN: std::sync::Mutex<()> = std::sync::Mutex::new(());
5869
5870    /// The rule of `demote_by_op`, stated against the two lengths directly.
5871    ///
5872    /// Exhaustive where the e-graph tests cannot be: the filter branch needs a
5873    /// relation of [`OP_FILTER_MIN_RELATION`], and materializing one at every
5874    /// corner would cost a hundred thousand nodes per case.
5875    #[test]
5876    fn op_restriction_rule_reads_both_lengths() {
5877        let c = OP_FILTER_MIN_RELATION;
5878        let k = OP_FILTER_RELATION_PER_CANDIDATE;
5879        // (m, n, expected demotion)
5880        let cases = [
5881            // The threshold on the relation climbs with the bucket, so a small
5882            // bucket filters against a relation a large one would leapfrog.
5883            (1, k - 1, false),
5884            (1, k, true),
5885            (16, 16 * k - 1, false),
5886            (16, 16 * k, true),
5887            // Until it reaches the ceiling, past which no bucket size matters.
5888            (c / k, c, true),
5889            (c, c - 1, false),
5890            (c, c, true),
5891            // The hub shape: a quarter of a million parents against a relation
5892            // of twenty-six. This is the case the unconditional filter lost on.
5893            (262_144, 26, false),
5894            // The guard: once the bucket outgrows twice the relation, the
5895            // operand's `min(m, n)` work stops growing and the test's does not.
5896            (2 * c, c, true),
5897            (2 * c + 1, c, false),
5898            // Saturating arithmetic at both ends rather than wrapping.
5899            (usize::MAX, c, false),
5900            (usize::MAX, usize::MAX, true),
5901            (0, 1, true),
5902        ];
5903        for (m, n, expect) in cases {
5904            assert_eq!(
5905                demote_by_op(m, Some(n), OpFilterPolicy::Adaptive),
5906                expect,
5907                "m={m} n={n}"
5908            );
5909            // The pins ignore the lengths.
5910            assert!(demote_by_op(m, Some(n), OpFilterPolicy::AlwaysFilter));
5911            assert!(!demote_by_op(m, Some(n), OpFilterPolicy::AlwaysLeapfrog));
5912        }
5913        // A join with no `ByOp` to place decides nothing under any policy: its
5914        // single lookup is the only thing enumerating candidates.
5915        for p in [
5916            OpFilterPolicy::Adaptive,
5917            OpFilterPolicy::AlwaysFilter,
5918            OpFilterPolicy::AlwaysLeapfrog,
5919        ] {
5920            assert!(!demote_by_op(3, None, p));
5921        }
5922        take_op_restriction_log();
5923    }
5924
5925    /// Two hub classes, one whose `f0` parents are read against a relation above
5926    /// the threshold and one whose `f1` parents are read against a relation of
5927    /// forty, so one query per operator drives the decision both ways.
5928    ///
5929    /// `f0`'s relation is sized from the rule's own constant rather than written
5930    /// down, so it stays on the filter side of the threshold if the constant
5931    /// moves: four parents against `4 * OP_FILTER_RELATION_PER_CANDIDATE` is
5932    /// exactly at it. The ceiling and the bucket guard are corners this shape
5933    /// cannot reach at a scale worth building; `op_restriction_rule_reads_both_lengths`
5934    /// covers them.
5935    fn op_restriction_eg() -> (EG, ENodeId, ENodeId) {
5936        let mut eg = EG::from_model(&NiraModel);
5937        let e = eg.intern_sort("IExpr");
5938        eg.register_op0("z", e);
5939        eg.register_op1("s", e, e);
5940        eg.register_op1("hub", e, e);
5941        eg.register_op2("f0", e, e, e);
5942        eg.register_op2("f1", e, e, e);
5943        let s = eg.ops().id_by_name("s").unwrap();
5944        let hub = eg.ops().id_by_name("hub").unwrap();
5945        let f0 = eg.ops().id_by_name("f0").unwrap();
5946        let f1 = eg.ops().id_by_name("f1").unwrap();
5947
5948        // Enough distinct classes that `side * side` distinct `f0` child pairs
5949        // reach the relation size.
5950        let relation = 4 * OP_FILTER_RELATION_PER_CANDIDATE;
5951        let side = (relation as f64).sqrt().ceil() as usize + 1;
5952        let mut leaves = vec![eg.add(eg.ops().id_by_name("z").unwrap(), &[])];
5953        for i in 1..side {
5954            let prev = leaves[i - 1];
5955            leaves.push(eg.add(s, &[prev]));
5956        }
5957        let hub_a = eg.add(hub, &[leaves[0]]);
5958        let hub_b = eg.add(hub, &[leaves[1]]);
5959
5960        // `by_op[f0]`: four parents of `hub_a` and the rest off the hubs.
5961        for k in 0..4 {
5962            eg.add(f0, &[hub_a, leaves[k]]);
5963        }
5964        let mut made = 4;
5965        'fill: for i in 0..side {
5966            for j in 0..side {
5967                if made >= relation {
5968                    break 'fill;
5969                }
5970                eg.add(f0, &[leaves[i], leaves[j]]);
5971                made += 1;
5972            }
5973        }
5974        // `by_op[f1]`: forty parents of `hub_b` and nothing else.
5975        for k in 0..40 {
5976            eg.add(f1, &[hub_b, leaves[k]]);
5977        }
5978        eg.rebuild();
5979        (eg, hub_a, hub_b)
5980    }
5981
5982    /// Run `src` against `eg` under `policy` and return the decisions the joins
5983    /// made together with the match set, keyed so it can be compared across
5984    /// policies.
5985    fn op_restriction_run(
5986        eg: &EG,
5987        src: &str,
5988        policy: OpFilterPolicy,
5989    ) -> (Vec<OpRestriction>, Vec<Vec<ENodeId>>) {
5990        set_op_filter_policy(policy);
5991        let pats = [parse_pattern(src)];
5992        let fq = flatten(&pats, eg.ops()).unwrap();
5993        let rq = resolve(
5994            &fq,
5995            eg.ops(),
5996            eg.sorts(),
5997            &NiraModel,
5998            &crate::resolve::GlobalCtx::<_, ()>::new(),
5999        )
6000        .unwrap();
6001        let plan = schedule(&rq);
6002        let store = IndexStore::build(eg);
6003        let index = VariantIndex::naive(&store);
6004        take_op_restriction_log();
6005        let ms = run_query(
6006            &plan,
6007            eg,
6008            &index,
6009            &crate::resolve::GlobalCtx::<(), _>::new(),
6010        );
6011        let log = take_op_restriction_log();
6012        let mut keys: Vec<Vec<ENodeId>> = ms
6013            .iter()
6014            .map(|m| {
6015                (0..plan.shape.num_vars())
6016                    .map(|v| m.get(VarId(v as u16)))
6017                    .collect()
6018            })
6019            .collect();
6020        keys.sort();
6021        (log, keys)
6022    }
6023
6024    /// The shipped rule decides per binding, not per atom: one query, two
6025    /// bindings of the same join, two mechanisms.
6026    ///
6027    /// `hub_a` has four `f0` parents and is read against the whole `f0`
6028    /// relation, the shape the demotion was landed for — a handful of
6029    /// candidates and a relation two orders larger, where the test wins.
6030    /// `hub_b`'s bucket holds its forty `f1` parents, which is the same
6031    /// position-0 bucket the `f0` join probes, and against a relation of that
6032    /// size the operand wins. Both decisions are taken inside one `run_query`.
6033    ///
6034    /// This is the decision gate: it asserts which mechanism ran, not how long
6035    /// it took, so it holds in every build profile. The timing half is
6036    /// `tests/ematch_op_filter.rs`.
6037    #[test]
6038    fn op_restriction_policy_is_taken_per_binding() {
6039        let _pin = OP_FILTER_PIN.lock().unwrap_or_else(|e| e.into_inner());
6040        let (eg, _, _) = op_restriction_eg();
6041
6042        let (log, _) = op_restriction_run(&eg, "(f0 (hub z) y)", OpFilterPolicy::Adaptive);
6043        assert_eq!(
6044            log,
6045            vec![OpRestriction::Filter, OpRestriction::Leapfrog],
6046            "4 parents against a relation of {} must filter and 40 must not",
6047            4 * OP_FILTER_RELATION_PER_CANDIDATE
6048        );
6049
6050        // Against a relation of forty, neither bucket is small enough to make
6051        // the test worth its per-candidate load.
6052        let (log, _) = op_restriction_run(&eg, "(f1 (hub z) y)", OpFilterPolicy::Adaptive);
6053        assert_eq!(log, vec![OpRestriction::Leapfrog; 2]);
6054
6055        set_op_filter_policy(OpFilterPolicy::Adaptive);
6056    }
6057
6058    /// The two mechanisms return the same match set on both shapes.
6059    ///
6060    /// The demotion's soundness argument is the identity
6061    /// `by_op[o] ∩ B = { n ∈ B : op(n) = o }` over one index build; this is that
6062    /// identity checked on the shapes the policy sends each way, so a change
6063    /// that moves the rule cannot also change what the matcher returns.
6064    #[test]
6065    fn op_restriction_mechanisms_agree_on_the_match_set() {
6066        let _pin = OP_FILTER_PIN.lock().unwrap_or_else(|e| e.into_inner());
6067        let (eg, _, _) = op_restriction_eg();
6068        for src in ["(f0 (hub z) y)", "(f1 (hub z) y)", "(f0 x y)"] {
6069            let (_, adaptive) = op_restriction_run(&eg, src, OpFilterPolicy::Adaptive);
6070            let (fl, filter) = op_restriction_run(&eg, src, OpFilterPolicy::AlwaysFilter);
6071            let (ll, leapfrog) = op_restriction_run(&eg, src, OpFilterPolicy::AlwaysLeapfrog);
6072            assert_eq!(adaptive, filter, "{src}: filter changed the match set");
6073            assert_eq!(adaptive, leapfrog, "{src}: leapfrog changed the match set");
6074            assert!(!adaptive.is_empty(), "{src}: shape must match something");
6075            // `(f0 x y)` is a one-lookup join: no `ByOp` to place, no decision.
6076            if src == "(f0 x y)" {
6077                assert!(fl.is_empty() && ll.is_empty());
6078            }
6079        }
6080        set_op_filter_policy(OpFilterPolicy::Adaptive);
6081    }
6082}