egglog_core_relations/free_join/
plan.rs

1//! This module defines query optimization for egglog. The main entry point is `plan_query`, which takes a `Query` and produces a `Plan`.
2//!
3//! At a high level, the query planner has two phases: **(hyper)tree decomposition** and **join planning for each bag**.
4//! Both phases are very subtle, and heuristics are heavily used for good performance.
5//!
6//! # (Hyper)tree Decomposition
7//!
8//! A conjunctive query can be viewed as a hypergraph where variables are vertices and atoms (relations) are hyperedges.
9//! The idea of tree decomposition is to break this hypergraph into a tree of overlapping subqueries called *bags*,
10//! each of which is cheaper to evaluate independently. This is the classical idea behind tree decomposition and the
11//! Yannakakis algorithm.
12//!
13//! The decomposition proceeds via *variable elimination*: we iteratively pick a variable `v` and eliminate the neighborhood
14//! `N(v)` (which also includes `v`) from the hypergraph, and add back a hyperedge consisting of `N(v) - {v}`, until
15//! there are no variables left. Each elimination step gives us a bag. A min-fill heuristic
16//! (`next_var_to_eliminate`) guides the order of elimination to keep bags small. After all variables are eliminated,
17//! redundant bags are pruned: bags subsumed by another (all their variables are covered) are merged, and "ears"
18//! are merged into their parent.
19//!
20//! We then topologically sort the bags and decide which variables are "message variables" and which are private to the bag.
21//! The materialized result of each bag has its output keyed on the *message variables* it shares with
22//! its parent, and the parent uses that materialization to prune its own search space.
23//!
24//! When the query hypergraph is a single connected component with no beneficial decomposition, the planner falls back to
25//! a `SinglePlan` with no materialization steps.
26//!
27//! # Join Planning for a Single Bag
28//!
29//! Once each bag (subquery) is isolated, the planner generates a sequence of `JoinStage` instructions that enumerate
30//! all satisfying tuples for that bag. Two heuristics are supported:
31//!
32//! - **Generic Join** (`PlanStrategy::Gj`): The classic worst-case optimal join algorithm. Each stage picks one variable
33//!   and intersects the columns of atoms that correspond to this variable (`JoinStage::Intersect`).
34//!
35//! - **Free Join** (`PlanStrategy::PureSize` / `PlanStrategy::MinCover`): From Remy's paper. The planning algorithm
36//!   does the following: Each stage it selects a *cover* — a (sub)atom whose columns span the variables being bound in that step — and
37//!   uses it to probe all other atoms that share those variables (`JoinStage::FusedIntersect`). When the cover is an
38//!   entire atom and there is only one relation to probe, this degenerates to a hash join; when covers are single-column
39//!   scans it ~ recovers generic join*.
40//!
41//!   *: although this is not worst-case optimal because it does not necessarily picks the smallest side to scan.
42//!
43//! Both strategies produce a flat list of `JoinStage` instructions that are fused where possible (`JoinStage::fuse`) to
44//! reduce the number of passes over the data. A `JoinHeader` is prepended to each plan to apply constant constraints and
45//! pre-filter the driving relation before the main join loop begins.
46//!
47use std::{
48    collections::BTreeMap,
49    iter, mem,
50    sync::{Arc, OnceLock},
51};
52
53use crate::{
54    TableId,
55    free_join::{ColUniqueness, ColumnCardEst, ProcessedConstraints},
56    numeric_id::{DenseIdMap, NumericId},
57    query::{FunDeps, SymbolMap},
58};
59use egglog_numeric_id::define_id;
60use fixedbitset::FixedBitSet;
61
62use super::packed_cache::AccessFamilies;
63use smallvec::{SmallVec, smallvec};
64
65use crate::{
66    common::{HashMap, HashSet, IndexSet},
67    offsets::{OffsetRange, Subset, SubsetRef},
68    pool::Pooled,
69    query::{Atom, Query, VarColumnMap},
70    table_spec::Constraint,
71};
72
73use super::{ActionId, AtomId, ColumnId, ColumnIds, SubAtom, VarInfo, Variable};
74
75#[derive(Clone, Debug, PartialEq, Eq)]
76pub(crate) struct ScanSpec {
77    pub to_index: SubAtom,
78    // Only yield rows where the given constraints match.
79    pub constraints: Vec<Constraint>,
80}
81
82#[derive(Clone, Debug, PartialEq, Eq)]
83pub(crate) struct SingleScanSpec {
84    pub atom: AtomId,
85    pub column: ColumnId,
86    pub cs: Vec<Constraint>,
87}
88
89define_id!(pub(crate) MatId, u32, "An identifier for materialization within a decomposed plan.");
90
91#[derive(Clone, Debug, PartialEq, Eq)]
92pub(crate) enum MatScanMode {
93    Full,
94    KeyOnly,
95    Value(SmallVec<[Variable; 16]>),
96    Lookup(SmallVec<[Variable; 16]>),
97}
98
99/// Immutable row storage shared by processed constraints and their headers.
100/// Dense timestamp ranges stay inline; sparse offsets are owned independently
101/// of the table indexes that produced them.
102#[derive(Debug, Clone)]
103pub(crate) enum SharedHeaderSubset {
104    Dense(OffsetRange),
105    Sparse(Arc<Subset>),
106}
107
108impl From<Subset> for SharedHeaderSubset {
109    fn from(subset: Subset) -> Self {
110        match subset {
111            Subset::Dense(range) => Self::Dense(range),
112            subset @ Subset::Sparse(_) => Self::Sparse(Arc::new(subset)),
113        }
114    }
115}
116
117impl SharedHeaderSubset {
118    pub(crate) fn as_ref(&self) -> SubsetRef<'_> {
119        match self {
120            Self::Dense(range) => SubsetRef::Dense(*range),
121            Self::Sparse(subset) => subset.as_ref().as_ref(),
122        }
123    }
124
125    pub(crate) fn size(&self) -> usize {
126        self.as_ref().size()
127    }
128
129    pub(crate) fn is_empty(&self) -> bool {
130        self.size() == 0
131    }
132}
133
134/// Join headers evaluate constraints on a single atom; they prune the search space before the rest
135/// of the join plan is executed.
136pub(crate) struct JoinHeader {
137    pub atom: AtomId,
138    /// Fast constraints used to refresh cached plans and identify reusable headers.
139    pub constraints: Pooled<Vec<Constraint>>,
140    /// A pre-computed table subset that we can use to filter the table,
141    /// given these constraints.
142    ///
143    /// Why use the constraints at all? Because we want to use them to
144    /// discover common plan nodes from different queries (subsets can be
145    /// large).
146    pub subset: SharedHeaderSubset,
147}
148
149impl std::fmt::Debug for JoinHeader {
150    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
151        f.debug_struct("JoinHeader")
152            .field("atom", &self.atom)
153            .field("constraints", &self.constraints)
154            .field(
155                "subset",
156                &format_args!("Subset(size={})", self.subset.size()),
157            )
158            .finish()
159    }
160}
161
162impl Clone for JoinHeader {
163    fn clone(&self) -> Self {
164        JoinHeader {
165            atom: self.atom,
166            constraints: Pooled::cloned(&self.constraints),
167            subset: self.subset.clone(),
168        }
169    }
170}
171
172#[derive(Debug, Clone)]
173pub(crate) enum JoinStage {
174    /// `Intersect` takes a variable and intersects a set of atoms
175    /// on that variable.
176    /// This corresponds to the classic generic join algorithm.
177    Intersect {
178        var: Variable,
179        scans: SmallVec<[SingleScanSpec; 3]>,
180    },
181    /// `FusedIntersect` takes a "cover" (sub)atom and use it to probe other (sub)atoms.
182    /// This corresponds to the free join algorithm, or when to_intersect.len() == 1 and cover is
183    /// the entire atom, a hash join.
184    FusedIntersect {
185        cover: ScanSpec,
186        bind: SmallVec<[(ColumnId, Variable); 2]>,
187        // to_intersect.1 is the index into the cover atom.
188        to_intersect: Vec<(ScanSpec, ColumnIds)>,
189    },
190    FusedIntersectMat {
191        cover: MatId,
192        mode: MatScanMode,
193        bind: SmallVec<[(ColumnId, Variable); 2]>,
194        to_intersect: Vec<(ScanSpec, ColumnIds)>,
195    },
196}
197
198/// Merge every `FusedIntersect { to_intersect: [] }` into the first earlier such stage on the
199/// same cover atom, so each atom contributes at most one single-scan stage. Same-atom no-
200/// `to_intersect` covers can always be merged: their projections share an atom and any
201/// per-atom constraints are produced exactly once by `take_atom_constraints_if_new`.
202fn fuse_single_scans(stages: &mut Vec<JoinStage>) {
203    let mut i = 0;
204    while i < stages.len() {
205        let cur_atom = match &stages[i] {
206            JoinStage::FusedIntersect {
207                cover,
208                to_intersect,
209                ..
210            } if to_intersect.is_empty() => cover.to_index.atom,
211            _ => {
212                i += 1;
213                continue;
214            }
215        };
216        let target = (0..i).find(|&j| {
217            matches!(
218                &stages[j],
219                JoinStage::FusedIntersect { cover, to_intersect, .. }
220                    if to_intersect.is_empty() && cover.to_index.atom == cur_atom
221            )
222        });
223        let Some(j) = target else {
224            i += 1;
225            continue;
226        };
227        let JoinStage::FusedIntersect {
228            cover: cover_i,
229            bind: bind_i,
230            ..
231        } = stages.remove(i)
232        else {
233            unreachable!("checked above")
234        };
235        let JoinStage::FusedIntersect {
236            cover: cover_j,
237            bind: bind_j,
238            ..
239        } = &mut stages[j]
240        else {
241            unreachable!("checked above")
242        };
243        cover_j.to_index.vars.extend(cover_i.to_index.vars);
244        cover_j.constraints.extend(cover_i.constraints);
245        bind_j.extend(bind_i);
246        // Don't advance `i`: stages.remove shifts later entries down by one.
247    }
248}
249
250#[derive(Debug, Clone)]
251pub(crate) enum Plan {
252    SinglePlan(SinglePlan),
253    DecomposedPlan(DecomposedPlan),
254}
255impl Plan {
256    pub fn actions(&self) -> ActionId {
257        match self {
258            Plan::SinglePlan(p) => p.actions,
259            Plan::DecomposedPlan(p) => p.actions,
260        }
261    }
262
263    pub fn atoms(&self) -> Arc<DenseIdMap<AtomId, Atom>> {
264        match self {
265            Plan::SinglePlan(p) => p.atoms.clone(),
266            Plan::DecomposedPlan(p) => p.atoms.clone(),
267        }
268    }
269
270    pub(crate) fn to_report(&self, _symbol_map: &SymbolMap) -> egglog_reports::Plan {
271        match self {
272            Plan::SinglePlan(p) => p.to_report(_symbol_map),
273            Plan::DecomposedPlan(_) => {
274                todo!()
275            }
276        }
277    }
278
279    pub(crate) fn header(&self) -> &[JoinHeader] {
280        match self {
281            Plan::SinglePlan(p) => &p.header,
282            Plan::DecomposedPlan(p) => &p.header,
283        }
284    }
285
286    /// Visit every stage block of the plan.
287    pub(crate) fn for_each_stages_mut(&mut self, mut f: impl FnMut(&mut JoinStages)) {
288        match self {
289            Plan::SinglePlan(p) => f(&mut p.stages),
290            Plan::DecomposedPlan(p) => {
291                for (stages, _) in &mut p.stages.blocks {
292                    f(stages);
293                }
294                f(&mut p.result_block);
295            }
296        }
297    }
298}
299
300#[derive(Debug, Clone)]
301pub(crate) struct SinglePlan {
302    pub atoms: Arc<DenseIdMap<AtomId, Atom>>,
303    pub header: Vec<JoinHeader>,
304    pub stages: JoinStages,
305    pub actions: ActionId,
306}
307
308/// Instructions and immutable index analysis shared by cached-plan clones.
309/// Seminaive variants change their headers, not this program.
310#[derive(Debug, Clone)]
311pub(crate) struct JoinStages(Arc<JoinStageData>);
312
313#[derive(Debug)]
314pub(crate) struct JoinStageData {
315    pub instrs: Vec<JoinStage>,
316    /// Successor families in `for_each_indexed_access` order, assigned before
317    /// the plan is shared. They remain fixed across executions.
318    pub families: Box<[AccessFamilies]>,
319    /// Analyze only blocks that execute, then reuse their immutable layout.
320    /// Catalog handles and arena addresses belong to each execution instead.
321    pub(super) prepared_layout: OnceLock<Option<Box<super::prepared_index::PreparedJoinLayout>>>,
322}
323
324impl std::ops::Deref for JoinStages {
325    type Target = JoinStageData;
326    fn deref(&self) -> &Self::Target {
327        &self.0
328    }
329}
330
331impl JoinStages {
332    fn into_instrs(self) -> Vec<JoinStage> {
333        match Arc::try_unwrap(self.0) {
334            Ok(data) => data.instrs,
335            Err(shared) => shared.instrs.clone(),
336        }
337    }
338
339    pub(crate) fn new(instrs: Vec<JoinStage>) -> Self {
340        Self(Arc::new(JoinStageData {
341            instrs,
342            families: Box::new([]),
343            prepared_layout: OnceLock::new(),
344        }))
345    }
346
347    pub(super) fn set_families(&mut self, families: Box<[AccessFamilies]>) {
348        let data =
349            Arc::get_mut(&mut self.0).expect("families are assigned before a plan is shared");
350        assert!(data.prepared_layout.get().is_none());
351        data.families = families;
352    }
353
354    /// Visit every indexed access as `(atom, columns, constraints)`, in the
355    /// order prepared index slots are assigned. Cover scans are not indexed.
356    pub(crate) fn for_each_indexed_access(
357        &self,
358        mut f: impl FnMut(AtomId, &[ColumnId], &[Constraint]),
359    ) {
360        for stage in self.instrs.iter() {
361            match stage {
362                JoinStage::Intersect { scans, .. } => {
363                    for scan in scans {
364                        f(scan.atom, std::slice::from_ref(&scan.column), &scan.cs);
365                    }
366                }
367                JoinStage::FusedIntersect { to_intersect, .. }
368                | JoinStage::FusedIntersectMat { to_intersect, .. } => {
369                    for (scan, _) in to_intersect {
370                        f(scan.to_index.atom, &scan.to_index.vars, &scan.constraints);
371                    }
372                }
373            }
374        }
375    }
376}
377
378/// Specification of the materialization of the intermediate results, as required by tree decomposition.
379/// A materialization has two parts. The message variables are variables that are passed to and joined with later stages,
380/// and the value/private variables are variables that only occur in the current (and maybe previous) bags.
381///
382/// A materialization thus looks like a map from values of the message variables to sets of values of the private variables,
383/// and when we evaluate other bags, only the keys (message variables) are looked up or enumerated. This is because
384/// the private variables are not relevant to the evaluation of other bags. A key idea of tree decomposition is to separate
385/// independent parts of a query and make sure they are evaluated independently.
386#[derive(Debug, Clone)]
387pub(crate) struct MatSpec {
388    // Variables that are used by later stages
389    pub msg_vars: SmallVec<[Variable; 16]>,
390    // Variables that are not used by later stages.
391    pub val_vars: SmallVec<[Variable; 16]>,
392}
393
394#[derive(Debug, Clone)]
395pub(crate) struct JoinStageBlocks {
396    // each block is a list of instructions and how to yield
397    pub blocks: Vec<(JoinStages, MatSpec)>,
398}
399
400#[derive(Debug, Clone)]
401pub(crate) struct DecomposedPlan {
402    pub atoms: Arc<DenseIdMap<AtomId, Atom>>,
403    pub header: Vec<JoinHeader>,
404    pub stages: JoinStageBlocks,
405    pub result_block: JoinStages,
406    pub actions: ActionId,
407}
408
409impl SinglePlan {
410    pub(crate) fn to_report(&self, symbol_map: &SymbolMap) -> egglog_reports::Plan {
411        use egglog_reports::{
412            Plan as ReportPlan, Scan as ReportScan, SingleScan as ReportSingleScan,
413            Stage as ReportStage,
414        };
415        const INTERNAL_PREFIX: &str = "@";
416        let get_var = |var: Variable| {
417            symbol_map
418                .vars
419                .get(&var)
420                .map(|s| s.to_string())
421                .unwrap_or_else(|| format!("{INTERNAL_PREFIX}x{var:?}"))
422        };
423        let get_atom = |atom: AtomId| {
424            symbol_map
425                .atoms
426                .get(&atom)
427                .map(|s| s.to_string())
428                .unwrap_or_else(|| format!("{INTERNAL_PREFIX}R{atom:?}"))
429        };
430        let mut stages = Vec::new();
431        for (i, stage) in self.stages.instrs.iter().enumerate() {
432            let report_stage = match stage {
433                JoinStage::Intersect { var, scans } => {
434                    let var_name = get_var(*var);
435                    let report_scans = scans
436                        .iter()
437                        .map(|scan| {
438                            let atom_name = get_atom(scan.atom);
439                            ReportSingleScan(
440                                atom_name,
441                                (var_name.clone(), scan.column.index() as i64),
442                            )
443                        })
444                        .collect();
445                    ReportStage::Intersect {
446                        scans: report_scans,
447                    }
448                }
449                JoinStage::FusedIntersect {
450                    cover,
451                    bind: _,
452                    to_intersect,
453                } => {
454                    let cover_atom_name = get_atom(cover.to_index.atom);
455                    let cover_cols: Vec<(String, i64)> = cover
456                        .to_index
457                        .vars
458                        .iter()
459                        .map(|col| {
460                            let var_name =
461                                get_var(self.atoms[cover.to_index.atom].get_var(*col).unwrap());
462                            (var_name, col.index() as i64)
463                        })
464                        .collect();
465                    let report_cover = ReportScan(cover_atom_name, cover_cols);
466                    let report_to_intersect = to_intersect
467                        .iter()
468                        .map(|(scan, key_spec)| {
469                            let atom_name = get_atom(scan.to_index.atom);
470                            let cols: Vec<(String, i64)> = key_spec
471                                .iter()
472                                .map(|col| {
473                                    let var_name = get_var(
474                                        self.atoms[scan.to_index.atom].get_var(*col).unwrap(),
475                                    );
476                                    (var_name, col.index() as i64)
477                                })
478                                .collect();
479                            ReportScan(atom_name, cols)
480                        })
481                        .collect();
482                    ReportStage::FusedIntersect {
483                        cover: report_cover,
484                        to_intersect: report_to_intersect,
485                    }
486                }
487                JoinStage::FusedIntersectMat {
488                    cover: _,
489                    mode: _,
490                    bind: _,
491                    to_intersect: _,
492                } => {
493                    todo!("materialization")
494                }
495            };
496            let next = if i == self.stages.instrs.len() - 1 {
497                vec![]
498            } else {
499                vec![i + 1]
500            };
501            stages.push((report_stage, None, next));
502        }
503        ReportPlan { stages }
504    }
505}
506
507/// The algorithm used to produce a join plan.
508#[derive(Default, Copy, Clone)]
509pub enum PlanStrategy {
510    /// Free Join: Iteratively pick the smallest atom as the cover for the next
511    /// stage, until all subatoms have been visited.
512    PureSize,
513
514    /// Free Join: Pick an approximate minimal set of covers, then order those
515    /// covers in increasing order of size.
516    ///
517    /// This is similar to PureSize but we first limit the potential atoms that
518    /// can act as covers so as to minimize the total number of stages in the
519    /// plan. This is only an approximate minimum: the problem of finding the
520    /// exact minimum ("set cover") is NP-hard.
521    MinCover,
522
523    /// Generate a plan for the classic Generic Join algorithm, constraining a
524    /// single variable per stage.
525    #[default]
526    Gj,
527}
528
529/// Pick the next variable to eliminate and computes its neighborhood.
530///
531/// Each time, we pick a variable that has the least number of occurrences and find its neighborhood* (i.e.,
532/// the set of variables that share an atom with it). We pick the neighborhood based on the "min-fill" heuristic,
533/// which tries to eliminate neighborhood that would introduce the least number of new hyperedges.
534/// A hyperedge is introduced during variable elimination if two variables that don't share an atom before are in the same neighborhood.
535///
536/// *: We find the closure of the neighborhood under functional dependencies, since these variables are "for free".
537fn next_var_to_eliminate(
538    vars: &DenseIdMap<Variable, VarInfo>,
539    atoms: &DenseIdMap<AtomId, Atom>,
540    fun_deps: &FunDeps,
541    col_est: &ColumnCardEst<'_>,
542) -> Option<IndexSet<Variable>> {
543    let (_var, subquery_vars) = vars
544        .iter()
545        .map(|(var, vinfo)| {
546            let subquery_vars = atoms
547                .iter()
548                // every atom that contains this variable
549                .filter(|(_, atom)| atom.get_col(var).is_some())
550                // every variable of those atoms
551                .flat_map(|(_, atom)| atom.vars());
552
553            // Optimization: use functional dependencies to find all variables inferred by the
554            // current neightborhood.
555            // let subquery_vars = fun_deps.closure(subquery_vars);
556            let subquery_vars: DenseIdMap<_, ()> = subquery_vars.map(|v| (v, ())).collect();
557
558            let occ = atoms
559                .iter()
560                .filter(|(_, atom)| atom.vars().any(|v| subquery_vars.contains_key(v)))
561                .count();
562            let size_estimation = vinfo
563                .occurrences
564                .iter()
565                .filter_map(|occ| {
566                    let atom = &atoms[occ.atom];
567                    let table = atom.table;
568                    if table.is_dummy() {
569                        return None;
570                    }
571                    let col = atom.get_col(var).unwrap();
572                    // TODO: plan header before query decomposition so we know the exact
573                    // subset we are handling
574                    Some(col_est.col_uniqueness(table, col))
575                })
576                .fold(ColUniqueness::default(), |a, b| a.join(&b));
577            ((occ, size_estimation), var, subquery_vars)
578            // (occ, var, subquery_vars)
579        })
580        .min_by_key(|a| a.0)
581        .map(|a| (a.1, a.2))?;
582    Some(IndexSet::from_iter(
583        fun_deps
584            .closure(subquery_vars.iter().map(|(var, _)| var))
585            .into_iter()
586            .map(|(var, _)| var),
587    ))
588}
589
590/// It updates the hypergraph with the given bag of variables by:
591/// 1. Remove atoms that only contain variables in the bag and remove those atoms from variable's occurrences,
592/// 2. Add a covering hyperedge that contains every non-private variable.
593fn update_hypergraph(
594    subquery_vars: &IndexSet<Variable>,
595    vars: &mut DenseIdMap<Variable, VarInfo>,
596    atoms: &mut DenseIdMap<AtomId, Atom>,
597) {
598    // Build the covering hyperedge before we remove from the hypergraph
599
600    // Find variables that occur not just in the subquery
601    let covering_vars: Vec<_> = subquery_vars
602        .iter()
603        .copied()
604        .filter(|&var| {
605            vars.contains_key(var)
606                && vars[var].occurrences.iter().any(|occ| {
607                    atoms[occ.atom]
608                        .vars()
609                        .any(|ov| !subquery_vars.contains(&ov))
610                })
611        })
612        .collect();
613
614    // Remove atoms from the hypergraph
615    let mut removed = Vec::new();
616    atoms.retain(|atom_id, atom| {
617        if atom.vars().all(|var| subquery_vars.contains(&var)) {
618            removed.push(atom_id);
619            false
620        } else {
621            true
622        }
623    });
624
625    // Update occurrences to reflect removed atoms
626    for &subq_var in subquery_vars.iter() {
627        if vars.contains_key(subq_var) {
628            vars[subq_var]
629                .occurrences
630                .retain(|occ| !removed.contains(&occ.atom));
631
632            if vars[subq_var].occurrences.is_empty() {
633                vars.unwrap_val(subq_var);
634            }
635        }
636    }
637
638    // Add the covering atom to the hypergraph
639    let mut var_columns = VarColumnMap::default();
640    for (ix, var) in covering_vars.iter().enumerate() {
641        var_columns.insert(*var, ColumnId::from_usize(ix));
642    }
643    let fake_atom_id = atoms.push(Atom {
644        var_columns,
645        constraints: ProcessedConstraints::dummy(),
646        table: TableId::dummy(),
647    });
648
649    // Update variable occurrences to include the covering atom
650    for (i, &covering_var) in covering_vars.iter().enumerate() {
651        vars[covering_var].occurrences.push(SubAtom {
652            atom: fake_atom_id,
653            vars: smallvec![ColumnId::from_usize(i)],
654        });
655    }
656}
657
658/// This function does tree decomposition. At a high level, it takes a bag (equivalently, a `PlanningContext`, a subquery, a hypergraph,
659/// or a set of variables + atoms), and returns a list of bags that forms a tree decomposition.
660///
661/// Recall that a bag is equivalent to a hypergraph, where vertices = variables and hyperedges = atoms.
662///
663/// The algorithm is based on the classical variable elimination, where it iteratively removes neighborhoods until no variables are left.
664/// More specifically, it iteratively
665///
666/// 1. Select a variable `v` and its neighborhood `N(v)`, based on the "min-fill" heuristic. (`next_var_to_eliminate`)
667/// 2. Remove the neighborhood from the working hypergraph. (`update_hypergraph`)
668/// 3. Add a covering atom that contains variables `N(v) - {v}` to the working hypergraph. (`update_hypergraph`)
669/// 4. Step 1-3 gives us a set of variables `N(v)`. We need to construct a subquery from it. This step is a bit subtle.
670///
671///    For example, consider the rectangle query `R(x, y), S(y, z), T(z, w), U(w, x)`. Let's say we pick variable `x` to eliminate.
672///    The neighborhood `N(x)` of `x` is {x, y, z}. A naive approach is to subquery would be `R(x, y), S(y, z)`, but this query can have size quadratic,
673///    even when the final output size is small. The issue here is `x` and `z` are not fully constrained in this subquery.
674///    Another approach is to include every atom that contains variables in `N(x)`, but this gives us the entire query as the subquery for that rectangle query,
675///    which is also not ideal because the rectangle query should be broken into two bags.
676///
677///    The solution is to include every atom that contains variables in `N(x)`, but only keep the variables in `N(x)` in those atoms. For the rectangle example,
678///    this would be `R(x, y), S(y, z), T(z, -), U(-, x)`, where `-` means we don't expand this variable during evaluation. As a result, the produced PlanningContext
679///    may have atoms whose variables are not in `PlanningContext::vars`. The query planner for a single bag handles this correctly.
680///
681/// Now we have collected a list of bags, but they are very redundant. (Remember the variable elimination loop is run |vars| steps, because each iteration eliminates
682/// only one variable.) We need to prune these bags. See the comments in the code for details.
683///
684/// Another invariant we maintain is higher-indexed bags are heavier (closer to the root of the tree decomposition), so they will be evaluated later and constrained
685/// by evaluation of earlier bags.
686fn decompose_into_bags<'a>(original_ctx: &PlanningContext<'a>) -> Vec<PlanningContext<'a>> {
687    let mut atoms = original_ctx.atoms.clone();
688    let mut vars = original_ctx.vars.clone();
689
690    // Prune variables with no occurrences
691    for (var, vinfo) in original_ctx.vars.iter() {
692        if vinfo.occurrences.is_empty() {
693            vars.take(var).unwrap();
694        }
695    }
696
697    let mut bags = Vec::new();
698
699    // Variable elimination loop
700    while let Some(subquery_vars) =
701        next_var_to_eliminate(&vars, &atoms, &original_ctx.fun_deps, &original_ctx.col_est)
702    {
703        // Create a fake covering atom to bridge back to the main query
704        // Remove hyperedges that only contain subquery variables.
705        update_hypergraph(&subquery_vars, &mut vars, &mut atoms);
706
707        // Collect atoms that only contain subquery variables.
708        let subquery_atoms: DenseIdMap<AtomId, Atom> = original_ctx
709            .atoms
710            .iter()
711            .filter(|(_, atom)| atom.vars().any(|var| subquery_vars.contains(&var)))
712            .map(|(atom_id, atom)| (atom_id, atom.clone()))
713            .collect();
714
715        let subquery_var_map = DenseIdMap::from_iter(subquery_vars.iter().map(|var| {
716            let mut var_info = original_ctx.vars[*var].clone();
717            // NB: used_in_rhs is handled in [`plan_single_bag`]
718            var_info
719                .occurrences
720                .retain(|occ| subquery_atoms.contains_key(occ.atom));
721            (*var, var_info)
722        }));
723
724        bags.push(PlanningContext {
725            vars: subquery_var_map,
726            atoms: subquery_atoms,
727            fun_deps: original_ctx.fun_deps.clone(),
728            col_est: original_ctx.col_est.clone(),
729        });
730    }
731
732    assert!(
733        !atoms.iter().any(|(_, atom_info)| {
734            !atom_info.table.is_dummy() && !atom_info.var_columns.is_empty()
735        }),
736        "All atoms should be put into bags"
737    );
738
739    // Iteratively prune the query
740    let mut changed = true;
741    while changed {
742        changed = false;
743        // Pruning 1: Remove bags that are subsumed by others. A bag is subsumed by another bag if all of its variables are contained in the other bag,
744        // so the output of this bag must be a subset of the bigger bag.
745        let mut pruned_bags: Vec<PlanningContext> = Vec::with_capacity(bags.len());
746        for mut bag1 in bags.into_iter() {
747            pruned_bags.retain_mut(|bag2| {
748                let leq = bag1.is_subsumed_by(bag2);
749                let geq = bag2.is_subsumed_by(&bag1);
750                if leq || geq {
751                    bag1.merge_bag(bag2);
752                    changed = true;
753                    false
754                } else {
755                    true
756                }
757            });
758            pruned_bags.push(bag1);
759        }
760
761        // Pruning 2: Find "ears" and merge them with other bags. A bag is an ear if one of its atoms covers all of its variables, i.e., it only has one useful
762        // relation. We can safely remove an ear if it shares variables with only one bag - in this case, that bag is necessarily the parent in the tree decomposition.
763        //
764        // Why removing ears? Let's say an ear has the form R(x, y, z) with message variable {x}. The evaluation of its parent will already intersect on `x` with `R(x, y, z)`,
765        // so if `y` and `z` are expanded at the innermost loop of the evaluation, this does not incur any overhead. Versus if we keep this ear as a separate bag,
766        // we would need to first build a map x -> (y, z) only to enumerate each x to get the corresponding (y, z) values.
767        bags = pruned_bags;
768        let is_ear = |bag: &PlanningContext| {
769            bag.atoms.iter().any(|(_atom_id, atom)| {
770                let all_vars = original_ctx.fun_deps.closure(atom.vars());
771                bag.is_subsumed_by_vars(&all_vars)
772            })
773            // HACK: this weird condition says if there's exactly one atom whose variables are all wanted, then we can also treat it as an ear,
774            // because other atoms in the bag are likely added only to constrain the bag. This is approximately what a bag is, but not really.
775            // However, removing this condition makes some benchmark much worse...
776            || bag
777                .atoms
778                .iter()
779                .filter(|(_atom_id, atom)| bag.has_vars(atom.vars()))
780                .count()
781                == 1
782        };
783
784        let mut i = 0;
785        while i < bags.len() {
786            if !is_ear(&bags[i]) {
787                i += 1;
788                continue;
789            }
790
791            // Find the bag that shares the most variables with this ear bag, and merge the ear bag into it.
792            let parent = bags
793                .iter()
794                .enumerate()
795                .rev()
796                .filter(|(j, _)| *j != i)
797                .map(|(j, b)| (j, b.common_vars_with(&bags[i]).count()))
798                .collect::<Vec<_>>();
799
800            let j = parent.into_iter().max_by_key(|(_, count)| *count);
801            if j.is_none() || j.unwrap().1 == 0 {
802                i += 1;
803                continue;
804            }
805            let j = j.unwrap().0;
806
807            // Invariant: bigger-numbered bags are heavier and should stay at the root of the tree
808            if i < j {
809                let bag = bags.remove(i);
810                bags[j - 1].merge_bag(&bag);
811            } else {
812                let bag = bags.remove(j);
813                bags[i - 1].merge_bag(&bag);
814            }
815            changed = true;
816        }
817    }
818    bags
819}
820
821/// Topologically sorts bags based on variable dependencies, and merges bags so
822/// that the final result is a *chain*. This means `plan_single_bag` only ever
823/// needs a single prologue per bag and never an epilogue. This is because the
824/// epilogues do not participate in joins and are checked only after the main
825/// join loop, so they can easily lead to cartesian products.
826///
827/// At every DFS node we pick one child as the chain continuation. Every other reachable bag —
828/// siblings *and* their entire sub-trees — gets absorbed into the current chain node. The
829/// continuation is picked in a way that minimizes the maximum number of atoms in a bag, i.e.,
830/// the pathwidth.
831///
832/// The pathwidth of a path decomposition is the maximum bag size (minus one) over all bags,
833/// and the size of a bag is measured as the number of atoms in the bag.
834fn topologically_sort_bags(bags: Vec<PlanningContext>) -> Vec<PlanningContext> {
835    let mut all_children_list: Vec<Vec<usize>> = vec![vec![]; bags.len()];
836    // best_pathwidth[i] = the best pathwidth of the chain if we pick bag i
837    // to be the chain child.
838    let mut best_pathwidth = vec![usize::MAX; bags.len()];
839    let mut full = vec![HashSet::default(); bags.len()];
840    let mut choice = vec![usize::MAX; bags.len()];
841    for i in 0..bags.len() {
842        let mut full_i: HashSet<AtomId> =
843            bags[i].atoms.iter().map(|(atom_id, _)| atom_id).collect();
844        for child in all_children_list[i].iter() {
845            full_i.extend(full[*child].iter().copied());
846        }
847        full[i] = full_i;
848        best_pathwidth[i] = full[i].len();
849        for chain_child in all_children_list[i].iter() {
850            let mut chain_score: HashSet<_> =
851                bags[i].atoms.iter().map(|(atom_id, _)| atom_id).collect();
852            chain_score.extend(
853                all_children_list[*chain_child]
854                    .iter()
855                    .filter(|child| *child != chain_child)
856                    .flat_map(|child| full[*child].iter().copied()),
857            );
858            let s = chain_score.len().max(best_pathwidth[*chain_child]);
859            if s <= best_pathwidth[i] {
860                best_pathwidth[i] = s;
861                choice[i] = *chain_child;
862            }
863        }
864
865        // Find the parent of this bag, which must be the lowerest-numbered bag
866        // that shares the most variables with it.
867        let parent = bags
868            .iter()
869            .enumerate()
870            .skip(i + 1)
871            .map(|(j, b)| (j, b.common_vars_with(&bags[i]).count()))
872            .filter(|(_, count)| *count > 0)
873            .max_by_key(|(j, count)| (*count, -(*j as isize)));
874        if let Some((j, _count)) = parent {
875            all_children_list[j].push(i);
876        }
877    }
878
879    let mut bags_opt = bags.into_iter().map(Some).collect::<Vec<_>>();
880    let mut bags_topo = Vec::<PlanningContext>::with_capacity(bags_opt.len());
881    let mut visited = vec![false; bags_opt.len()];
882    // Stack entries: (bag_id, parent). `parent` is None for chain nodes (the bag is
883    // pushed to `bags_topo` as a new standalone entry) and Some(idx) for nodes being
884    // absorbed into `bags_topo[idx]`.
885    let mut stack: Vec<(usize, Option<usize>)> = Vec::new();
886
887    // Starting from the last, since early bags are more likely to be leaves and we don't
888    // want a leafy bag to be a root.
889    for i in (0..bags_opt.len()).rev() {
890        if visited[i] {
891            continue;
892        }
893        stack.push((i, None));
894        visited[i] = true;
895
896        while let Some((bag_id, parent)) = stack.pop() {
897            let bag = mem::take(&mut bags_opt[bag_id]).unwrap();
898
899            let this;
900            if let Some(parent) = parent {
901                bags_topo[parent].merge_bag(&bag);
902                this = parent;
903            } else {
904                this = bags_topo.len();
905            }
906
907            let all_children = &mut all_children_list[bag_id];
908
909            if parent.is_some() {
910                // This bag is being absorbed into `bags_topo[this]`. To keep the
911                // result a chain, every descendant of this bag is also absorbed —
912                // none of them get to spawn a new chain node.
913                for &i in all_children.iter() {
914                    visited[i] = true;
915                    stack.push((i, Some(this)));
916                }
917            } else {
918                // This bag is a chain node. The child that minimizes pathwidth continues the
919                // chain; the rest (and all their descendants, via the branch above)
920                // are absorbed into this chain node.
921                if !all_children.is_empty() {
922                    for &i in all_children[1..].iter() {
923                        if i == choice[bag_id] {
924                            continue;
925                        }
926                        visited[i] = true;
927                        stack.push((i, Some(this)));
928                    }
929                    visited[choice[bag_id]] = true;
930                    stack.push((choice[bag_id], None));
931                }
932            }
933
934            if parent.is_none() {
935                bags_topo.push(bag);
936            }
937        }
938    }
939
940    bags_topo.reverse();
941    bags_topo
942}
943
944/// Counts how many bags each variable appears in.
945///
946/// This is used to determine whether a variable should be passed as a message
947/// variable (if used in later bags) or a value variable (if only used in the current bag).
948fn count_variable_usage_per_bag(bags: &[PlanningContext]) -> DenseIdMap<Variable, usize> {
949    let mut n_used_in_bag = DenseIdMap::new();
950    for bag in bags {
951        for (var, _vinfo) in bag.vars.iter() {
952            if !n_used_in_bag.contains_key(var) {
953                n_used_in_bag.insert(var, 0);
954            }
955            n_used_in_bag[var] += 1;
956        }
957    }
958    n_used_in_bag
959}
960
961/// Plans the execution stages for a single bag.
962///
963/// This involves:
964/// - Dividing variables into message variables (passed to later stages) and value variables
965/// - Planning join stages within the bag
966/// - Adding prologue and epilogue instructions so that the bag is constrained by previous materializations.
967///
968/// This function also sets the `used_in_rhs` field for variables. A variable is not used in RHS during the planning
969/// of a bag if it's not used in later bags.
970fn plan_single_bag(
971    bag: &mut PlanningContext,
972    blocks: &[(JoinStages, MatSpec)],
973    // If this bag has been used to prune its parent
974    has_block_contributed: &mut [bool],
975    n_used_in_bag: &mut DenseIdMap<Variable, usize>,
976    strat: PlanStrategy,
977) -> (Vec<JoinHeader>, JoinStages, MatSpec) {
978    let mut msg_vars = smallvec![];
979    let mut val_vars = smallvec![];
980
981    // Classify variables as message or value variables
982    for (var, vinfo) in bag.vars.iter_mut() {
983        n_used_in_bag[var] -= 1;
984        if n_used_in_bag[var] > 0 {
985            // If this is a public variable, then we need to pass it on anyway
986            vinfo.used_in_rhs = true;
987            msg_vars.push(var);
988        } else {
989            // If this variable is not used in later and previous bag,
990            // and it is not used in the right hand side,
991            // this variable doesn't need to be expanded.
992            if !vinfo.used_in_rhs
993                && blocks.iter().all(|(_, spec)| !spec.msg_vars.contains(&var))
994                && n_used_in_bag[var] == 0
995            {
996                continue;
997            }
998            val_vars.push(var);
999            vinfo.used_in_rhs = true;
1000        }
1001    }
1002
1003    let mut stripped_bag = bag.clone();
1004
1005    // Add prologue and epilogue instructions to look up previous materialized bags
1006    // These are constraints from children blocks. If there's only one such block, it can be the header.
1007    // Otherwise, they have to be epilogue instructions doing filtering at the end, which is less efficient.
1008    let mut prologue = None;
1009    let mut epilogue = Vec::new();
1010    for (i, prev_block) in blocks.iter().enumerate().rev() {
1011        if prev_block.1.msg_vars.is_empty() {
1012            continue;
1013        }
1014        if !has_block_contributed[i]
1015            && prev_block
1016                .1
1017                .msg_vars
1018                .iter()
1019                .all(|var| bag.vars.contains_key(*var))
1020        {
1021            has_block_contributed[i] = true;
1022            if prologue.is_none() {
1023                let bind = prev_block
1024                    .1
1025                    .msg_vars
1026                    .iter()
1027                    .enumerate()
1028                    .map(|(j, var)| (ColumnId::from_usize(j), *var))
1029                    .collect();
1030                let mut to_intersect: Vec<(ScanSpec, ColumnIds)> = vec![];
1031                for (col, var) in prev_block.1.msg_vars.iter().enumerate() {
1032                    let vinfo = &bag.vars[*var];
1033                    for occ in vinfo.occurrences.iter() {
1034                        let isect = match to_intersect
1035                            .iter_mut()
1036                            .find(|(spec, _)| spec.to_index.atom == occ.atom)
1037                        {
1038                            Some(isect) => isect,
1039                            None => {
1040                                to_intersect.push((
1041                                    ScanSpec {
1042                                        to_index: SubAtom {
1043                                            atom: occ.atom,
1044                                            vars: smallvec![],
1045                                        },
1046                                        constraints: vec![],
1047                                    },
1048                                    smallvec![],
1049                                ));
1050                                to_intersect.last_mut().unwrap()
1051                            }
1052                        };
1053                        isect.0.to_index.vars.extend(occ.vars.iter().copied());
1054                        isect
1055                            .1
1056                            .extend(occ.vars.iter().map(|_| ColumnId::from_usize(col)));
1057                    }
1058                }
1059
1060                prologue = Some(JoinStage::FusedIntersectMat {
1061                    cover: MatId::from_usize(i),
1062                    mode: MatScanMode::KeyOnly,
1063                    bind,
1064                    to_intersect,
1065                });
1066
1067                stripped_bag
1068                    .vars
1069                    .retain(|var, _vinfo| !prev_block.1.msg_vars.contains(&var));
1070            } else {
1071                epilogue.push(JoinStage::FusedIntersectMat {
1072                    cover: MatId::from_usize(i),
1073                    mode: MatScanMode::Lookup(prev_block.1.msg_vars.clone()),
1074                    bind: smallvec![],
1075                    to_intersect: vec![],
1076                });
1077            }
1078        }
1079    }
1080
1081    let (header, mut instrs) = plan_stages(&stripped_bag, strat);
1082    instrs.splice(0..0, prologue);
1083    instrs.extend(epilogue);
1084
1085    let stages = JoinStages::new(instrs);
1086
1087    (header, stages, MatSpec { msg_vars, val_vars })
1088}
1089
1090/// Builds the final result block that collects results from all materialized bags.
1091///
1092/// This performs a bottom-up pass through the materialized bags, binding value
1093/// variables and gathering results. Each block is scanned at most once.
1094fn build_result_block(blocks: &[(JoinStages, MatSpec)]) -> JoinStages {
1095    let mut result_block = Vec::new();
1096    let mut pinned_vars = DenseIdMap::<Variable, ()>::new();
1097
1098    for (i, (_stages, mat_spec)) in blocks.iter().enumerate().rev() {
1099        let to_bind: SmallVec<[(ColumnId, Variable); 2]> = mat_spec
1100            .val_vars
1101            .iter()
1102            .copied()
1103            .enumerate()
1104            .filter(|(_, var)| !pinned_vars.contains_key(*var))
1105            .map(|(i, var)| (ColumnId::from_usize(i), var))
1106            .collect();
1107
1108        if to_bind.is_empty() {
1109            continue;
1110        }
1111
1112        for (_, var) in to_bind.iter() {
1113            pinned_vars.insert(*var, ());
1114        }
1115
1116        result_block.push(JoinStage::FusedIntersectMat {
1117            cover: MatId::from_usize(i),
1118            mode: if i == blocks.len() - 1 {
1119                MatScanMode::Full
1120            } else {
1121                MatScanMode::Value(mat_spec.msg_vars.clone())
1122            },
1123            bind: to_bind,
1124            to_intersect: vec![],
1125        });
1126    }
1127
1128    JoinStages::new(result_block)
1129}
1130
1131/// The last stage and the result block have the following structure:
1132///
1133/// for ...
1134///    yield [] -> x1, x2, ... as Mn
1135///
1136/// For x1, x2, ... in Mn:
1137///   ...
1138///
1139/// This can be fused into one loop
1140///
1141/// This is currently not used because somehow iterating the materialized RowBuffer is much faster than iterating the table
1142#[allow(unused)]
1143fn fuse_last_stage(
1144    mut blocks: Vec<(JoinStages, MatSpec)>,
1145    result_block: JoinStages,
1146) -> (Vec<(JoinStages, MatSpec)>, JoinStages) {
1147    if blocks.is_empty() {
1148        return (blocks, result_block);
1149    }
1150
1151    let last_block = blocks.pop().unwrap();
1152    assert!(last_block.1.msg_vars.is_empty());
1153    if !matches!(
1154        result_block.instrs[0],
1155        JoinStage::FusedIntersectMat {
1156            cover,
1157            mode: MatScanMode::Full,
1158            ..
1159        } if cover == MatId::from_usize(blocks.len()
1160    )) {
1161        // If the first stage of the result block does not scan the last materialization
1162        return (blocks, result_block);
1163    }
1164
1165    // Fuse the instructions
1166    let mut instrs = last_block.0.into_instrs();
1167    instrs.extend(result_block.instrs[1..].iter().cloned());
1168    (blocks, JoinStages::new(instrs))
1169}
1170
1171/// Eagerly lift materialization lookups up
1172///
1173/// For example, in the following, looking up of `r` can be lifted up before `z`
1174///
1175/// for x in R isec S:
1176///  R = R[x]; S = S[x]
1177///  for z in R:
1178///   if r in Mat[x]:
1179///     yield
1180fn loop_lifting(stages: JoinStages) -> JoinStages {
1181    let mut instrs = stages.into_instrs();
1182    for i in 1..instrs.len() {
1183        if let JoinStage::FusedIntersectMat {
1184            cover: _,
1185            mode: MatScanMode::Lookup(vars),
1186            bind,
1187            to_intersect,
1188        } = &instrs[i]
1189        {
1190            assert!(bind.is_empty() && to_intersect.is_empty());
1191            let vars = vars.clone();
1192            let mut j = i;
1193            while j > 0 {
1194                if matches!(
1195                    &instrs[j - 1], JoinStage::FusedIntersect { bind, .. } | JoinStage::FusedIntersectMat { bind, ..}
1196                        if bind.iter().all(|(_, var)| !vars.contains(var))
1197                ) || matches!(&instrs[j - 1], JoinStage::Intersect { var, .. } if !vars.contains(var))
1198                {
1199                    instrs.swap(j - 1, j);
1200                    j -= 1;
1201                } else {
1202                    break;
1203                }
1204            }
1205        }
1206    }
1207    JoinStages::new(instrs)
1208}
1209
1210/// This is the main entry point for query optimization using tree decomposition.
1211pub(crate) fn tree_decompose_and_plan(
1212    ctx: PlanningContext,
1213    strat: PlanStrategy,
1214    actions: ActionId,
1215    no_decomp: bool,
1216) -> Plan {
1217    macro_rules! fast_path {
1218        () => {{
1219            let (header, instrs) = plan_stages(&ctx, strat);
1220            let stages = JoinStages::new(instrs);
1221
1222            Plan::SinglePlan(SinglePlan {
1223                atoms: Arc::new(ctx.atoms),
1224                header,
1225                stages,
1226                actions,
1227            })
1228        }};
1229    }
1230    if no_decomp || ctx.atoms.len() <= 2 {
1231        return fast_path!();
1232    }
1233
1234    // Step 1: Decompose the query into tree-structured bags
1235    let bags = decompose_into_bags(&ctx);
1236    if bags.len() <= 1 {
1237        // Don't do Yannakakis if it's just one bag
1238        return fast_path!();
1239    }
1240
1241    // Step 2: Sort bags topologically and merge leafy bags with their parents
1242    let mut bags = topologically_sort_bags(bags);
1243
1244    if bags.len() <= 1 {
1245        return fast_path!();
1246    }
1247
1248    // Step 3: Count variable usage across bags. Used for deciding if a variable is public (i.e., message variables) or private.
1249    let mut n_used_in_bag = count_variable_usage_per_bag(&bags);
1250    let mut has_block_contributed = vec![false; bags.len()];
1251
1252    // Step 4: Plan each bag and create materialization blocks
1253    let mut blocks = Vec::new();
1254    let mut header = vec![];
1255    for bag in bags.iter_mut() {
1256        let (bag_header, stages, mat_spec) = plan_single_bag(
1257            bag,
1258            &blocks,
1259            &mut has_block_contributed,
1260            &mut n_used_in_bag,
1261            strat,
1262        );
1263        blocks.push((stages, mat_spec));
1264        header.extend(bag_header);
1265    }
1266
1267    // Step 5: Build the final result block
1268    let result_block = build_result_block(&blocks);
1269
1270    // Optimization the avoids the last materialization
1271    // let (blocks, result_block) = fuse_last_stage(blocks, result_block);
1272
1273    // Lifting variables
1274    let blocks = blocks
1275        .into_iter()
1276        .map(|(stages, mat_spec)| (loop_lifting(stages), mat_spec))
1277        .collect::<Vec<_>>();
1278    let result_block = loop_lifting(result_block);
1279
1280    Plan::DecomposedPlan(DecomposedPlan {
1281        atoms: Arc::new(ctx.atoms),
1282        header,
1283        stages: JoinStageBlocks { blocks },
1284        result_block,
1285        actions,
1286    })
1287}
1288
1289pub(crate) fn plan_query<'a>(query: Query, col_est: ColumnCardEst<'a>) -> Plan {
1290    let atoms = query.atoms;
1291    let ctx = PlanningContext {
1292        vars: query.var_info,
1293        atoms,
1294        fun_deps: Arc::new(query.fun_deps),
1295        col_est,
1296    };
1297    tree_decompose_and_plan(ctx, query.plan_strategy, query.action, query.no_decomp)
1298}
1299
1300/// StageInfo is an intermediate stage used to describe the ordering of
1301/// operations. One of these contains enough information to "expand" it to a
1302/// JoinStage, but it still contains variable information.
1303///
1304/// This separation makes it easier for us to iterate with different planning
1305/// algorithms while sharing the same "backend" that generates a concrete plan.
1306#[derive(Debug)]
1307struct StageInfo {
1308    cover: SubAtom,
1309    vars: SmallVec<[Variable; 1]>,
1310    filters: Vec<(
1311        SubAtom,   /* the subatom to index */
1312        ColumnIds, /* how to build a key for that index from the cover atom */
1313    )>,
1314}
1315
1316/// Immutable context for query planning containing references to query metadata.
1317#[derive(Debug, Clone)]
1318pub(crate) struct PlanningContext<'a> {
1319    vars: DenseIdMap<Variable, VarInfo>,
1320    atoms: DenseIdMap<AtomId, Atom>,
1321    fun_deps: Arc<FunDeps>,
1322    col_est: ColumnCardEst<'a>,
1323}
1324
1325impl<'a> PlanningContext<'a> {
1326    fn is_subsumed_by(&self, bag2: &PlanningContext<'a>) -> bool {
1327        self.is_subsumed_by_vars(&bag2.vars)
1328    }
1329
1330    fn is_subsumed_by_vars<I>(&self, bag2: &DenseIdMap<Variable, I>) -> bool {
1331        self.vars.iter().all(|(var, _)| bag2.contains_key(var))
1332    }
1333
1334    fn merge_bag(&mut self, bag2: &PlanningContext<'a>) {
1335        for (var, vinfo) in bag2.vars.iter() {
1336            if self.vars.contains_key(var) {
1337                for new_occ in vinfo.occurrences.iter().cloned() {
1338                    if !self.vars[var]
1339                        .occurrences
1340                        .iter()
1341                        .any(|occ| occ.atom == new_occ.atom)
1342                    {
1343                        self.vars[var].occurrences.push(new_occ);
1344                    }
1345                }
1346            } else {
1347                self.vars.insert(var, vinfo.clone());
1348            }
1349        }
1350        for (atom_id, atom) in bag2.atoms.iter() {
1351            // atoms don't need to be merged
1352            if !self.atoms.contains_key(atom_id) {
1353                self.atoms.insert(atom_id, atom.clone());
1354            }
1355        }
1356    }
1357
1358    fn common_vars_with<'b>(
1359        &'b self,
1360        other: &'b PlanningContext<'a>,
1361    ) -> impl Iterator<Item = Variable> + 'b {
1362        self.vars
1363            .iter()
1364            .filter(|(var, _)| other.vars.contains_key(*var))
1365            .map(|(var, _)| var)
1366    }
1367
1368    fn has_vars(&self, mut vars: impl Iterator<Item = Variable>) -> bool {
1369        vars.all(|var| self.vars.contains_key(var))
1370    }
1371}
1372
1373type VarSet = FixedBitSet;
1374type AtomSet = FixedBitSet;
1375
1376/// Mutable state tracked during query planning.
1377#[derive(Clone)]
1378pub(crate) struct PlanningState {
1379    used_vars: VarSet,
1380    constrained_atoms: AtomSet,
1381}
1382
1383impl PlanningState {
1384    fn new(n_vars: usize, n_atoms: usize) -> Self {
1385        Self {
1386            used_vars: VarSet::with_capacity(n_vars),
1387            constrained_atoms: AtomSet::with_capacity(n_atoms),
1388        }
1389    }
1390
1391    fn mark_var_used(&mut self, var: Variable) {
1392        self.used_vars.insert(var.index());
1393    }
1394
1395    fn is_var_used(&self, var: Variable) -> bool {
1396        self.used_vars.contains(var.index())
1397    }
1398
1399    fn mark_atom_constrained(&mut self, atom: AtomId) {
1400        self.constrained_atoms.insert(atom.index());
1401    }
1402
1403    fn is_atom_constrained(&self, atom: AtomId) -> bool {
1404        self.constrained_atoms.contains(atom.index())
1405    }
1406}
1407
1408/// Datastructure used to greedily solve the set cover problem for a given free
1409/// join plan.
1410struct BucketQueue<'a> {
1411    var_info: &'a DenseIdMap<Variable, VarInfo>,
1412    cover: VarSet,
1413    atom_info: DenseIdMap<AtomId, VarSet>,
1414    sizes: BTreeMap<usize, IndexSet<AtomId>>,
1415}
1416
1417impl<'a> BucketQueue<'a> {
1418    fn new(var_info: &'a DenseIdMap<Variable, VarInfo>, atoms: &DenseIdMap<AtomId, Atom>) -> Self {
1419        let cover = VarSet::with_capacity(var_info.n_ids());
1420        let mut atom_info = DenseIdMap::with_capacity(atoms.n_ids());
1421        let mut sizes = BTreeMap::<usize, IndexSet<AtomId>>::new();
1422        for (id, atom) in atoms.iter() {
1423            let mut bitset = VarSet::with_capacity(var_info.n_ids());
1424            for var in atom.vars() {
1425                bitset.insert(var.index());
1426            }
1427            sizes.entry(bitset.count_ones(..)).or_default().insert(id);
1428            atom_info.insert(id, bitset);
1429        }
1430        BucketQueue {
1431            var_info,
1432            cover,
1433            atom_info,
1434            sizes,
1435        }
1436    }
1437
1438    /// Return the atom with the largest number of uncovered variables. A
1439    /// variable is "covered" if a previous call to `pop_min` returned an atom
1440    /// referencing that variable.
1441    fn pop_min(&mut self) -> Option<AtomId> {
1442        // Pick an arbitrary atom from the smallest bucket.
1443        let (_, atoms) = self.sizes.iter_mut().next_back()?;
1444        let res = atoms.pop().unwrap();
1445        let vars = self.atom_info[res].clone();
1446        // For each variable that we added to the cover, remove it from the
1447        // entries in atom_info referencing it and update `sizes` to reflect the
1448        // new ordering.
1449        for new_var in vars.difference(&self.cover).map(Variable::from_usize) {
1450            for subatom in &self.var_info[new_var].occurrences {
1451                let cur_set = &mut self.atom_info[subatom.atom];
1452                let old_size = cur_set.count_ones(..);
1453                cur_set.difference_with(&vars);
1454                let new_size = cur_set.count_ones(..);
1455                if old_size == new_size {
1456                    continue;
1457                }
1458                if let Some(old_size_set) = self.sizes.get_mut(&old_size) {
1459                    old_size_set.swap_remove(&subatom.atom);
1460                    if old_size_set.is_empty() {
1461                        self.sizes.remove(&old_size);
1462                    }
1463                }
1464                if new_size > 0 {
1465                    self.sizes.entry(new_size).or_default().insert(subatom.atom);
1466                }
1467            }
1468        }
1469        self.cover.union_with(&vars);
1470        Some(res)
1471    }
1472}
1473
1474/// Build join headers from fast constraints and compute remaining constraints for planning.
1475/// Returns (headers, remaining_constraints) tuple.
1476fn plan_headers<'a, 'b>(
1477    ctx: &'b PlanningContext<'a>,
1478) -> (
1479    Vec<JoinHeader>,
1480    DenseIdMap<
1481        AtomId,
1482        (
1483            usize, /* The approx size of the subset matching the constraints. */
1484            &'b Pooled<Vec<Constraint>>,
1485        ),
1486    >,
1487) {
1488    let mut header = Vec::new();
1489    let mut remaining_constraints: DenseIdMap<AtomId, (usize, &Pooled<Vec<Constraint>>)> =
1490        Default::default();
1491
1492    for (atom, atom_info) in ctx.atoms.iter() {
1493        remaining_constraints.insert(
1494            atom,
1495            (
1496                atom_info.constraints.approx_size(),
1497                &atom_info.constraints.slow,
1498            ),
1499        );
1500        if !atom_info.constraints.fast.is_empty() {
1501            header.push(JoinHeader {
1502                atom,
1503                constraints: Pooled::cloned(&atom_info.constraints.fast),
1504                subset: atom_info.constraints.subset.clone(),
1505            });
1506        }
1507    }
1508
1509    (header, remaining_constraints)
1510}
1511
1512/// Plan query execution stages using the specified strategy.
1513/// Returns (header, instructions) tuple that can be assembled into a Plan by the caller.
1514/// It does not directly return the plan because the caller may want to further modify the stages.
1515fn plan_stages(ctx: &PlanningContext, strat: PlanStrategy) -> (Vec<JoinHeader>, Vec<JoinStage>) {
1516    let (header, remaining_constraints) = plan_headers(ctx);
1517    let mut instrs = Vec::new();
1518    let mut state = PlanningState::new(ctx.vars.n_ids(), ctx.atoms.n_ids());
1519
1520    match strat {
1521        PlanStrategy::PureSize | PlanStrategy::MinCover => {
1522            plan_free_join(ctx, &mut state, strat, &remaining_constraints, &mut instrs)
1523        }
1524        PlanStrategy::Gj => plan_gj(ctx, &mut state, &remaining_constraints, &mut instrs),
1525    };
1526
1527    (header, instrs)
1528}
1529
1530/// Plan free join queries using pure size or minimal cover strategy.
1531fn plan_free_join(
1532    ctx: &PlanningContext,
1533    state: &mut PlanningState,
1534    strat: PlanStrategy,
1535    remaining_constraints: &DenseIdMap<AtomId, (usize, &Pooled<Vec<Constraint>>)>,
1536    stages: &mut Vec<JoinStage>,
1537) {
1538    let mut size_info = Vec::<(AtomId, usize)>::new();
1539
1540    match strat {
1541        PlanStrategy::PureSize => {
1542            for (atom, (size, _)) in remaining_constraints.iter() {
1543                size_info.push((atom, *size));
1544            }
1545        }
1546        PlanStrategy::MinCover => {
1547            let mut eligible_covers = HashSet::default();
1548            let mut queue = BucketQueue::new(&ctx.vars, &ctx.atoms);
1549            while let Some(atom) = queue.pop_min() {
1550                eligible_covers.insert(atom);
1551            }
1552            for (atom, (size, _)) in remaining_constraints
1553                .iter()
1554                .filter(|(atom, _)| eligible_covers.contains(atom))
1555            {
1556                size_info.push((atom, *size));
1557            }
1558        }
1559        PlanStrategy::Gj => unreachable!(),
1560    };
1561
1562    size_info.sort_by_key(|(_, size)| *size);
1563    let mut atoms = size_info.iter().map(|(atom, _)| *atom);
1564
1565    while let Some(info) = get_next_freejoin_stage(ctx, state, &mut atoms) {
1566        let stage = compile_stage(ctx, state, info);
1567        stages.push(stage);
1568    }
1569}
1570
1571/// Generate the next free join stage by picking an atom from the ordering.
1572/// Returns the stage info and updated state, or None if all atoms are covered.
1573fn get_next_freejoin_stage(
1574    ctx: &PlanningContext,
1575    state: &mut PlanningState,
1576    ordering: &mut impl Iterator<Item = AtomId>,
1577) -> Option<StageInfo> {
1578    let mut scratch_subatom: HashMap<AtomId, ColumnIds> = Default::default();
1579
1580    loop {
1581        let mut covered = false;
1582        let atom = ordering.next()?;
1583        let atom_info = &ctx.atoms[atom];
1584        let mut cover = SubAtom::new(atom);
1585        let mut vars = SmallVec::<[Variable; 1]>::new();
1586
1587        for (ix, var) in atom_info.var_columns.iter() {
1588            if state.is_var_used(var) {
1589                continue;
1590            }
1591            // This atom is not completely covered by previous stages.
1592            covered = true;
1593            state.mark_var_used(var);
1594            vars.push(var);
1595            cover.vars.push(ix);
1596
1597            for subatom in ctx.vars[var].occurrences.iter() {
1598                if subatom.atom == atom {
1599                    continue;
1600                }
1601                scratch_subatom
1602                    .entry(subatom.atom)
1603                    .or_default()
1604                    .extend(subatom.vars.iter().copied());
1605            }
1606        }
1607
1608        if !covered {
1609            // Search the next atom.
1610            continue;
1611        }
1612
1613        let mut filters = Vec::new();
1614        for (atom, cols) in scratch_subatom.drain() {
1615            let mut form_key = ColumnIds::new();
1616            for var_ix in &cols {
1617                let var = ctx.atoms[atom].get_var(*var_ix).unwrap();
1618                // form_key is an index _into the subatom forming the cover_.
1619                let cover_col = vars.iter().position(|v| *v == var).unwrap();
1620                form_key.push(ColumnId::from_usize(cover_col));
1621            }
1622            filters.push((SubAtom { atom, vars: cols }, form_key));
1623        }
1624
1625        return Some(StageInfo {
1626            cover,
1627            vars,
1628            filters,
1629        });
1630    }
1631}
1632
1633/// Plan generic join queries (one variable per stage).
1634///
1635/// Variables are visited in their natural id order. Runtime stage selection
1636/// reorders stages anyway, so static ordering only needs to be deterministic;
1637/// [`fuse_single_scans`] collapses any same-atom single-scans afterwards
1638/// regardless of where they ended up.
1639fn plan_gj(
1640    ctx: &PlanningContext,
1641    state: &mut PlanningState,
1642    _remaining_constraints: &DenseIdMap<AtomId, (usize, &Pooled<Vec<Constraint>>)>,
1643    stages: &mut Vec<JoinStage>,
1644) {
1645    let mut planned_vars = Vec::with_capacity(ctx.vars.n_ids());
1646    let mut atoms_hit = AtomSet::with_capacity(ctx.atoms.n_ids());
1647    for (var, var_info) in ctx.vars.iter() {
1648        let n_occs = var_info.occurrences.len();
1649        if n_occs == 0 {
1650            // No occurrences: ignore (may be bound on the RHS or simply unused).
1651            continue;
1652        }
1653        if n_occs == 1 && !var_info.used_in_rhs {
1654            // Skip for now; we'll plan it below only if its atom is otherwise unmentioned.
1655            continue;
1656        }
1657        for subatom in var_info.occurrences.iter() {
1658            atoms_hit.set(subatom.atom.index(), true);
1659        }
1660        planned_vars.push(var);
1661    }
1662    for (var, var_info) in ctx.vars.iter() {
1663        if var_info.occurrences.len() == 1 && !var_info.used_in_rhs {
1664            // The variable looks "unused" but we still need to touch its atom if nothing else
1665            // has so the join visits every relation.
1666            let subatom = &var_info.occurrences[0];
1667            if !atoms_hit.contains(subatom.atom.index()) {
1668                atoms_hit.set(subatom.atom.index(), true);
1669                planned_vars.push(var);
1670            }
1671        }
1672    }
1673    for var in planned_vars {
1674        let occ = ctx.vars[var].occurrences[0].clone();
1675        let mut info = StageInfo {
1676            cover: occ,
1677            vars: smallvec![var],
1678            filters: Default::default(),
1679        };
1680        for occ in &ctx.vars[var].occurrences[1..] {
1681            info.filters
1682                .push((occ.clone(), smallvec![ColumnId::new(0); occ.vars.len()]));
1683        }
1684
1685        stages.push(compile_stage(ctx, state, info));
1686    }
1687    fuse_single_scans(stages);
1688}
1689
1690/// Compile a stage info into a concrete join stage, updating constraint state.
1691fn compile_stage(
1692    ctx: &PlanningContext,
1693    state: &mut PlanningState,
1694    StageInfo {
1695        cover,
1696        vars,
1697        filters,
1698    }: StageInfo,
1699) -> JoinStage {
1700    fn take_atom_constraints_if_new(
1701        ctx: &PlanningContext,
1702        state: &mut PlanningState,
1703        atom: AtomId,
1704    ) -> Vec<Constraint> {
1705        if state.is_atom_constrained(atom) {
1706            Default::default()
1707        } else {
1708            state.mark_atom_constrained(atom);
1709            ctx.atoms[atom].constraints.slow.clone()
1710        }
1711    }
1712
1713    // Only do this if it's a join of more than one relations
1714    if vars.len() == 1 && !filters.is_empty() {
1715        let scans = SmallVec::<[SingleScanSpec; 3]>::from_iter(
1716            iter::once(&cover)
1717                .chain(filters.iter().map(|(x, _)| x))
1718                .map(|subatom| {
1719                    let atom = subatom.atom;
1720                    SingleScanSpec {
1721                        atom,
1722                        column: subatom.vars[0],
1723                        cs: take_atom_constraints_if_new(ctx, state, atom),
1724                    }
1725                }),
1726        );
1727
1728        return JoinStage::Intersect {
1729            var: vars[0],
1730            scans,
1731        };
1732    }
1733
1734    // FusedIntersect case
1735    let atom = cover.atom;
1736
1737    let cover_spec = ScanSpec {
1738        to_index: cover,
1739        constraints: take_atom_constraints_if_new(ctx, state, atom),
1740    };
1741
1742    let mut bind = SmallVec::new();
1743    for var in vars {
1744        bind.push((ctx.atoms[atom].get_col(var).unwrap(), var));
1745    }
1746
1747    let mut to_intersect = Vec::with_capacity(filters.len());
1748    for (subatom, key_spec) in filters {
1749        let atom = subatom.atom;
1750        let scan = ScanSpec {
1751            to_index: subatom,
1752            constraints: take_atom_constraints_if_new(ctx, state, atom),
1753        };
1754        to_intersect.push((scan, key_spec));
1755    }
1756
1757    JoinStage::FusedIntersect {
1758        cover: cover_spec,
1759        bind,
1760        to_intersect,
1761    }
1762}