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