1use 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#[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#[derive(Clone, Debug, PartialEq, Eq)]
42pub enum Step<O, I, V> {
43 Join {
44 target: VarId,
45 lookups: Vec<IndexLookup<O, I>>,
46 atom_id: usize,
51 },
52 ExtractChild {
53 target: VarId,
54 parent: VarId,
55 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 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 CheckLit {
111 node: VarId,
112 value: V,
113 },
114 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
127pub struct IndexStats<O: Eq + Hash> {
132 pub op_card: std::collections::HashMap<O, usize>,
136 pub fanouts: crate::index::FanOuts<O>,
140 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
179fn 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
211fn 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
223fn 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#[derive(Clone, Copy, PartialEq, Eq, Debug)]
253pub enum KeySite {
254 Node,
256 Child(usize),
258 Element,
262}
263
264#[derive(Clone, Copy, PartialEq, Eq, Debug)]
266pub enum ProbePath {
267 ChildPos(usize),
269 Contains,
271}
272
273#[derive(Clone, Copy, Debug, PartialEq)]
275pub struct SamplerConfig {
276 pub k: usize,
278 pub bootstrap: usize,
280 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 static SAMPLED_SELECTIVITY: Cell<Option<SamplerConfig>> = const { Cell::new(None) };
304}
305
306pub fn set_sampled_selectivity(cfg: Option<SamplerConfig>) {
316 SAMPLED_SELECTIVITY.with(|c| c.set(cfg));
317}
318
319pub fn sampled_selectivity() -> Option<SamplerConfig> {
321 SAMPLED_SELECTIVITY.with(|c| c.get())
322}
323
324thread_local! {
325 static SAMPLE_TALLY: Cell<(u64, u64)> = const { Cell::new((0, 0)) };
328}
329
330pub fn sample_tally() -> (u64, u64) {
339 SAMPLE_TALLY.with(|c| c.get())
340}
341
342pub 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
354pub trait CrossSampler<O> {
362 fn driver_sample(&self, atom_id: usize, op: O, k: usize, out: &mut Vec<usize>);
370
371 fn key_classes(&self, node: usize, site: KeySite, out: &mut Vec<usize>);
375
376 fn probe_len(&self, class: usize, path: ProbePath, op: O) -> usize;
379}
380
381type SampleKey = (usize, KeySite, usize, ProbePath);
384
385struct 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 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 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 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 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 fn bootstrap_ok(&mut self, mean: f64) -> bool {
507 if mean <= 0.0 {
508 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
535fn 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
544type Emitters = Vec<Option<(usize, KeySite)>>;
546
547fn 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 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 RAtom::EqGlobal(..) | RAtom::Pred { .. } => {}
617 }
618 }
619}
620
621fn emitter_op<O: Copy, S, V>(atom: &RAtom<O, S, V>) -> Option<O> {
625 crate::saturate::atom_op(atom)
626}
627
628struct 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 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
656fn 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
726fn 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#[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
776pub 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 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 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
856fn 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
863fn 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
973pub(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 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 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
1219pub(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 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 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 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 #[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 assert!(
1474 plan.steps[pred + 1..]
1475 .iter()
1476 .any(|s| matches!(s, Step::Join { .. }))
1477 );
1478 }
1479
1480 #[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 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 #[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 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 #[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 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 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 #[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 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 let bound_none = [false, false];
1771 assert_eq!(cost_of(&bound_none), 1000.0);
1772
1773 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 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 #[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 #[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 #[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 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}