Skip to main content

semi_persistent_egraph/
schedule.rs

1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// SPDX-License-Identifier: Apache-2.0
3//! Query scheduler: order variables and assign index constraints.
4//!
5//! Given a `ResolvedQuery` (OpId-based), produce a `QueryPlan` that
6//! tells the execution engine which variable to bind next and how.
7
8use crate::ast::{GlobalVarId, LitValVarId, MsetVarId, SeqVarId, SetVarId, VarId};
9use crate::containers::{DenseId, IndexLike};
10use crate::resolve::{MatchShape, PatVar, PredGuard, RAtom, RMult, ResolvedQuery};
11use std::cell::Cell;
12use std::hash::Hash;
13
14// ---------------------------------------------------------------------------
15// Index lookups — each produces a SortedVec<G> for leapfrog
16// ---------------------------------------------------------------------------
17
18/// `I` is the child-position word: [`EGraphConfig::Index`], the same width the
19/// e-graph indexes its child pool with. A position is an offset into one node's
20/// children, so its range is the node's arity, and a variadic node's arity is a
21/// span in that pool — bounded by `I` and by nothing narrower. Hard-coding `u32`
22/// here would cap a 63-bit session's node arity at 2^32 children, and the cap
23/// would be reached silently: the counter in [`IndexStore::build`] wrapped, and
24/// the child at position 2^32 landed in bucket 0, where it would match patterns
25/// written for the first argument.
26///
27/// [`EGraphConfig::Index`]: crate::config::EGraphConfig::Index
28/// [`IndexStore::build`]: crate::index::IndexStore::build
29#[derive(Clone, Debug, PartialEq, Eq)]
30pub enum IndexLookup<O, I> {
31    ByOp { op: O },
32    ByChildPos { child: PatVar, pos: I },
33    ByRepr { repr: VarId },
34    ByContains { child: PatVar },
35}
36
37// ---------------------------------------------------------------------------
38// Execution steps
39// ---------------------------------------------------------------------------
40
41#[derive(Clone, Debug, PartialEq, Eq)]
42pub enum Step<O, I, V> {
43    Join {
44        target: VarId,
45        lookups: Vec<IndexLookup<O, I>>,
46        /// Stable atom index in the compile-time numbering. Bridges the
47        /// fixed atom order (which defines semi-naive variants) to the
48        /// dynamic execution order chosen by the scheduler. Not used by
49        /// the naive matcher; consumed by semi-naive variant dispatch.
50        atom_id: usize,
51    },
52    ExtractChild {
53        target: VarId,
54        parent: VarId,
55        /// Child position, `I`-wide for the same reason as
56        /// [`IndexLookup::ByChildPos`]: it is read back through
57        /// `EGraph::child_at`, which offsets into the node's span in the child pool.
58        pos: I,
59    },
60    CheckChildEq {
61        parent: VarId,
62        pos: I,
63        expected: PatVar,
64    },
65    CheckEq {
66        a: VarId,
67        b: VarId,
68    },
69    CheckEqGlobal {
70        local: VarId,
71        global: GlobalVarId,
72    },
73    /// Bind an as-yet unbound variable to a global's class. The dual of
74    /// `CheckEqGlobal`: an `(= x g)` atom CHECKS when `x` already has a value
75    /// and BINDS when it does not. Without this a rule whose only atom is such
76    /// an equality compiles to a plan that binds nothing, and materializing a
77    /// match then reads an unset variable.
78    BindGlobal {
79        target: VarId,
80        global: GlobalVarId,
81    },
82    CopyBinding {
83        target: VarId,
84        other: VarId,
85    },
86    ExpandA {
87        node: VarId,
88        children: Vec<PatVar>,
89        pre: Option<SeqVarId>,
90        suf: Option<SeqVarId>,
91    },
92    DecomposeAC {
93        node: VarId,
94        elems: Vec<(PatVar, RMult)>,
95        rest: Option<MsetVarId>,
96        idempotent: bool,
97    },
98    DecomposeACI {
99        node: VarId,
100        elems: Vec<PatVar>,
101        rest: Option<SetVarId>,
102    },
103    ExtractLitVal {
104        node: VarId,
105        val: LitValVarId,
106    },
107    /// Keep the match only if `node`'s literal payload equals `value`. The constant
108    /// counterpart of [`Step::ExtractLitVal`]: that one binds the payload to a pattern
109    /// variable, this one pins it to a literal written in the pattern.
110    CheckLit {
111        node: VarId,
112        value: V,
113    },
114    /// Keep the match only if the guard evaluates to a true boolean over the literal
115    /// values bound so far.
116    CheckPred {
117        guard: PredGuard<O, V>,
118    },
119}
120
121#[derive(Clone, Debug)]
122pub struct QueryPlan<O, I, V> {
123    pub steps: Vec<Step<O, I, V>>,
124    pub shape: MatchShape,
125}
126
127// ---------------------------------------------------------------------------
128// Stats
129// ---------------------------------------------------------------------------
130
131pub struct IndexStats<O: Eq + Hash> {
132    /// Per-op driver-scan cardinality (`|by_op[op]|`). The base estimate for an
133    /// atom when no per-atom override is present — correct for naive matching,
134    /// where every atom of an op reads the same full bucket.
135    pub op_card: std::collections::HashMap<O, usize>,
136    /// Measured mean fan-out of each access path, from the round's index build.
137    /// The default is all-unmeasured, which prices every bound key at the fixed
138    /// halving this model replaces; see `path_selectivity`.
139    pub fanouts: crate::index::FanOuts<O>,
140    /// Per-atom (`atom_id`) driver-scan cardinality, overriding `op_card` for
141    /// that atom. Needed for semi-naive: an atom's base cardinality is set by
142    /// its **mode** (delta / full / full∖delta), which is per-atom, not per-op —
143    /// two atoms with the same op can have different modes in one flavor (e.g.
144    /// `(f (f x y) z)` variant 1: atom 0 is full∖delta, atom 1 is delta, both
145    /// op `f`). `op_card` cannot represent that; `atom_card` can.
146    pub atom_card: std::collections::HashMap<usize, usize>,
147}
148
149impl<O: Eq + Hash> Default for IndexStats<O> {
150    fn default() -> Self {
151        Self::new()
152    }
153}
154
155impl<O: Eq + Hash> IndexStats<O> {
156    pub fn new() -> Self {
157        Self {
158            op_card: std::collections::HashMap::new(),
159            atom_card: std::collections::HashMap::new(),
160            fanouts: crate::index::FanOuts::default(),
161        }
162    }
163}
164
165impl<O: Eq + Hash + Copy> IndexStats<O> {
166    pub fn from_index<Cfg>(index: &crate::index::IndexStore<Cfg>) -> Self
167    where
168        Cfg: crate::config::EGraphConfig<O = O>,
169        crate::canon::MSetCanon: crate::canon::VarCanon<Cfg::G, Cfg::C>,
170    {
171        Self {
172            op_card: index.op_cardinalities().collect(),
173            atom_card: std::collections::HashMap::new(),
174            fanouts: index.fanouts.clone(),
175        }
176    }
177}
178
179// ---------------------------------------------------------------------------
180// Scheduler
181// ---------------------------------------------------------------------------
182
183/// A child position in the plan's index word.
184///
185/// The argument is a *pattern's* arity, authored in a rewrite rule, so in practice a
186/// handful — but the value is compared against and used to offset into positions the
187/// e-graph assigns to real nodes ([`IndexStore::build`], [`EGraph::child_at`]), whose
188/// range is the child pool's. Narrowing it silently would probe or read the wrong
189/// argument, so it is checked rather than cast.
190///
191/// [`IndexStore::build`]: crate::index::IndexStore::build
192/// [`EGraph::child_at`]: crate::egraph::EGraph::child_at
193fn child_pos<I: IndexLike>(pos: usize) -> I {
194    I::try_from_usize(pos)
195        .expect("pattern child position exceeds EGraphConfig::Index; configure a wider index word")
196}
197
198fn pv_is_bound(pv: &PatVar, bound: &[bool]) -> bool {
199    match pv {
200        PatVar::Local(vid) => bound[vid.idx()],
201        PatVar::Global(_) => true,
202    }
203}
204
205fn pv_mark_bound(pv: &PatVar, bound: &mut [bool]) {
206    if let PatVar::Local(vid) = pv {
207        bound[vid.idx()] = true;
208    }
209}
210
211/// Base driver-scan cardinality for an atom: its per-atom override
212/// (`atom_card[atom_id]`, set per semi-naive flavor) if present, else the
213/// per-op bucket size (`op_card[op]`, the naive default).
214fn base_card<O: Eq + Hash>(op: &O, atom_id: usize, stats: &IndexStats<O>) -> usize {
215    stats
216        .atom_card
217        .get(&atom_id)
218        .copied()
219        .or_else(|| stats.op_card.get(op).copied())
220        .unwrap_or(usize::MAX)
221}
222
223/// Fraction of an atom's relation that survives intersecting one index bucket.
224///
225/// `fanout` is the bucket size a probe on that path lands in, measured by
226/// [`FanOuts`](crate::index::FanOuts), and `denom` the relation the bucket
227/// filters: `|by_op[op]|` for `by_child_pos` and `by_contains`, the whole
228/// indexed node count for `by_repr`. The ratio replaces a fixed halving
229/// heuristic that cannot distinguish access paths. The concrete values in the
230/// scheduler regression below are a captured fixture, not branch-tip workload
231/// statistics.
232///
233/// Falls back to the halving when the path was never measured, which is every
234/// call from [`schedule`], the stats-free entry point.
235fn path_selectivity(fanout: Option<f64>, denom: usize) -> f64 {
236    match fanout {
237        Some(f) if denom > 0 => (f / denom as f64).clamp(0.0, 1.0),
238        _ => 0.5,
239    }
240}
241
242// ---------------------------------------------------------------------------
243// Sampled cross-index selectivity
244// ---------------------------------------------------------------------------
245
246/// Where in an emitter atom's node a variable that atom bound sits.
247///
248/// The scheduler needs it to reproduce, at plan time, the key a later atom's
249/// probe will be handed at run time: the runtime key is the class of the
250/// emitter node's child at some position, so a sample of emitter nodes plus a
251/// site is a sample of probe keys.
252#[derive(Clone, Copy, PartialEq, Eq, Debug)]
253pub enum KeySite {
254    /// The node variable itself; the key is the node's own class.
255    Node,
256    /// The child at this position of a fixed-arity node.
257    Child(usize),
258    /// An element of a variadic node, which has no fixed position: the
259    /// decomposition binds the variable to each element in turn, so every
260    /// child of the node is an equally likely key.
261    Element,
262}
263
264/// The access path a candidate atom's join opens for one bound key.
265#[derive(Clone, Copy, PartialEq, Eq, Debug)]
266pub enum ProbePath {
267    /// `by_child_pos[(key, pos)]`, restricted to the atom's operator.
268    ChildPos(usize),
269    /// `by_contains[key]`, restricted to the atom's operator.
270    Contains,
271}
272
273/// Knobs for sampled cross-index selectivity; see [`set_sampled_selectivity`].
274#[derive(Clone, Copy, Debug, PartialEq)]
275pub struct SamplerConfig {
276    /// Emitter nodes drawn per estimate.
277    pub k: usize,
278    /// Bootstrap resamples used to guard the estimate. `0` disables the guard.
279    pub bootstrap: usize,
280    /// Coefficient of variation of the bootstrap mean above which the estimate
281    /// is discarded for the size-biased mean.
282    pub cv_threshold: f64,
283}
284
285impl Default for SamplerConfig {
286    fn default() -> Self {
287        Self {
288            k: 32,
289            bootstrap: 0,
290            cv_threshold: 1.0,
291        }
292    }
293}
294
295thread_local! {
296    /// Sampling configuration, or `None` for the size-biased mean model.
297    ///
298    /// Thread-local for the same reason as `ematch::RUNTIME_SCHEDULING`: it is
299    /// read once per scheduled query rather than on a per-candidate path, and
300    /// the differential tests run one plan with it on against another with it
301    /// off, which a process-wide flag would make order-dependent under the test
302    /// harness's thread pool.
303    static SAMPLED_SELECTIVITY: Cell<Option<SamplerConfig>> = const { Cell::new(None) };
304}
305
306/// Price a bound key by sampling the emitter's relation instead of by the
307/// round's size-biased mean fan-out. Off by default.
308///
309/// The mean assumes the emitter's key distribution mirrors the probed index's
310/// marginal. It does not have to: an emitter whose nodes point only at leaf
311/// classes never probes the hub buckets that dominate the mean, and the mean
312/// then over-prices the probe by the hub's size. Sampling reads the joint
313/// distribution directly — draw emitter nodes, extract the keys they expose,
314/// read the buckets those keys actually select. See design chapter 20.
315pub fn set_sampled_selectivity(cfg: Option<SamplerConfig>) {
316    SAMPLED_SELECTIVITY.with(|c| c.set(cfg));
317}
318
319/// The sampling configuration in force on this thread, if any.
320pub fn sampled_selectivity() -> Option<SamplerConfig> {
321    SAMPLED_SELECTIVITY.with(|c| c.get())
322}
323
324thread_local! {
325    /// Estimates taken, and estimates the bootstrap guard sent back to the
326    /// size-biased mean.
327    static SAMPLE_TALLY: Cell<(u64, u64)> = const { Cell::new((0, 0)) };
328}
329
330/// `(estimates taken, estimates the bootstrap guard rejected)` since the last
331/// [`reset_sample_tally`].
332///
333/// The guard is the only part of the estimator whose effect is invisible in the
334/// plan — a rejected estimate produces the order the mean model would have
335/// produced anyway — so whether it fires on a given workload is a question only
336/// a counter answers. Incremented on the sampling path alone, so the flag-off
337/// scheduler does not touch it.
338pub fn sample_tally() -> (u64, u64) {
339    SAMPLE_TALLY.with(|c| c.get())
340}
341
342/// Zero the counters [`sample_tally`] reports.
343pub fn reset_sample_tally() {
344    SAMPLE_TALLY.with(|c| c.set((0, 0)));
345}
346
347fn tally(rejected: bool) {
348    SAMPLE_TALLY.with(|c| {
349        let (t, r) = c.get();
350        c.set((t + 1, r + u64::from(rejected)));
351    });
352}
353
354/// Plan-time read access to the round's buckets, for sampled selectivity.
355///
356/// A trait, and phrased in `usize` ids, so that the scheduler stays generic
357/// over the operator alone: threading the e-graph's whole configuration through
358/// [`IndexStats`] would put a second type parameter and a lifetime on every
359/// signature that carries stats. [`IndexSampler`](crate::index::IndexSampler)
360/// is the one implementation.
361pub trait CrossSampler<O> {
362    /// Up to `k` node ids of the slice atom `atom_id` will enumerate, in
363    /// ascending id order.
364    ///
365    /// The draw is an even stride over the sorted bucket rather than a random
366    /// sample: a plan must be a function of the e-graph and the rule, and
367    /// nothing else, so that a run is reproducible and a differential test can
368    /// compare two engines on the same order.
369    fn driver_sample(&self, atom_id: usize, op: O, k: usize, out: &mut Vec<usize>);
370
371    /// The classes a variable bound at `site` takes for emitter node `node`.
372    /// One class for [`KeySite::Node`] and [`KeySite::Child`]; for
373    /// [`KeySite::Element`], every distinct class among the node's children.
374    fn key_classes(&self, node: usize, site: KeySite, out: &mut Vec<usize>);
375
376    /// Nodes of operator `op` in the bucket `path` selects for `class` — the
377    /// candidate count the join's intersection with `by_op[op]` can propose.
378    fn probe_len(&self, class: usize, path: ProbePath, op: O) -> usize;
379}
380
381/// One sampled estimate's cache key: emitter atom, the site it binds the
382/// variable at, and the probe the candidate atom would make.
383type SampleKey = (usize, KeySite, usize, ProbePath);
384
385/// Sampling state for one [`schedule_with_stats_sampled`] call: the emitter
386/// draws and the finished estimates, both memoized because the greedy loop
387/// re-costs every unused atom after each choice and the index does not move
388/// underneath it.
389struct Sampling<'a, O> {
390    sampler: &'a dyn CrossSampler<O>,
391    cfg: SamplerConfig,
392    drivers: Vec<(usize, Vec<usize>)>,
393    memo: Vec<(SampleKey, Option<f64>)>,
394    classes: Vec<usize>,
395    draws: Vec<f64>,
396    means: Vec<f64>,
397}
398
399impl<'a, O: DenseId + Copy> Sampling<'a, O> {
400    fn new(sampler: &'a dyn CrossSampler<O>, cfg: SamplerConfig) -> Self {
401        Self {
402            sampler,
403            cfg,
404            drivers: Vec::new(),
405            memo: Vec::new(),
406            classes: Vec::new(),
407            draws: Vec::new(),
408            means: Vec::new(),
409        }
410    }
411
412    /// Index of `atom_id`'s emitter draw, taking it if this is the first ask.
413    fn driver(&mut self, atom_id: usize, op: O) -> usize {
414        if let Some(i) = self.drivers.iter().position(|(a, _)| *a == atom_id) {
415            return i;
416        }
417        let mut nodes = Vec::new();
418        self.sampler
419            .driver_sample(atom_id, op, self.cfg.k, &mut nodes);
420        self.drivers.push((atom_id, nodes));
421        self.drivers.len() - 1
422    }
423
424    /// Mean bucket length the candidate's probe returns over the emitter's
425    /// sampled keys, or `None` when the emitter's slice is empty or the
426    /// bootstrap guard rejects the draw.
427    fn estimate(
428        &mut self,
429        emitter: usize,
430        emitter_op: O,
431        site: KeySite,
432        path: ProbePath,
433        probe_op: O,
434    ) -> Option<f64> {
435        let key: SampleKey = (emitter, site, probe_op.to_usize(), path);
436        if let Some((_, v)) = self.memo.iter().find(|(k, _)| *k == key) {
437            return *v;
438        }
439        let v = self.measure(emitter, emitter_op, site, path, probe_op);
440        self.memo.push((key, v));
441        v
442    }
443
444    fn measure(
445        &mut self,
446        emitter: usize,
447        emitter_op: O,
448        site: KeySite,
449        path: ProbePath,
450        probe_op: O,
451    ) -> Option<f64> {
452        let di = self.driver(emitter, emitter_op);
453        // Taken out and put back so the per-sample scratch below can be
454        // borrowed mutably while the draw is read.
455        let nodes = std::mem::take(&mut self.drivers[di].1);
456        let out = self.sample_draws(&nodes, site, path, probe_op);
457        self.drivers[di].1 = nodes;
458        out
459    }
460
461    fn sample_draws(
462        &mut self,
463        nodes: &[usize],
464        site: KeySite,
465        path: ProbePath,
466        probe_op: O,
467    ) -> Option<f64> {
468        if nodes.is_empty() {
469            return None;
470        }
471        self.draws.clear();
472        for &n in nodes {
473            self.classes.clear();
474            self.sampler.key_classes(n, site, &mut self.classes);
475            if self.classes.is_empty() {
476                continue;
477            }
478            // Every class the site can take is an equally likely key, which is
479            // one class except under `Element`, where the decomposition binds
480            // the variable to each element of the node in turn.
481            let sum: usize = self
482                .classes
483                .iter()
484                .map(|&c| self.sampler.probe_len(c, path, probe_op))
485                .sum();
486            self.draws.push(sum as f64 / self.classes.len() as f64);
487        }
488        if self.draws.is_empty() {
489            return None;
490        }
491        let mean = self.draws.iter().sum::<f64>() / self.draws.len() as f64;
492        let rejected = self.cfg.bootstrap > 0 && !self.bootstrap_ok(mean);
493        tally(rejected);
494        if rejected { None } else { Some(mean) }
495    }
496
497    /// Resample the draws with replacement and reject the estimate when the
498    /// resampled means scatter too far.
499    ///
500    /// The stride is deterministic but arbitrary with respect to the key
501    /// distribution, so a draw can miss a mode that dominates the true mean.
502    /// The bootstrap prices that risk from the draw itself: a sample whose mean
503    /// is stable under resampling is one the stride did not decide. The
504    /// generator is a fixed-seed SplitMix64, so the verdict is a function of the
505    /// draw and plans stay reproducible.
506    fn bootstrap_ok(&mut self, mean: f64) -> bool {
507        if mean <= 0.0 {
508            // A draw of all zeros has no scale to be uncertain on, and its
509            // relative spread is 0/0. The estimate is exact: no key the emitter
510            // produces selects anything.
511            return self.draws.iter().all(|&d| d == 0.0);
512        }
513        let n = self.draws.len();
514        let mut state = 0x2545_F491_4F6C_DD1Du64;
515        self.means.clear();
516        for _ in 0..self.cfg.bootstrap {
517            let mut acc = 0.0;
518            for _ in 0..n {
519                acc += self.draws[(splitmix64(&mut state) % n as u64) as usize];
520            }
521            self.means.push(acc / n as f64);
522        }
523        let b = self.means.len() as f64;
524        let bmean = self.means.iter().sum::<f64>() / b;
525        let var = self
526            .means
527            .iter()
528            .map(|m| (m - bmean) * (m - bmean))
529            .sum::<f64>()
530            / b;
531        var.sqrt() / mean <= self.cfg.cv_threshold
532    }
533}
534
535/// SplitMix64, the reference generator for the bootstrap resample.
536fn splitmix64(state: &mut u64) -> u64 {
537    *state = state.wrapping_add(0x9E37_79B9_7F4A_7C15);
538    let mut z = *state;
539    z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
540    z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
541    z ^ (z >> 31)
542}
543
544/// The atom each variable was bound by, and where in that atom's node it sits.
545type Emitters = Vec<Option<(usize, KeySite)>>;
546
547/// Record every variable the atoms newly lowered by this step bind, first
548/// writer winning — the atom that binds a variable is the first lowered atom
549/// that mentions it, and later atoms only re-check it.
550fn record_emitters<O, S, V>(
551    atoms: &[RAtom<O, S, V>],
552    before: &[bool],
553    used: &[bool],
554    em: &mut Emitters,
555) {
556    fn set(em: &mut Emitters, v: usize, src: (usize, KeySite)) {
557        if em[v].is_none() {
558            em[v] = Some(src);
559        }
560    }
561    fn set_pv(em: &mut Emitters, pv: &PatVar, src: (usize, KeySite)) {
562        if let PatVar::Local(v) = pv {
563            set(em, v.idx(), src);
564        }
565    }
566    for (ai, atom) in atoms.iter().enumerate() {
567        if used[ai] == before[ai] {
568            continue;
569        }
570        match atom {
571            RAtom::Plain { node, children, .. } => {
572                set(em, (*node).idx(), (ai, KeySite::Node));
573                for (pos, cv) in children.iter().enumerate() {
574                    set_pv(em, cv, (ai, KeySite::Child(pos)));
575                }
576            }
577            RAtom::AExact { node, children, .. } => {
578                set(em, (*node).idx(), (ai, KeySite::Node));
579                for cv in children {
580                    set_pv(em, cv, (ai, KeySite::Element));
581                }
582            }
583            RAtom::APrefix { node, fixed, .. }
584            | RAtom::ASuffix { node, fixed, .. }
585            | RAtom::ABoth { node, fixed, .. } => {
586                set(em, (*node).idx(), (ai, KeySite::Node));
587                for cv in fixed {
588                    set_pv(em, cv, (ai, KeySite::Element));
589                }
590            }
591            RAtom::ACExact { node, elems, .. } | RAtom::ACSub { node, elems, .. } => {
592                set(em, (*node).idx(), (ai, KeySite::Node));
593                for (ev, _) in elems {
594                    set_pv(em, ev, (ai, KeySite::Element));
595                }
596            }
597            RAtom::ACIExact { node, elems, .. } | RAtom::ACISub { node, elems, .. } => {
598                set(em, (*node).idx(), (ai, KeySite::Node));
599                for ev in elems {
600                    set_pv(em, ev, (ai, KeySite::Element));
601                }
602            }
603            RAtom::Lit { node, .. } | RAtom::LitBind { node, .. } => {
604                set(em, (*node).idx(), (ai, KeySite::Node))
605            }
606            // `CopyBinding` propagates a binding rather than producing one, so
607            // the copy's emitter is the original's.
608            RAtom::Eq(a, b) => {
609                if em[(*a).idx()].is_none() {
610                    em[(*a).idx()] = em[(*b).idx()];
611                } else if em[(*b).idx()].is_none() {
612                    em[(*b).idx()] = em[(*a).idx()];
613                }
614            }
615            // A guard binds nothing, so it emits nothing.
616            RAtom::EqGlobal(..) | RAtom::Pred { .. } => {}
617        }
618    }
619}
620
621/// The relation an atom scans, for the emitter draw. Mirrors
622/// [`saturate::atom_op`](crate::saturate::atom_op) — the same partition into
623/// scanning and non-scanning atoms the semi-naive decomposition uses.
624fn emitter_op<O: Copy, S, V>(atom: &RAtom<O, S, V>) -> Option<O> {
625    crate::saturate::atom_op(atom)
626}
627
628/// Everything the cost model reads: the round's aggregates, which atom bound
629/// each variable, and the sampler when it is on.
630struct Cost<'a, O: Eq + Hash> {
631    stats: &'a IndexStats<O>,
632    emitters: Emitters,
633    sampling: Option<Sampling<'a, O>>,
634}
635
636impl<'a, O: DenseId + Hash + Copy> Cost<'a, O> {
637    /// Sampled fan-out of one bound key of a candidate atom, or `None` when
638    /// sampling is off, the key was not bound by a scheduled atom (a global, or
639    /// a variable an eager step produced from one), or the guard rejected it.
640    fn sampled<S, V>(
641        &mut self,
642        atoms: &[RAtom<O, S, V>],
643        key: &PatVar,
644        path: ProbePath,
645        probe_op: O,
646    ) -> Option<f64> {
647        let PatVar::Local(v) = key else { return None };
648        let (emitter, site) = (*self.emitters.get(v.idx())?)?;
649        let emitter_op = emitter_op(atoms.get(emitter)?)?;
650        self.sampling
651            .as_mut()?
652            .estimate(emitter, emitter_op, site, path, probe_op)
653    }
654}
655
656/// Expected number of candidate nodes an atom's join enumerates, given which
657/// of its keys the scheduler has already bound.
658///
659/// The join drives from `by_op[op]` — or, under semi-naive, from the slice of
660/// it the atom's mode reads, which is what [`base_card`] returns — and
661/// intersects one bucket per bound key. Each intersection multiplies in the
662/// measured selectivity of its access path, so `k` bound keys multiply `k`
663/// measured fractions where the previous model multiplied `k` halves. Two
664/// consequences the halving did not have: the estimate for one bound key is
665/// the size of the bucket that key's probe lands in rather than half the
666/// relation, and a delta-restricted atom is priced by the delta's cardinality
667/// at any position of the order, not only when it drives the scan.
668///
669/// The three paths follow `emit_atom`: a `Plain` atom intersects
670/// `by_child_pos` per bound child, every variadic atom (A*/AC*/ACI*, including
671/// `AExact`) intersects `by_contains` per bound element, and an atom whose
672/// node variable is already bound re-joins within its class through `by_repr`.
673fn estimate_cost<O: DenseId + Hash + Copy, S, V>(
674    atoms: &[RAtom<O, S, V>],
675    atom_id: usize,
676    bound: &[bool],
677    ctx: &mut Cost<'_, O>,
678) -> f64 {
679    let atom = &atoms[atom_id];
680    let stats = ctx.stats;
681    match atom {
682        RAtom::Plain { node, op, children } => {
683            if bound[(*node).idx()] {
684                return by_repr_cost(op, atom_id, stats);
685            }
686            let full = stats.op_card.get(op).copied().unwrap_or(0);
687            let mut cost = base_card(op, atom_id, stats) as f64;
688            for (pos, cv) in children.iter().enumerate() {
689                if pv_is_bound(cv, bound) {
690                    let f = ctx
691                        .sampled(atoms, cv, ProbePath::ChildPos(pos), *op)
692                        .or_else(|| ctx.stats.fanouts.by_child_pos.get(&(*op, pos)).copied());
693                    cost *= path_selectivity(f, full);
694                }
695            }
696            cost
697        }
698        RAtom::AExact { node, op, children } => {
699            by_contains_cost(atoms, node, op, atom_id, children, bound, ctx)
700        }
701        RAtom::APrefix {
702            node, op, fixed, ..
703        }
704        | RAtom::ASuffix {
705            node, op, fixed, ..
706        }
707        | RAtom::ABoth {
708            node, op, fixed, ..
709        } => by_contains_cost(atoms, node, op, atom_id, fixed, bound, ctx),
710        RAtom::ACExact { node, op, elems }
711        | RAtom::ACSub {
712            node, op, elems, ..
713        } => {
714            let evs: Vec<PatVar> = elems.iter().map(|(ev, _)| *ev).collect();
715            by_contains_cost(atoms, node, op, atom_id, &evs, bound, ctx)
716        }
717        RAtom::ACIExact { node, op, elems }
718        | RAtom::ACISub {
719            node, op, elems, ..
720        } => by_contains_cost(atoms, node, op, atom_id, elems, bound, ctx),
721        RAtom::Lit { op, .. } | RAtom::LitBind { op, .. } => base_card(op, atom_id, stats) as f64,
722        RAtom::Eq(..) | RAtom::EqGlobal(..) | RAtom::Pred { .. } => 0.0,
723    }
724}
725
726/// Cost of re-joining an atom whose node variable is already bound: the class's
727/// nodes, intersected with the op's. The denominator is every indexed node,
728/// because a class holds nodes of every op.
729fn by_repr_cost<O: Eq + Hash>(op: &O, atom_id: usize, stats: &IndexStats<O>) -> f64 {
730    let sel = path_selectivity(Some(stats.fanouts.by_repr), stats.fanouts.nodes);
731    base_card(op, atom_id, stats) as f64 * sel
732}
733
734/// Cost of a variadic atom's join: `by_contains` per bound element, or the
735/// class re-join when the node variable itself is bound (`emit_variadic_join`
736/// emits one or the other).
737#[allow(clippy::too_many_arguments)]
738fn by_contains_cost<O: DenseId + Hash + Copy, S, V>(
739    atoms: &[RAtom<O, S, V>],
740    node: &VarId,
741    op: &O,
742    atom_id: usize,
743    elems: &[PatVar],
744    bound: &[bool],
745    ctx: &mut Cost<'_, O>,
746) -> f64 {
747    if bound[(*node).idx()] {
748        return by_repr_cost(op, atom_id, ctx.stats);
749    }
750    let full = ctx.stats.op_card.get(op).copied().unwrap_or(0);
751    let mut cost = base_card(op, atom_id, ctx.stats) as f64;
752    for e in elems {
753        if pv_is_bound(e, bound) {
754            let f = ctx
755                .sampled(atoms, e, ProbePath::Contains, *op)
756                .or_else(|| ctx.stats.fanouts.by_contains.get(op).copied());
757            cost *= path_selectivity(f, full);
758        }
759    }
760    cost
761}
762
763pub fn schedule<O: DenseId + Hash + Copy, S: DenseId + Copy, V: Clone, I: IndexLike>(
764    rq: &ResolvedQuery<O, S, V>,
765) -> QueryPlan<O, I, V> {
766    schedule_with_stats(rq, &IndexStats::new())
767}
768
769pub fn schedule_with_stats<O: DenseId + Hash + Copy, S: DenseId + Copy, V: Clone, I: IndexLike>(
770    rq: &ResolvedQuery<O, S, V>,
771    stats: &IndexStats<O>,
772) -> QueryPlan<O, I, V> {
773    schedule_inner(rq, stats, None)
774}
775
776/// [`schedule_with_stats`] with plan-time access to the round's buckets, so
777/// that a bound key can be priced by sampling the emitter's relation rather
778/// than by the round's mean fan-out.
779///
780/// Whether it does is [`set_sampled_selectivity`]'s to decide: with the flag
781/// off this is `schedule_with_stats` and `sampler` is never called, so a caller
782/// that always has a sampler in hand needs no branch of its own.
783pub fn schedule_with_stats_sampled<
784    O: DenseId + Hash + Copy,
785    S: DenseId + Copy,
786    V: Clone,
787    I: IndexLike,
788>(
789    rq: &ResolvedQuery<O, S, V>,
790    stats: &IndexStats<O>,
791    sampler: &dyn CrossSampler<O>,
792) -> QueryPlan<O, I, V> {
793    schedule_inner(rq, stats, sampled_selectivity().map(|cfg| (sampler, cfg)))
794}
795
796fn schedule_inner<O: DenseId + Hash + Copy, S: DenseId + Copy, V: Clone, I: IndexLike>(
797    rq: &ResolvedQuery<O, S, V>,
798    stats: &IndexStats<O>,
799    sampling: Option<(&dyn CrossSampler<O>, SamplerConfig)>,
800) -> QueryPlan<O, I, V> {
801    let mut bound = vec![false; rq.shape.num_vars()];
802    let mut steps = Vec::new();
803    let mut used = vec![false; rq.atoms.len()];
804    let mut ctx = Cost {
805        stats,
806        emitters: vec![None; rq.shape.num_vars()],
807        sampling: sampling.map(|(s, cfg)| Sampling::new(s, cfg)),
808    };
809    let mut before = used.clone();
810    loop {
811        // Eager pass: Eq, Lit, already-bound nodes.
812        lower_eager(&rq.atoms, &mut used, &mut bound, &mut steps);
813        record_emitters(&rq.atoms, &before, &used, &mut ctx.emitters);
814        before.copy_from_slice(&used);
815
816        // Pick the cheapest unprocessed atom.
817        // The estimate is an expected cardinality, so it is compared as an
818        // `f64`: rounding it to an integer would tie every selective atom at 0.
819        // Every value is finite (`path_selectivity` guards its divisor), and the
820        // fold replaces only on a strict improvement, so equal minima keep the
821        // lowest atom index and the choice is a function of the atom order.
822        // Costs are taken once per atom per pass rather than inside a
823        // comparator, which under sampling would redraw them per comparison.
824        let mut best: Option<(usize, f64)> = None;
825        for ai in 0..rq.atoms.len() {
826            if used[ai]
827                || matches!(
828                    &rq.atoms[ai],
829                    RAtom::Eq(..) | RAtom::EqGlobal(..) | RAtom::Pred { .. }
830                )
831            {
832                continue;
833            }
834            let c = estimate_cost(&rq.atoms, ai, &bound, &mut ctx);
835            if best.is_none_or(|(_, b)| c < b) {
836                best = Some((ai, c));
837            }
838        }
839
840        let Some((ai, _)) = best else { break };
841        emit_atom(&rq.atoms[ai], ai, &mut bound, &mut steps);
842        used[ai] = true;
843        record_emitters(&rq.atoms, &before, &used, &mut ctx.emitters);
844        before.copy_from_slice(&used);
845    }
846
847    if dump_plan_enabled() {
848        dump_plan(&steps, rq.atoms.len());
849    }
850    QueryPlan {
851        steps,
852        shape: rq.shape.clone(),
853    }
854}
855
856/// Whether `EGRAPH_DUMP_PLAN` is set, read once. The variable is read at the first
857/// scheduled query and cached, so an unset environment costs one relaxed load per plan.
858fn dump_plan_enabled() -> bool {
859    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
860    *ON.get_or_init(|| std::env::var_os("EGRAPH_DUMP_PLAN").is_some())
861}
862
863/// Print the scheduled plan to stderr, one line per step, in the form chapter 8's
864/// "Example Plan" section uses. Variables are printed by their resolved index, so a
865/// step's `v3` is variable 3 of the query's `MatchShape`.
866///
867/// This is the diagnostic the pre-bound-child defect in `ematch.rs` was found with: the
868/// dump showed a `Join` keyed on `v0` scheduled after an `ExpandA` that listed `v0`
869/// among its fixed children, which is the order that made the expansion's cleanup unbind
870/// a variable the join then read.
871fn dump_plan<O: std::fmt::Debug, I: std::fmt::Debug, V>(steps: &[Step<O, I, V>], atoms: usize) {
872    eprintln!("=== plan: {} atoms, {} steps ===", atoms, steps.len());
873    for (i, st) in steps.iter().enumerate() {
874        eprintln!("step[{i}]: {}", fmt_step(st));
875    }
876}
877
878fn fmt_step<O: std::fmt::Debug, I: std::fmt::Debug, V>(st: &Step<O, I, V>) -> String {
879    match st {
880        Step::BindGlobal { target, global } => {
881            format!("BindGlobal target=v{} global={global:?}", target.idx())
882        }
883        Step::Join {
884            target,
885            lookups,
886            atom_id,
887        } => format!(
888            "Join target=v{} atom={atom_id} lookups={lookups:?}",
889            target.idx()
890        ),
891        Step::ExtractChild {
892            target,
893            parent,
894            pos,
895        } => format!(
896            "ExtractChild target=v{} parent=v{} pos={pos:?}",
897            target.idx(),
898            parent.idx()
899        ),
900        Step::CheckChildEq {
901            parent,
902            pos,
903            expected,
904        } => format!(
905            "CheckChildEq parent=v{} pos={pos:?} expected={expected:?}",
906            parent.idx()
907        ),
908        Step::CheckEq { a, b } => format!("CheckEq v{} v{}", a.idx(), b.idx()),
909        Step::CheckEqGlobal { local, global } => {
910            format!("CheckEqGlobal v{} global={global:?}", local.idx())
911        }
912        Step::CopyBinding { target, other } => {
913            format!("CopyBinding target=v{} from=v{}", target.idx(), other.idx())
914        }
915        Step::ExpandA {
916            node,
917            children,
918            pre,
919            suf,
920        } => format!(
921            "ExpandA node=v{} children={children:?} pre={pre:?} suf={suf:?}",
922            node.idx()
923        ),
924        Step::DecomposeAC {
925            node,
926            elems,
927            rest,
928            idempotent,
929        } => format!(
930            "DecomposeAC node=v{} elems={elems:?} rest={rest:?} idempotent={idempotent}",
931            node.idx()
932        ),
933        Step::DecomposeACI { node, elems, rest } => format!(
934            "DecomposeACI node=v{} elems={elems:?} rest={rest:?}",
935            node.idx()
936        ),
937        Step::ExtractLitVal { node, val } => {
938            format!("ExtractLitVal node=v{} val={val:?}", node.idx())
939        }
940        Step::CheckLit { node, .. } => format!("CheckLit node=v{}", node.idx()),
941        Step::CheckPred { .. } => "CheckPred".to_string(),
942    }
943}
944
945fn emit_read_children<O: DenseId + Hash + Copy, S, V, I: IndexLike>(
946    atom: &RAtom<O, S, V>,
947    bound: &mut [bool],
948    steps: &mut Vec<Step<O, I, V>>,
949) {
950    if let RAtom::Plain { node, children, .. } = atom {
951        for (pos, &cv) in children.iter().enumerate() {
952            if !pv_is_bound(&cv, bound) {
953                let PatVar::Local(vid) = cv else {
954                    unreachable!()
955                };
956                steps.push(Step::ExtractChild {
957                    target: vid,
958                    parent: *node,
959                    pos: child_pos::<I>(pos),
960                });
961                pv_mark_bound(&cv, bound);
962            } else {
963                steps.push(Step::CheckChildEq {
964                    parent: *node,
965                    pos: child_pos::<I>(pos),
966                    expected: cv,
967                });
968            }
969        }
970    }
971}
972
973/// Run the eager pass to fixpoint: lower every atom the current bindings make
974/// free (see [`try_eager_lower`]), marking each one used and binding whatever it
975/// binds, until no unused atom is free any more.
976///
977/// Shared by the static scheduler's Phase A and the runtime-scheduled matcher,
978/// which reaches the same fixpoint at each of its decision points before it
979/// costs the remaining atoms.
980pub(crate) fn lower_eager<O: DenseId + Hash + Copy, S, V: Clone, I: IndexLike>(
981    atoms: &[RAtom<O, S, V>],
982    used: &mut [bool],
983    bound: &mut [bool],
984    steps: &mut Vec<Step<O, I, V>>,
985) {
986    let mut progress = true;
987    while progress {
988        progress = false;
989        for ai in 0..atoms.len() {
990            if used[ai] {
991                continue;
992            }
993            // A guard is free exactly when the atoms binding its values have run.
994            // That is a condition on `used`, not on `bound`, and it has to be: the
995            // node variable of a `LitBind` atom is bound by the enclosing pattern's
996            // `ExtractChild`, one step before the `ExtractLitVal` that fills the
997            // value slot the guard reads.
998            if let RAtom::Pred { guard, deps } = &atoms[ai] {
999                if deps.iter().all(|d| used[*d]) {
1000                    steps.push(Step::CheckPred {
1001                        guard: guard.clone(),
1002                    });
1003                    used[ai] = true;
1004                    progress = true;
1005                }
1006                continue;
1007            }
1008            if let Some(eager) = try_eager_lower(&atoms[ai], ai, bound) {
1009                steps.extend(eager);
1010                used[ai] = true;
1011                progress = true;
1012            }
1013        }
1014    }
1015}
1016
1017pub(crate) fn emit_atom<O: DenseId + Hash + Copy, S, V: Clone, I: IndexLike>(
1018    atom: &RAtom<O, S, V>,
1019    atom_id: usize,
1020    bound: &mut [bool],
1021    steps: &mut Vec<Step<O, I, V>>,
1022) {
1023    match atom {
1024        RAtom::Plain { node, op, children } => {
1025            let mut lookups = vec![IndexLookup::ByOp { op: *op }];
1026            for (pos, &cv) in children.iter().enumerate() {
1027                if pv_is_bound(&cv, bound) {
1028                    lookups.push(IndexLookup::ByChildPos {
1029                        child: cv,
1030                        pos: child_pos::<I>(pos),
1031                    });
1032                }
1033            }
1034            steps.push(Step::Join {
1035                target: *node,
1036                lookups,
1037                atom_id,
1038            });
1039            bound[(*node).idx()] = true;
1040            for (pos, &cv) in children.iter().enumerate() {
1041                if !pv_is_bound(&cv, bound) {
1042                    let PatVar::Local(vid) = cv else {
1043                        unreachable!()
1044                    };
1045                    steps.push(Step::ExtractChild {
1046                        target: vid,
1047                        parent: *node,
1048                        pos: child_pos::<I>(pos),
1049                    });
1050                    pv_mark_bound(&cv, bound);
1051                } else {
1052                    steps.push(Step::CheckChildEq {
1053                        parent: *node,
1054                        pos: child_pos::<I>(pos),
1055                        expected: cv,
1056                    });
1057                }
1058            }
1059        }
1060        RAtom::Lit {
1061            node, op, value, ..
1062        } => {
1063            if !bound[(*node).idx()] {
1064                steps.push(Step::Join {
1065                    target: *node,
1066                    lookups: vec![IndexLookup::ByOp { op: *op }],
1067                    atom_id,
1068                });
1069                bound[(*node).idx()] = true;
1070            }
1071            steps.push(Step::CheckLit {
1072                node: *node,
1073                value: value.clone(),
1074            });
1075        }
1076        RAtom::LitBind { node, op, val } => {
1077            if !bound[(*node).idx()] {
1078                steps.push(Step::Join {
1079                    target: *node,
1080                    lookups: vec![IndexLookup::ByOp { op: *op }],
1081                    atom_id,
1082                });
1083                bound[(*node).idx()] = true;
1084            }
1085            steps.push(Step::ExtractLitVal {
1086                node: *node,
1087                val: *val,
1088            });
1089        }
1090        // Never selected by phase B: the equalities and the guards have no join to
1091        // cost, and `schedule_inner`/`choose_atom` skip them for that reason. The
1092        // eager pass owns them.
1093        RAtom::Eq(..) | RAtom::EqGlobal(..) | RAtom::Pred { .. } => {}
1094        RAtom::AExact { node, op, children } => {
1095            emit_variadic_join(node, *op, atom_id, children, bound, steps);
1096            steps.push(Step::ExpandA {
1097                node: *node,
1098                children: children.clone(),
1099                pre: None,
1100                suf: None,
1101            });
1102            for &cv in children {
1103                pv_mark_bound(&cv, bound);
1104            }
1105        }
1106        RAtom::APrefix {
1107            node,
1108            op,
1109            pre,
1110            fixed,
1111        } => {
1112            emit_variadic_join(node, *op, atom_id, fixed, bound, steps);
1113            steps.push(Step::ExpandA {
1114                node: *node,
1115                children: fixed.clone(),
1116                pre: Some(*pre),
1117                suf: None,
1118            });
1119            for &cv in fixed {
1120                pv_mark_bound(&cv, bound);
1121            }
1122        }
1123        RAtom::ASuffix {
1124            node,
1125            op,
1126            fixed,
1127            suf,
1128        } => {
1129            emit_variadic_join(node, *op, atom_id, fixed, bound, steps);
1130            steps.push(Step::ExpandA {
1131                node: *node,
1132                children: fixed.clone(),
1133                pre: None,
1134                suf: Some(*suf),
1135            });
1136            for &cv in fixed {
1137                pv_mark_bound(&cv, bound);
1138            }
1139        }
1140        RAtom::ABoth {
1141            node,
1142            op,
1143            pre,
1144            fixed,
1145            suf,
1146        } => {
1147            emit_variadic_join(node, *op, atom_id, fixed, bound, steps);
1148            steps.push(Step::ExpandA {
1149                node: *node,
1150                children: fixed.clone(),
1151                pre: Some(*pre),
1152                suf: Some(*suf),
1153            });
1154            for &cv in fixed {
1155                pv_mark_bound(&cv, bound);
1156            }
1157        }
1158        RAtom::ACExact { node, op, elems } => {
1159            let evs: Vec<PatVar> = elems.iter().map(|(ev, _)| *ev).collect();
1160            emit_variadic_join(node, *op, atom_id, &evs, bound, steps);
1161            steps.push(Step::DecomposeAC {
1162                node: *node,
1163                elems: elems.clone(),
1164                rest: None,
1165                idempotent: false,
1166            });
1167            for (ev, _) in elems {
1168                pv_mark_bound(ev, bound);
1169            }
1170        }
1171        RAtom::ACSub {
1172            node,
1173            op,
1174            elems,
1175            rest,
1176        } => {
1177            let evs: Vec<PatVar> = elems.iter().map(|(ev, _)| *ev).collect();
1178            emit_variadic_join(node, *op, atom_id, &evs, bound, steps);
1179            steps.push(Step::DecomposeAC {
1180                node: *node,
1181                elems: elems.clone(),
1182                rest: Some(*rest),
1183                idempotent: false,
1184            });
1185            for (ev, _) in elems {
1186                pv_mark_bound(ev, bound);
1187            }
1188        }
1189        RAtom::ACIExact { node, op, elems } => {
1190            emit_variadic_join(node, *op, atom_id, elems, bound, steps);
1191            steps.push(Step::DecomposeACI {
1192                node: *node,
1193                elems: elems.clone(),
1194                rest: None,
1195            });
1196            for &ev in elems {
1197                pv_mark_bound(&ev, bound);
1198            }
1199        }
1200        RAtom::ACISub {
1201            node,
1202            op,
1203            elems,
1204            rest,
1205        } => {
1206            emit_variadic_join(node, *op, atom_id, elems, bound, steps);
1207            steps.push(Step::DecomposeACI {
1208                node: *node,
1209                elems: elems.clone(),
1210                rest: Some(*rest),
1211            });
1212            for &ev in elems {
1213                pv_mark_bound(&ev, bound);
1214            }
1215        }
1216    }
1217}
1218
1219/// Try to lower an atom that is *forced or free* given the current bindings —
1220/// the "eager pass" cases that cost nothing to resolve and only shrink the
1221/// problem: `Eq`/`EqGlobal` constraints between bound vars, and
1222/// `Lit`/`LitBind`/`Plain` whose node var is already bound (re-join within its
1223/// class). Returns `Some(steps)` and marks newly-bound vars if the atom is
1224/// eagerly resolvable now; `None` if it must wait for cost-based selection
1225/// (an unbound scanning atom). Single source of truth shared by the static
1226/// scheduler's eager pass and the runtime-adaptive matcher.
1227pub(crate) fn try_eager_lower<O: DenseId + Hash + Copy, S, V: Clone, I: IndexLike>(
1228    atom: &RAtom<O, S, V>,
1229    atom_id: usize,
1230    bound: &mut [bool],
1231) -> Option<Vec<Step<O, I, V>>> {
1232    let mut steps = Vec::new();
1233    match atom {
1234        RAtom::Eq(a, b) => {
1235            if bound[(*a).idx()] && bound[(*b).idx()] {
1236                steps.push(Step::CheckEq { a: *a, b: *b });
1237            } else if bound[(*a).idx()] {
1238                steps.push(Step::CopyBinding {
1239                    target: *b,
1240                    other: *a,
1241                });
1242                bound[(*b).idx()] = true;
1243            } else if bound[(*b).idx()] {
1244                steps.push(Step::CopyBinding {
1245                    target: *a,
1246                    other: *b,
1247                });
1248                bound[(*a).idx()] = true;
1249            } else {
1250                return None;
1251            }
1252        }
1253        RAtom::EqGlobal(local, global) if bound[(*local).idx()] => {
1254            steps.push(Step::CheckEqGlobal {
1255                local: *local,
1256                global: *global,
1257            });
1258        }
1259        RAtom::EqGlobal(local, global) => {
1260            // Unbound: the atom is what gives the variable its value.
1261            steps.push(Step::BindGlobal {
1262                target: *local,
1263                global: *global,
1264            });
1265            bound[(*local).idx()] = true;
1266        }
1267        RAtom::Lit {
1268            node, op, value, ..
1269        } if bound[(*node).idx()] => {
1270            steps.push(Step::Join {
1271                target: *node,
1272                lookups: vec![
1273                    IndexLookup::ByRepr { repr: *node },
1274                    IndexLookup::ByOp { op: *op },
1275                ],
1276                atom_id,
1277            });
1278            steps.push(Step::CheckLit {
1279                node: *node,
1280                value: value.clone(),
1281            });
1282        }
1283        RAtom::LitBind { node, op, val } if bound[(*node).idx()] => {
1284            steps.push(Step::Join {
1285                target: *node,
1286                lookups: vec![
1287                    IndexLookup::ByRepr { repr: *node },
1288                    IndexLookup::ByOp { op: *op },
1289                ],
1290                atom_id,
1291            });
1292            steps.push(Step::ExtractLitVal {
1293                node: *node,
1294                val: *val,
1295            });
1296        }
1297        RAtom::Plain { node, op, .. } if bound[(*node).idx()] => {
1298            steps.push(Step::Join {
1299                target: *node,
1300                lookups: vec![
1301                    IndexLookup::ByRepr { repr: *node },
1302                    IndexLookup::ByOp { op: *op },
1303                ],
1304                atom_id,
1305            });
1306            emit_read_children(atom, bound, &mut steps);
1307        }
1308        _ => return None,
1309    }
1310    Some(steps)
1311}
1312
1313fn emit_variadic_join<O: DenseId + Hash + Copy, I: IndexLike, V>(
1314    node: &VarId,
1315    op: O,
1316    atom_id: usize,
1317    elems: &[PatVar],
1318    bound: &mut [bool],
1319    steps: &mut Vec<Step<O, I, V>>,
1320) {
1321    if !bound[(*node).idx()] {
1322        // Drive from `by_op[op]`, intersected with `by_contains[e]` for every
1323        // element `e` already bound. A matching variadic node MUST contain each
1324        // bound element, so `by_contains[e]` is a sound (membership-only) filter
1325        // — the following DecomposeAC/ExpandA/DecomposeACI does the precise
1326        // multiplicity/position check. This narrows the driver to the few
1327        // parents containing the bound element instead of scanning the whole
1328        // `by_op` bucket — the variadic analogue of `Plain`'s `ByChildPos`.
1329        let mut lookups = vec![IndexLookup::ByOp { op }];
1330        for &pv in elems {
1331            if pv_is_bound(&pv, bound) {
1332                lookups.push(IndexLookup::ByContains { child: pv });
1333            }
1334        }
1335        steps.push(Step::Join {
1336            target: *node,
1337            lookups,
1338            atom_id,
1339        });
1340        bound[(*node).idx()] = true;
1341    } else {
1342        // The node var is already bound — e.g. extracted as an enclosing
1343        // atom's child via `ExtractChild`. Re-join within its class
1344        // (`ByRepr ∩ ByOp`), exactly as the `Plain` bound-node path does, so
1345        // this atom still emits a `Step::Join` carrying `atom_id`. Without it,
1346        // the semi-naive variant mode (delta / full∖delta / full) — which is
1347        // realized *only* on `Step::Join` (see `ematch::run_join`) — would
1348        // never be applied to a parent-driven variadic atom, letting the
1349        // parent-driven variant re-discover matches the delta-driven variants
1350        // already own. In the naive path this re-join is a no-op intersection
1351        // (the node re-selects itself within its own class).
1352        steps.push(Step::Join {
1353            target: *node,
1354            lookups: vec![
1355                IndexLookup::ByRepr { repr: *node },
1356                IndexLookup::ByOp { op },
1357            ],
1358            atom_id,
1359        });
1360    }
1361}
1362
1363#[cfg(test)]
1364mod tests {
1365    use super::*;
1366    use crate::id::{OpId, SortId};
1367    use crate::lit_model::LitModel;
1368    use crate::literal::{LitValStore, NiraLitVal, NiraModel};
1369    use crate::nodes::LitValId;
1370    use crate::registry::{OpRegistry, SortRegistry};
1371    use crate::resolve::MatchShape;
1372    use crate::resolve::resolve;
1373    use crate::sortcheck::flatten_surface as flatten;
1374    use crate::test_helpers::parse_pattern;
1375
1376    fn setup() -> (
1377        OpRegistry<OpId, SortId, false>,
1378        SortRegistry<SortId, false>,
1379        LitValStore<NiraLitVal, LitValId, false>,
1380    ) {
1381        let model = NiraModel;
1382        let mut sorts: SortRegistry<SortId, false> = SortRegistry::new();
1383        let sort_names: Vec<&str> = model.sorts().iter().map(|s| s.name).collect();
1384        sorts.register_builtins(&sort_names);
1385        let e = sorts.intern("IExpr");
1386        let mut ops = OpRegistry::new();
1387        ops.register_builtins(&model, &sorts);
1388        ops.register("f", &[e, e], e);
1389        ops.register("g", &[e], e);
1390        ops.register("h", &[e, e], e);
1391        ops.register_a("concat", e, e, crate::registry::AssocDir::Right);
1392        ops.register_mset("add", e, e);
1393        ops.register_set("union", e, e);
1394        let ibig = sorts.id_by_name("IBig").expect("IBig builtin");
1395        ops.register("ILit", &[ibig], e);
1396        (ops, sorts, LitValStore::new())
1397    }
1398
1399    fn do_plan(src: &str) -> (QueryPlan<OpId, u32, NiraLitVal>, MatchShape) {
1400        let (ops, sorts, _) = setup();
1401        let model = NiraModel;
1402        let pat = parse_pattern(src);
1403        let fq = flatten(&[pat], &ops).unwrap();
1404        let rq = resolve(
1405            &fq,
1406            &ops,
1407            &sorts,
1408            &model,
1409            &crate::resolve::GlobalCtx::<_, ()>::new(),
1410        )
1411        .unwrap();
1412        (schedule(&rq), rq.shape)
1413    }
1414
1415    fn do_plan_multi(srcs: &[&str]) -> (QueryPlan<OpId, u32, NiraLitVal>, MatchShape) {
1416        let (ops, sorts, _) = setup();
1417        let model = NiraModel;
1418        let pats: Vec<_> = srcs.iter().map(|s| parse_pattern(s)).collect();
1419        let fq = flatten(&pats, &ops).unwrap();
1420        let rq = resolve(
1421            &fq,
1422            &ops,
1423            &sorts,
1424            &model,
1425            &crate::resolve::GlobalCtx::<_, ()>::new(),
1426        )
1427        .unwrap();
1428        (schedule(&rq), rq.shape)
1429    }
1430
1431    fn do_plan_with_stats(
1432        srcs: &[&str],
1433        card: &[(&str, usize)],
1434    ) -> (QueryPlan<OpId, u32, NiraLitVal>, MatchShape) {
1435        let (ops, sorts, _) = setup();
1436        let model = NiraModel;
1437        let pats: Vec<_> = srcs.iter().map(|s| parse_pattern(s)).collect();
1438        let fq = flatten(&pats, &ops).unwrap();
1439        let rq = resolve(
1440            &fq,
1441            &ops,
1442            &sorts,
1443            &model,
1444            &crate::resolve::GlobalCtx::<_, ()>::new(),
1445        )
1446        .unwrap();
1447        let mut stats = IndexStats::new();
1448        for &(name, c) in card {
1449            let op_id = ops.id_by_name(name).unwrap();
1450            stats.op_card.insert(op_id, c);
1451        }
1452        (schedule_with_stats(&rq, &stats), rq.shape)
1453    }
1454
1455    /// A guard runs as soon as its values are bound, not at the end of the plan: the
1456    /// check sits immediately after the last `ExtractLitVal` it depends on, so a false
1457    /// guard cuts the search before the remaining atoms are joined.
1458    #[test]
1459    fn guard_runs_as_soon_as_its_values_are_bound() {
1460        let (plan, _) = do_plan_multi(&["(f (ILit a) (ILit b))", "(< a b)", "(g y)"]);
1461        let pred = plan
1462            .steps
1463            .iter()
1464            .position(|s| matches!(s, Step::CheckPred { .. }))
1465            .expect("guard step");
1466        let last_extract = plan
1467            .steps
1468            .iter()
1469            .rposition(|s| matches!(s, Step::ExtractLitVal { .. }))
1470            .expect("lit-val extraction");
1471        assert_eq!(pred, last_extract + 1);
1472        // The unrelated atom is still to come, so the guard cut it off.
1473        assert!(
1474            plan.steps[pred + 1..]
1475                .iter()
1476                .any(|s| matches!(s, Step::Join { .. }))
1477        );
1478    }
1479
1480    /// The root-binding form costs one step when the bound name is fresh: the root is
1481    /// copied onto it, not re-searched.
1482    #[test]
1483    fn root_binding_copies_the_root() {
1484        let (plan, shape) = do_plan("(= v (g x))");
1485        let v = shape.find_var("v").unwrap();
1486        assert!(
1487            plan.steps
1488                .iter()
1489                .any(|s| matches!(s, Step::CopyBinding { target, .. } if *target == v))
1490        );
1491    }
1492
1493    #[test]
1494    fn plain_flat() {
1495        let (qp, _) = do_plan("(f x y)");
1496        assert_eq!(qp.steps.len(), 3);
1497        assert!(matches!(&qp.steps[0], Step::Join { lookups, .. }
1498            if matches!(&lookups[0], IndexLookup::ByOp { .. })));
1499        assert!(matches!(&qp.steps[1], Step::ExtractChild { pos: 0, .. }));
1500        assert!(matches!(&qp.steps[2], Step::ExtractChild { pos: 1, .. }));
1501    }
1502
1503    #[test]
1504    fn nested() {
1505        let (qp, _) = do_plan("(f x (g y))");
1506        let join_count = qp
1507            .steps
1508            .iter()
1509            .filter(|s| matches!(s, Step::Join { .. }))
1510            .count();
1511        assert_eq!(join_count, 2);
1512    }
1513
1514    #[test]
1515    fn multi_atom_shared_var() {
1516        let (qp, vars) = do_plan_multi(&["(f x y)", "(g y)"]);
1517        let y = vars.find_var("y").unwrap();
1518        // g has 1 arg, so after f binds y, g-join should use ByChildPos(y, 0)
1519        let g_join = qp.steps.iter().find(|s| match s {
1520            Step::Join { lookups, .. } => lookups.len() > 1,
1521            _ => false,
1522        });
1523        assert!(g_join.is_some());
1524        if let Step::Join { lookups, .. } = g_join.unwrap() {
1525            assert!(
1526                lookups
1527                    .iter()
1528                    .any(|l| matches!(l, IndexLookup::ByChildPos { child, pos: 0 } if *child == PatVar::Local(y)))
1529            );
1530        }
1531    }
1532
1533    /// A ground literal in a pattern must compile to a *satisfiable* plan: a join that
1534    /// actually reads an index, followed by the payload check that pins the value.
1535    /// Regression for the dead-literal defect — the literal atom used to emit
1536    /// `Join { lookups: [] }`, and an empty lookup vector makes both matcher engines
1537    /// abandon the query, so the whole rule was inert.
1538    #[test]
1539    fn literal_atom_joins_and_checks_payload() {
1540        let (qp, _) = do_plan("(f (ILit 42) x)");
1541        for step in &qp.steps {
1542            if let Step::Join { lookups, .. } = step {
1543                assert!(
1544                    !lookups.is_empty(),
1545                    "a join with no lookups yields no candidates: {qp:?}"
1546                );
1547            }
1548        }
1549        let checks: Vec<_> = qp
1550            .steps
1551            .iter()
1552            .filter(|s| matches!(s, Step::CheckLit { .. }))
1553            .collect();
1554        assert_eq!(checks.len(), 1, "expected one payload check in {qp:?}");
1555        assert!(
1556            matches!(checks[0], Step::CheckLit { value, .. } if value.to_string() == "42"),
1557            "payload check does not carry the pattern's literal: {qp:?}"
1558        );
1559    }
1560
1561    #[test]
1562    fn nonlinear_check_eq() {
1563        let (qp, _) = do_plan("(f x x)");
1564        assert!(
1565            qp.steps
1566                .iter()
1567                .any(|s| matches!(s, Step::CheckChildEq { .. }))
1568        );
1569    }
1570
1571    #[test]
1572    fn ac_subset() {
1573        let (qp, _) = do_plan("(add x:2 ..rest)");
1574        assert!(qp.steps.iter().any(|s| matches!(
1575            s,
1576            Step::DecomposeAC {
1577                rest: Some(_),
1578                idempotent: false,
1579                ..
1580            }
1581        )));
1582    }
1583
1584    #[test]
1585    fn aci_subset() {
1586        let (qp, _) = do_plan("(union x y ..rest)");
1587        assert!(
1588            qp.steps
1589                .iter()
1590                .any(|s| matches!(s, Step::DecomposeACI { rest: Some(_), .. }))
1591        );
1592    }
1593
1594    #[test]
1595    fn a_prefix() {
1596        let (qp, _) = do_plan("(concat ..pre x y)");
1597        assert!(qp.steps.iter().any(|s| matches!(
1598            s,
1599            Step::ExpandA {
1600                pre: Some(_),
1601                suf: None,
1602                ..
1603            }
1604        )));
1605    }
1606
1607    #[test]
1608    fn selectivity_picks_rarest() {
1609        let (qp, _) = do_plan_with_stats(&["(f x (g y))"], &[("f", 10_000), ("g", 10)]);
1610        // First Join should be for g (rarest)
1611        let first_join = qp
1612            .steps
1613            .iter()
1614            .find(|s| matches!(s, Step::Join { .. }))
1615            .unwrap();
1616        if let Step::Join { lookups, .. } = first_join {
1617            let (ops, _, _) = setup();
1618            let g_id = ops.id_by_name("g").unwrap();
1619            assert!(
1620                lookups
1621                    .iter()
1622                    .any(|l| matches!(l, IndexLookup::ByOp { op } if *op == g_id))
1623            );
1624        }
1625    }
1626
1627    #[test]
1628    fn selectivity_three_atoms() {
1629        let (qp, _) = do_plan_with_stats(
1630            &["(f x y)", "(g y)", "(h y w)"],
1631            &[("f", 10_000), ("g", 500), ("h", 5)],
1632        );
1633        let (ops, _, _) = setup();
1634        let join_ops: Vec<OpId> = qp
1635            .steps
1636            .iter()
1637            .filter_map(|s| match s {
1638                Step::Join { lookups, .. } => lookups.iter().find_map(|l| match l {
1639                    IndexLookup::ByOp { op } => Some(*op),
1640                    _ => None,
1641                }),
1642                _ => None,
1643            })
1644            .collect();
1645        let h = ops.id_by_name("h").unwrap();
1646        let g = ops.id_by_name("g").unwrap();
1647        let f = ops.id_by_name("f").unwrap();
1648        assert_eq!(join_ops, [h, g, f]);
1649    }
1650
1651    #[test]
1652    fn bound_child_reduces_cost() {
1653        let (qp, _) = do_plan_with_stats(&["(f x y)", "(h y z)"], &[("f", 1000), ("h", 1000)]);
1654        let second_join = qp
1655            .steps
1656            .iter()
1657            .filter(|s| matches!(s, Step::Join { .. }))
1658            .nth(1);
1659        if let Some(Step::Join { lookups, .. }) = second_join {
1660            assert!(
1661                lookups
1662                    .iter()
1663                    .any(|l| matches!(l, IndexLookup::ByChildPos { .. }))
1664            );
1665        }
1666    }
1667
1668    /// The captured fan-out constants, not the atoms' cardinalities, decide
1669    /// which atom is joined second. This regression retains a historically
1670    /// problematic shape:
1671    /// two `f` atoms sharing a child and joined only through their common `h`
1672    /// parent, with `f` = Mul and `h` = Add. Both candidates have one bound
1673    /// child once the first `f` is
1674    /// scanned, so the fixed halving compared 54,051/2 against 86,061/2 and
1675    /// took the `f` atom, whose `by_child_pos` probe returns 1,239 nodes
1676    /// instead of the 43,030 charged. With the fan-outs measured, the `h` atom
1677    /// is charged 1.5 and wins, and the second `f` then costs a `ByRepr`
1678    /// re-join within the class the `h` atom bound.
1679    #[test]
1680    fn measured_fanouts_beat_cardinalities_on_sibling_atoms() {
1681        let (ops, _, _) = setup();
1682        let f = ops.id_by_name("f").unwrap();
1683        let h = ops.id_by_name("h").unwrap();
1684
1685        let mut stats = IndexStats::<OpId>::new();
1686        stats.op_card.insert(f, 54_051);
1687        stats.op_card.insert(h, 86_061);
1688        stats.fanouts.nodes = 216_061;
1689        stats.fanouts.by_repr = 2.51;
1690        // `f` nodes share their first child with 1,239 siblings on average;
1691        // `h` nodes almost never share theirs.
1692        stats.fanouts.by_child_pos.insert((f, 0), 1_239.0);
1693        stats.fanouts.by_child_pos.insert((f, 1), 1_239.0);
1694        stats.fanouts.by_child_pos.insert((h, 0), 1.5);
1695        stats.fanouts.by_child_pos.insert((h, 1), 1.5);
1696
1697        let join_ops = |stats: &IndexStats<OpId>| -> Vec<OpId> {
1698            let (ops, sorts, _) = setup();
1699            let pats = [parse_pattern("(h (f a b) (f a c))")];
1700            let fq = flatten(&pats, &ops).unwrap();
1701            let rq = resolve(
1702                &fq,
1703                &ops,
1704                &sorts,
1705                &NiraModel,
1706                &crate::resolve::GlobalCtx::<_, ()>::new(),
1707            )
1708            .unwrap();
1709            let qp: QueryPlan<OpId, u32, NiraLitVal> = schedule_with_stats(&rq, stats);
1710            qp.steps
1711                .iter()
1712                .filter_map(|s| match s {
1713                    Step::Join { lookups, .. } => lookups.iter().find_map(|l| match l {
1714                        IndexLookup::ByOp { op } => Some(*op),
1715                        _ => None,
1716                    }),
1717                    _ => None,
1718                })
1719                .collect()
1720        };
1721
1722        // Control: the same cardinalities with no measurements reproduce the
1723        // defect, so the assertion below is about the constants and not about
1724        // some other difference between the two runs.
1725        let mut halving = IndexStats::<OpId>::new();
1726        halving.op_card.insert(f, 54_051);
1727        halving.op_card.insert(h, 86_061);
1728        assert_eq!(
1729            join_ops(&halving),
1730            [f, f, h],
1731            "the fixed halving should still join the second f before h"
1732        );
1733        assert_eq!(
1734            join_ops(&stats),
1735            [f, h, f],
1736            "measured fan-outs should join h second, leaving the second f a class re-join"
1737        );
1738    }
1739
1740    /// A bound element discounts a variadic atom's cost, just as a bound child
1741    /// discounts a `Plain` atom — so `estimate_cost` reflects the `by_contains`
1742    /// narrowing that `emit_variadic_join` performs. Without the discount a
1743    /// fully-bound variadic atom would be mis-costed as a full `by_op` scan.
1744    #[test]
1745    fn bound_element_discounts_variadic_cost() {
1746        let (ops, _, _) = setup();
1747        let add = ops.id_by_name("add").unwrap();
1748        let mut stats = IndexStats::<OpId>::new();
1749        stats.op_card.insert(add, 1000);
1750
1751        // ACSub `(add x:1 ..rest)` with one element var `x` (VarId 0).
1752        let atom = RAtom::<OpId, SortId, NiraLitVal>::ACSub {
1753            node: VarId::new(1),
1754            op: add,
1755            elems: vec![(PatVar::Local(VarId::new(0)), RMult::Exact(1))],
1756            rest: crate::ast::MsetVarId::new(0),
1757        };
1758
1759        let cost_of = |bound: &[bool]| {
1760            let mut ctx = Cost {
1761                stats: &stats,
1762                emitters: vec![None; bound.len()],
1763                sampling: None,
1764            };
1765            estimate_cost(std::slice::from_ref(&atom), 0, bound, &mut ctx)
1766        };
1767
1768        // x unbound → full op cardinality. (atom_id 0; no per-atom override,
1769        // so it falls back to op_card.)
1770        let bound_none = [false, false];
1771        assert_eq!(cost_of(&bound_none), 1000.0);
1772
1773        // x bound → discounted (halved per bound element), reflecting the
1774        // `by_contains[x]` intersection the join will apply.
1775        let bound_x = [true, false];
1776        let cost_bound = cost_of(&bound_x);
1777        assert!(
1778            cost_bound < 1000.0,
1779            "binding an element must discount a variadic atom's cost, got {cost_bound}"
1780        );
1781        assert_eq!(
1782            cost_bound, 500.0,
1783            "with no measured fan-out one bound element halves the estimate"
1784        );
1785    }
1786
1787    /// A sampler that answers every probe with a per-operator constant, and
1788    /// records which atom it was asked to draw from.
1789    struct StubSampler {
1790        lens: std::collections::HashMap<OpId, usize>,
1791        drawn: std::cell::RefCell<Vec<usize>>,
1792    }
1793
1794    impl CrossSampler<OpId> for StubSampler {
1795        fn driver_sample(&self, atom_id: usize, _op: OpId, k: usize, out: &mut Vec<usize>) {
1796            self.drawn.borrow_mut().push(atom_id);
1797            out.clear();
1798            out.extend(0..k);
1799        }
1800        fn key_classes(&self, node: usize, _site: KeySite, out: &mut Vec<usize>) {
1801            out.push(node);
1802        }
1803        fn probe_len(&self, _class: usize, _path: ProbePath, op: OpId) -> usize {
1804            self.lens.get(&op).copied().unwrap_or(0)
1805        }
1806    }
1807
1808    /// The sampled bucket length replaces the round's mean fan-out in the cost,
1809    /// and the draw is taken from the atom that bound the key.
1810    ///
1811    /// `(f x y) (g y) (h y w)` with `f` cheapest, so both estimators drive from
1812    /// it and both then choose between `g` and `h` on the same bound `y`. The
1813    /// mean has `g`'s probe returning 1 node and `h`'s 500, and orders `g`
1814    /// second. The sampler reverses the two numbers on the same statistics, and
1815    /// the order reverses with them — which is only possible if the fan-out is
1816    /// what the sample displaces. The draw must come from atom 0: `y` is `f`'s
1817    /// second child, and no other scheduled atom binds it.
1818    #[test]
1819    fn a_sampled_bucket_displaces_the_mean_fanout() {
1820        let (ops, sorts, _) = setup();
1821        let (f, g, h) = (
1822            ops.id_by_name("f").unwrap(),
1823            ops.id_by_name("g").unwrap(),
1824            ops.id_by_name("h").unwrap(),
1825        );
1826        let mut stats = IndexStats::<OpId>::new();
1827        stats.op_card.insert(f, 10);
1828        stats.op_card.insert(g, 1_000);
1829        stats.op_card.insert(h, 1_000);
1830        stats.fanouts.by_child_pos.insert((g, 0), 1.0);
1831        stats.fanouts.by_child_pos.insert((h, 0), 500.0);
1832
1833        let pats: Vec<_> = ["(f x y)", "(g y)", "(h y w)"]
1834            .iter()
1835            .map(|s| parse_pattern(s))
1836            .collect();
1837        let fq = flatten(&pats, &ops).unwrap();
1838        let rq = resolve(
1839            &fq,
1840            &ops,
1841            &sorts,
1842            &NiraModel,
1843            &crate::resolve::GlobalCtx::<_, ()>::new(),
1844        )
1845        .unwrap();
1846        let join_ops = |plan: &QueryPlan<OpId, u32, NiraLitVal>| -> Vec<OpId> {
1847            plan.steps
1848                .iter()
1849                .filter_map(|s| match s {
1850                    Step::Join { lookups, .. } => lookups.iter().find_map(|l| match l {
1851                        IndexLookup::ByOp { op } => Some(*op),
1852                        _ => None,
1853                    }),
1854                    _ => None,
1855                })
1856                .collect()
1857        };
1858
1859        assert_eq!(
1860            join_ops(&schedule_with_stats(&rq, &stats)),
1861            [f, g, h],
1862            "the mean should join g second"
1863        );
1864
1865        let stub = StubSampler {
1866            lens: [(g, 400usize), (h, 2usize)].into_iter().collect(),
1867            drawn: std::cell::RefCell::new(Vec::new()),
1868        };
1869        let cfg = SamplerConfig::default();
1870        let plan: QueryPlan<OpId, u32, NiraLitVal> =
1871            schedule_inner(&rq, &stats, Some((&stub, cfg)));
1872        assert_eq!(
1873            join_ops(&plan),
1874            [f, h, g],
1875            "the sampled lengths should join h second"
1876        );
1877        let drawn = stub.drawn.into_inner();
1878        assert_eq!(
1879            drawn,
1880            vec![0],
1881            "the draw must come once from the atom that bound the key"
1882        );
1883    }
1884
1885    /// With sampling off the sampler is never consulted, so a caller may hold
1886    /// one unconditionally: the flag alone decides.
1887    #[test]
1888    fn the_flag_off_path_never_samples() {
1889        let (ops, sorts, _) = setup();
1890        let pats = [parse_pattern("(f x y)"), parse_pattern("(g y)")];
1891        let fq = flatten(&pats, &ops).unwrap();
1892        let rq = resolve(
1893            &fq,
1894            &ops,
1895            &sorts,
1896            &NiraModel,
1897            &crate::resolve::GlobalCtx::<_, ()>::new(),
1898        )
1899        .unwrap();
1900        let stub = StubSampler {
1901            lens: std::collections::HashMap::new(),
1902            drawn: std::cell::RefCell::new(Vec::new()),
1903        };
1904        assert_eq!(sampled_selectivity(), None, "the flag defaults to off");
1905        let plan: QueryPlan<OpId, u32, NiraLitVal> =
1906            schedule_with_stats_sampled(&rq, &IndexStats::new(), &stub);
1907        assert_eq!(
1908            plan.steps,
1909            schedule_with_stats::<_, _, _, u32>(&rq, &IndexStats::new()).steps
1910        );
1911        assert!(stub.drawn.into_inner().is_empty());
1912    }
1913
1914    /// End-to-end: with a bound element, the scheduler must be willing to drive
1915    /// from a high-cardinality variadic atom. `(g x)` binds x cheaply; the
1916    /// `add` atom has 100× g's cardinality, but once x is bound its discounted
1917    /// cost lets `by_contains[x]` carry the join (lookups include ByContains).
1918    #[test]
1919    fn scheduler_drives_variadic_from_bound_element() {
1920        let (qp, vars) =
1921            do_plan_with_stats(&["(g x)", "(add x ..rest)"], &[("g", 10), ("add", 1000)]);
1922        let x = vars.find_var("x").unwrap();
1923        // The add-atom join must intersect by_contains on the bound element x.
1924        let has_by_contains = qp.steps.iter().any(|s| match s {
1925            Step::Join { lookups, .. } => lookups.iter().any(
1926                |l| matches!(l, IndexLookup::ByContains { child } if *child == PatVar::Local(x)),
1927            ),
1928            _ => false,
1929        });
1930        assert!(
1931            has_by_contains,
1932            "variadic atom with a bound element should drive via ByContains: {:?}",
1933            qp.steps
1934        );
1935    }
1936}