Skip to main content

rudb_exec/
prepared.rs

1//! An expression prepared once for a pipeline and then evaluated over every chunk.
2//!
3//! `spec/engine/04-expressions.md`. [`evaluate`](crate::evaluate) walks the plan's expression tree
4//! on every chunk, which means it does four things per chunk that depend on nothing about the
5//! chunk: it recurses, it resolves every column reference by a linear search through the schema, it
6//! clones a [`LogicalType`] for every node, and it copies the whole column a [`Expr::Column`] names.
7//! Over `hits` at a hundred thousand chunks that is a hundred thousand schema searches per column
8//! reference and a hundred thousand copies of every column any expression mentions.
9//!
10//! This type does all four once. The tree is flattened into a post order array, so evaluating it is
11//! a loop over that array and the recursion is gone with it. Column references are resolved to
12//! positions when the pipeline is built. Types are held here rather than cloned out of the plan.
13//! And a column reference is not a step that produces anything: it is read straight out of the chunk
14//! at the point an operand is wanted, so the column is never copied at all.
15//!
16//! # What is shared and what is not
17//!
18//! [`Prepared`] is immutable after it is built and is `Send` and `Sync`, so one of them serves every
19//! thread running a copy of the pipeline. [`Scratch`] is the per chunk working space and there is
20//! one per pipeline instance. That split is not for this layer's benefit. It is the same split every
21//! operator needs at layer eight, where the scheduler runs one pipeline on as many threads as it has
22//! morsels for, and building it here means the operators above are written against it from the start
23//! rather than retrofitted onto it.
24//!
25//! # What is still allocated per chunk
26//!
27//! Two things, and both are named rather than hidden. A node with four or more operands gathers
28//! references to them into a `Vec<&Vector>` so a kernel can take a slice, which is one allocation of
29//! pointers rather than a copy of any data, and which a node of one, two or three operands does on
30//! the stack instead. And every kernel allocates the vector it returns, because no kernel in
31//! `rudb-kernels` takes an output parameter. The second is much the larger of the two and it is the
32//! one tier 1 fusion removes, which is scheduled after layer six for the reason
33//! `spec/engine/04-expressions.md` gives: once the tree walk is gone what is left to save is pass
34//! count, and at 1024 rows the intermediate vectors are eight kilobytes and stay in L1.
35
36use rudb_common::{Error, LogicalType, PhysicalType, Result, Value};
37use rudb_kernels::{
38    Comparison, Connective, Held, Members, Recipe, cast, combine, compare_prepared, in_set,
39    is_true, refine_flags, refine_prepared, selection,
40};
41use rudb_plan::{CompareOp, ConjunctionOp, Expr, ExprRef, Plan};
42use rudb_vector::{Chunk, Selection, Vector};
43use std::collections::HashMap;
44
45use crate::ordering::Ordering;
46use crate::schema::Schema;
47use crate::written::written;
48
49/// The scheduler's half of the expression contract, imposed now rather than at layer eight.
50///
51/// A prepared expression is the immutable half of a pipeline and layer eight hands one of them to
52/// every thread running that pipeline. That is only sound if it holds nothing thread local, and the
53/// way to find out on the commit that breaks it rather than eight layers later is to ask the
54/// compiler here, exactly as [`Chunk`] does for the data plane.
55const _: () = {
56    const fn assert_shareable<T: Send + Sync>() {}
57    assert_shareable::<Prepared>();
58};
59
60/// One or more bound expressions, flattened and resolved against a schema.
61///
62/// Built once per pipeline with [`Prepared::new`] and evaluated per chunk with
63/// [`Prepared::evaluate`] or [`Prepared::evaluate_one`], each of which wants the [`Scratch`] that
64/// [`Prepared::scratch`] hands out.
65#[derive(Debug)]
66pub struct Prepared {
67    /// The nodes in post order, so every node's operands have already been computed when it runs.
68    steps: Vec<Step>,
69    /// The type each step produces, indexed the same way as `steps`.
70    ///
71    /// A parallel array rather than a field in the variant, for the reason [`Expr`] gives: a
72    /// [`LogicalType`] owns a `Vec` for its nested cases and putting one in every variant would make
73    /// the common variants several times larger for the benefit of the rare ones.
74    types: Vec<LogicalType>,
75    /// The operand lists of the steps that have one, as runs of step indices.
76    operands: Vec<usize>,
77    /// The last step that reads each step's slot, or `usize::MAX` for one nothing reads.
78    ///
79    /// A slot is emptied as soon as the step that was the last to read it has run. Keeping every
80    /// intermediate alive to the end of the array instead is what the first measured version of this
81    /// did, and a chain of eight additions was slower prepared than walked because of it: nine live
82    /// intermediates at eight kilobytes each is seventy two kilobytes of working set where the tree
83    /// walk has two, and two is the pair the allocator hands back and forth and that stays in L1.
84    /// Everything else about the prepared form was faster and this one thing paid all of it back.
85    last_use: Vec<usize>,
86    /// The step index each expression this was built from ends at.
87    roots: Vec<usize>,
88    /// The step already compiled for each shared plan expression.
89    shared: HashMap<ExprRef, usize>,
90    share: bool,
91}
92
93/// One node of a flattened expression.
94///
95/// A step refers to its operands by their index in [`Prepared::steps`], which is always smaller than
96/// its own because the array is in post order.
97#[derive(Debug)]
98enum Step {
99    /// A column of the chunk, by resolved position.
100    ///
101    /// This step computes nothing. Its slot stays empty and an operand that names it is read out of
102    /// the chunk, which is the whole of what makes a column reference free rather than a copy.
103    Column(usize),
104    /// A literal, materialized into a constant vector as long as the chunk.
105    Constant(Value),
106    /// A cast to this step's own type.
107    Cast {
108        /// The step being cast.
109        input: usize,
110        /// Whether a failed cast yields null instead of raising.
111        try_cast: bool,
112    },
113    /// A binary comparison.
114    Compare {
115        /// Which comparison.
116        op: Comparison,
117        /// The left operand's step.
118        left: usize,
119        /// The right operand's step.
120        right: usize,
121        /// The side that is a literal, in the one row column the comparison loops read it through,
122        /// and `None` when neither side is one.
123        ///
124        /// Built here because the loops read both sides through a slice, so the constant side has
125        /// to become a column somewhere, and the plan says which side that is. For a string it is
126        /// also where the four byte prefix comes from, which is what almost every row of a string
127        /// comparison is decided by.
128        held: Option<Held>,
129    },
130    /// An `AND` or `OR` over a run of [`Prepared::operands`].
131    Conjunction {
132        /// Which connective.
133        op: Connective,
134        /// Where the operand list starts.
135        start: usize,
136        /// How many operands it has.
137        len: usize,
138    },
139    /// A scalar function over a run of [`Prepared::operands`].
140    Function {
141        /// The call, with the name resolved and whatever the kernel could work out from the
142        /// arguments that were literals already worked out.
143        ///
144        /// Held here so the plan is not consulted per chunk, and built here so that a regular
145        /// expression is compiled once for the query rather than once for each of the hundred
146        /// thousand chunks a pipeline over `hits` runs.
147        recipe: Recipe,
148        /// How the call is written, for the one error message that quotes it.
149        ///
150        /// Rendered when the pipeline is built rather than when a chunk arrives, because the plan
151        /// is here and is not there. It is a short string per function node in the query and it is
152        /// built once, which is a different cost from the tree walk's, where the plan is still to
153        /// hand and the rendering can wait until the row that fails.
154        written: String,
155        /// Where the argument list starts.
156        start: usize,
157        /// How many arguments it has.
158        len: usize,
159    },
160    /// A membership test over a list the query wrote out.
161    ///
162    /// The binder has no `IN` node: `x IN (1, 2, 3)` arrives as an `OR` of three equalities and
163    /// `x NOT IN (1, 2, 3)` as an `AND` of three inequalities. That is the right shape for a binder
164    /// to produce, because nothing after it then needs a second set of rules for null, and it is the
165    /// wrong shape to run, because it is a pass over the column and an output vector per entry.
166    /// This is that shape folded back up, and folding it here rather than after the operands are
167    /// pushed is what keeps the equalities from being run anyway.
168    InSet {
169        /// The step being tested.
170        input: usize,
171        /// The list, as a set, with the null rule and the direction it is read in.
172        members: Members,
173    },
174    /// A searched `CASE`, whose branches are prepared expressions of their own.
175    ///
176    /// Nested rather than flattened into the same array because a branch is not evaluated over the
177    /// chunk, it is evaluated over the rows no earlier arm claimed, and a step in the outer array
178    /// would have no way to say that. The selection threaded form in #57 replaces this whole
179    /// variant, and when it does the branches stop being separate arrays.
180    Case {
181        /// The `WHEN`/`THEN` pairs, in order.
182        arms: Vec<PreparedArm>,
183        /// The `ELSE`, if there is one. Absent means null.
184        otherwise: Option<Prepared>,
185    },
186}
187
188/// One `WHEN`/`THEN` pair of a prepared [`Step::Case`].
189#[derive(Debug)]
190struct PreparedArm {
191    /// The condition.
192    when: Prepared,
193    /// The result if the condition is true.
194    then: Prepared,
195}
196
197/// The per chunk working space of one [`Prepared`].
198///
199/// One per pipeline instance and never shared, which is the mutable half of the split the module
200/// documentation describes. It is handed back in rather than made inside [`Prepared::evaluate`] so
201/// that the array of slots survives from one chunk to the next instead of being allocated a hundred
202/// thousand times over a scan.
203#[derive(Debug)]
204pub struct Scratch {
205    /// What each step produced, or `None` for a step that produces nothing and for one that has not
206    /// run yet.
207    slots: Vec<Option<Vector>>,
208    /// What each connective step has learned about its operands, indexed by step.
209    ///
210    /// Empty for every step that is not a connective and for a connective a filter has not reached
211    /// yet, since it is built the first time one runs and the shape it needs is not known before
212    /// then. This is the mutable half of the adaptive ordering and it is here rather than in
213    /// [`Prepared`] because a prepared expression is shared by every thread running the pipeline.
214    orders: Vec<Option<Ordering>>,
215}
216
217impl Scratch {
218    /// The order a connective's operands are run in.
219    ///
220    /// For the tests that say the learning reached the walk. Nothing in the engine asks a scratch
221    /// this, because the walk is the only thing that reads an ordering and it reads its own.
222    #[cfg(test)]
223    fn order(&self, step: usize) -> Option<&[usize]> {
224        self.orders[step].as_ref().map(Ordering::order)
225    }
226}
227
228impl Prepared {
229    /// Prepares `exprs` against `schema`.
230    ///
231    /// # Errors
232    ///
233    /// If a column reference names a binding the schema does not have, or if an aggregate appears
234    /// where an ordinary expression was expected. Both are failures of the plan rather than of the
235    /// data, which is why they are found here, once, rather than on some chunk in the middle of a
236    /// scan.
237    pub fn new(plan: &Plan, exprs: &[ExprRef], schema: &Schema) -> Result<Self> {
238        Self::build(plan, exprs, schema, false)
239    }
240
241    /// Prepares expressions whose caller can evaluate a shared expression graph as one unit.
242    pub(crate) fn shared(plan: &Plan, exprs: &[ExprRef], schema: &Schema) -> Result<Self> {
243        Self::build(plan, exprs, schema, true)
244    }
245
246    fn build(plan: &Plan, exprs: &[ExprRef], schema: &Schema, share: bool) -> Result<Self> {
247        let mut prepared = Self {
248            steps: Vec::new(),
249            types: Vec::new(),
250            operands: Vec::new(),
251            last_use: Vec::new(),
252            roots: Vec::new(),
253            shared: HashMap::new(),
254            share,
255        };
256        for &expr in exprs {
257            let root = prepared.push(plan, expr, schema)?;
258            prepared.roots.push(root);
259        }
260        prepared.last_use = prepared.last_uses();
261        Ok(prepared)
262    }
263
264    /// Which step is the last to read each step, computed once when the expression is prepared.
265    ///
266    /// A root is never freed, because the whole point of running the array was to produce it. A
267    /// step nothing reads and that is not a root cannot happen, since every step is pushed by the
268    /// node that wanted it, but saying `usize::MAX` rather than asserting that keeps this a fact
269    /// about the array rather than a claim about the builder.
270    fn last_uses(&self) -> Vec<usize> {
271        let mut last = vec![usize::MAX; self.steps.len()];
272        for index in 0..self.steps.len() {
273            self.for_each_operand(index, |operand| last[operand] = index);
274        }
275        for &root in &self.roots {
276            last[root] = usize::MAX;
277        }
278        last
279    }
280
281    /// Visits the steps one step reads, whatever shape its operands are held in.
282    fn for_each_operand(&self, index: usize, mut visit: impl FnMut(usize)) {
283        match &self.steps[index] {
284            // A case's branches are arrays of their own and read nothing out of this one.
285            Step::Column(_) | Step::Constant(_) | Step::Case { .. } => {}
286            Step::Cast { input, .. } | Step::InSet { input, .. } => visit(*input),
287            Step::Compare { left, right, .. } => {
288                visit(*left);
289                visit(*right);
290            }
291            Step::Conjunction { start, len, .. } | Step::Function { start, len, .. } => {
292                for &operand in &self.operands[*start..*start + *len] {
293                    visit(operand);
294                }
295            }
296        }
297    }
298
299    /// Prepares one expression, which is the common case and saves the caller a slice.
300    ///
301    /// # Errors
302    ///
303    /// Whatever [`Prepared::new`] reports.
304    pub fn one(plan: &Plan, expr: ExprRef, schema: &Schema) -> Result<Self> {
305        Self::new(plan, &[expr], schema)
306    }
307
308    /// Working space sized for this expression.
309    #[must_use]
310    pub fn scratch(&self) -> Scratch {
311        Scratch {
312            slots: (0..self.steps.len()).map(|_| None).collect(),
313            orders: (0..self.steps.len()).map(|_| None).collect(),
314        }
315    }
316
317    /// How many expressions this was built from.
318    #[must_use]
319    pub fn len(&self) -> usize {
320        self.roots.len()
321    }
322
323    /// How many comparisons have their literal side already built.
324    ///
325    /// For the tests, for the same reason as [`Self::sets`]: an answer that moved would be a bug,
326    /// so the only thing a test can look at is whether the building happened.
327    #[cfg(test)]
328    fn literals_built(&self) -> usize {
329        self.steps.iter().filter(|step| matches!(step, Step::Compare { held: Some(_), .. })).count()
330    }
331
332    /// How many of the steps are an `IN` list folded back up.
333    ///
334    /// For the tests, which cannot see the fold in an answer because an answer that changed would
335    /// be a bug.
336    #[cfg(test)]
337    fn sets(&self) -> usize {
338        self.steps.iter().filter(|step| matches!(step, Step::InSet { .. })).count()
339    }
340
341    /// How many of the function steps worked something out when this was built.
342    ///
343    /// For the tests, which cannot see the hoisting in an answer because an answer that changed
344    /// would be a bug.
345    #[cfg(test)]
346    fn hoisted(&self) -> usize {
347        self.steps
348            .iter()
349            .filter(|step| matches!(step, Step::Function { recipe, .. } if recipe.hoists()))
350            .count()
351    }
352
353    /// Whether it was built from no expressions at all.
354    #[must_use]
355    pub fn is_empty(&self) -> bool {
356        self.roots.is_empty()
357    }
358
359    /// Evaluates every expression over `chunk`, appending one vector each to `out`.
360    ///
361    /// Appends rather than returns a `Vec`, so a caller in a loop reuses one buffer.
362    ///
363    /// # Errors
364    ///
365    /// Anything a kernel reports, on the first expression that reports it.
366    pub fn evaluate(
367        &self,
368        chunk: &Chunk,
369        scratch: &mut Scratch,
370        out: &mut Vec<Vector>,
371    ) -> Result<()> {
372        self.run(chunk, scratch)?;
373        let mut remaining: HashMap<usize, usize> = HashMap::new();
374        for &root in &self.roots {
375            *remaining.entry(root).or_default() += 1;
376        }
377        for &root in &self.roots {
378            // The one place a column is copied, and it is copied because the caller is taking
379            // ownership of a vector that has to outlive the chunk it came from. `SELECT a` is that
380            // shape and a projection of a bare column is the only expression where it happens.
381            match self.steps[root] {
382                Step::Column(position) => out.push(chunk.column(position)?.clone()),
383                _ => {
384                    let Some(left) = remaining.get_mut(&root) else {
385                        return Err(Error::internal("a prepared root was not counted"));
386                    };
387                    *left -= 1;
388                    if *left == 0 {
389                        out.push(scratch.slots[root].take().ok_or_else(|| missing(root))?);
390                    } else {
391                        out.push(
392                            scratch.slots[root].as_ref().ok_or_else(|| missing(root))?.clone(),
393                        );
394                    }
395                }
396            }
397        }
398        Ok(())
399    }
400
401    /// Evaluates a single expression over `chunk`, handing back a reference to the answer.
402    ///
403    /// A reference rather than a vector, because the caller of this is a filter, which reads the
404    /// flags to build a selection and then drops them. Nothing about that wants ownership, and a
405    /// predicate that is a bare column reference, which `WHERE flag` is, would otherwise copy the
406    /// column to hand it over.
407    ///
408    /// # Errors
409    ///
410    /// Anything a kernel reports, and an internal error if this was not built from exactly one
411    /// expression.
412    pub fn evaluate_one<'s>(
413        &'s self,
414        chunk: &'s Chunk,
415        scratch: &'s mut Scratch,
416    ) -> Result<&'s Vector> {
417        let [root] = self.roots[..] else {
418            return Err(Error::internal(format!(
419                "evaluate_one over a prepared expression of {} roots",
420                self.roots.len()
421            )));
422        };
423        self.run(chunk, scratch)?;
424        self.operand(root, chunk, &scratch.slots)
425    }
426
427    /// Evaluates a single expression as a filter, handing back the rows it keeps.
428    ///
429    /// The difference between this and [`evaluate_one`](Self::evaluate_one) followed by
430    /// [`selection`] is the whole of what a threaded filter is. An `AND` evaluated as an expression
431    /// runs every conjunct over every row and then combines the flag vectors, so a predicate of four
432    /// conjuncts that each pass a fifth of the rows does five times the work of one that stops
433    /// looking at a row as soon as a conjunct rejects it. TPC-H Q6 is exactly that predicate.
434    ///
435    /// So the conjuncts of a top level `AND` are run one at a time, each over the rows the ones
436    /// before it left, and the moment nothing is left the rest of the predicate is not run at all.
437    /// The order they run in starts as the order the plan gives and then moves, because which
438    /// conjunct is worth running first is a question about the data and the scan is the thing
439    /// holding the answer. The `ordering` module has what is measured and how.
440    ///
441    /// A top level `OR` is threaded the same way against the complement. A row the first branch
442    /// accepts is a row the filter keeps whatever the rest of the predicate says about it, so each
443    /// branch is run over the rows no branch before it accepted, and the moment every row has been
444    /// accepted the rest of the predicate is not run either. That is the mirror of the `AND` case
445    /// and not an approximation of it: the answer is the same set of rows, because `OR` over three
446    /// valued logic is true wherever any branch is true and nothing a later branch says can take a
447    /// row back. It is worth less than the `AND` case in practice, since an `OR` of selective
448    /// branches leaves almost every row in play for the branch after, and it is worth having anyway
449    /// because the cost of finding that out is one merge per branch.
450    ///
451    /// What is threaded is the operand's own comparison rather than the whole of its subtree. A
452    /// conjunct of `a + b > 5` still adds over the whole chunk, because the scalar kernels take a
453    /// vector rather than a selection, and it is the comparison and everything downstream of it that
454    /// reads only the rows still in play. An operand that is a bare column or a function produces
455    /// flags over the chunk and is narrowed with [`refine_flags`], which is what keeps one awkward
456    /// operand from putting the others back on the unthreaded path. An operand that is itself a
457    /// connective recurses, so the two conjuncts of each half of `(a AND b) OR (c AND d)` are
458    /// threaded the same way the halves are.
459    ///
460    /// None of this is available to a projection. `SELECT a > 5 AND b LIKE 'x%'` wants a value per
461    /// row and the rows a selection dropped have no value in it, so [`evaluate`](Self::evaluate) and
462    /// [`evaluate_one`](Self::evaluate_one) evaluate the whole tree over the whole chunk and combine
463    /// flags. The two are separate entry points picked when the pipeline is built rather than one
464    /// path with a flag in it, because conflating them is a wrong answer rather than a slow one.
465    ///
466    /// # Errors
467    ///
468    /// Anything a kernel reports, and an internal error if this was not built from exactly one
469    /// expression.
470    pub fn evaluate_filter(&self, chunk: &Chunk, scratch: &mut Scratch) -> Result<Selection> {
471        let [root] = self.roots[..] else {
472            return Err(Error::internal(format!(
473                "evaluate_filter over a prepared expression of {} roots",
474                self.roots.len()
475            )));
476        };
477        scratch.slots.clear();
478        scratch.slots.resize_with(self.steps.len(), || None);
479        // A predicate that is not a connective at all is the same walk over one operand, which is
480        // where [`thread`](Self::thread) starts: it runs the tree and turns the flags into a
481        // selection, with no narrowing to do because nothing has narrowed anything yet.
482        self.thread(root, 0, chunk, scratch, None)
483    }
484
485    /// The operands of one connective, run in order, each over the rows the ones before it left.
486    ///
487    /// `live` is the rows this connective has to decide about and `None` means every row of the
488    /// chunk, which is not the same as a selection of all of them: it lets the first operand take
489    /// the unthreaded kernel rather than a pass over an identity selection. The answer is the rows
490    /// out of `live` the connective is true for.
491    ///
492    /// The walk is the same for both connectives and only the bookkeeping differs. `AND` carries the
493    /// rows every operand so far has kept, so each answer replaces it. `OR` carries the rows no
494    /// operand so far has accepted, so each answer comes out of it and the rows the connective keeps
495    /// are the ones that went missing along the way.
496    ///
497    /// The operand is not `steps[begin..=operand]` evaluated and then narrowed. Its subtree is run
498    /// over the whole chunk and it is the operand itself that reads only the rows in play, except
499    /// where the operand is another connective, which recurses and threads its own operands from
500    /// here rather than falling back to a flag vector. That is what makes `(a AND b) OR (c AND d)`
501    /// four threaded comparisons rather than two threaded ones and two flag passes.
502    fn branches(
503        &self,
504        index: usize,
505        begin: usize,
506        chunk: &Chunk,
507        scratch: &mut Scratch,
508        live: Option<&Selection>,
509    ) -> Result<Selection> {
510        let Step::Conjunction { op, start, len } = self.steps[index] else {
511            return Err(Error::internal("a connective walk over a step that is not a connective"));
512        };
513        let operands = &self.operands[start..start + len];
514        let rows = chunk.len();
515        // Out of the scratch for the length of the walk, because the walk runs steps and running a
516        // step wants the scratch. It goes back at the end, which is also where it learns. A walk
517        // that fails leaves the slot empty and the next chunk starts the connective over, which is
518        // a history lost on a query that is about to stop running anyway.
519        let mut order = scratch.orders[index]
520            .take()
521            .unwrap_or_else(|| Ordering::new(op, self.weights(operands, begin)));
522        let mut carried: Option<Selection> = live.cloned();
523        for slot in 0..len {
524            if carried.as_ref().is_some_and(Selection::is_empty) {
525                break;
526            }
527            let which = order.at(slot);
528            let operand = operands[which];
529            // The array is in post order and an operand's whole subtree sits between the operand
530            // before it and the operand itself, which is a range the run order cannot move. That is
531            // what lets the operands run in any order at all without a second structure to say
532            // where each one starts.
533            let from = if which == 0 { begin } else { operands[which - 1] + 1 };
534            let given = carried.as_ref().map_or(rows, Selection::len);
535            let answered = self.thread(operand, from, chunk, scratch, carried.as_ref())?;
536            order.observed(which, given, answered.len());
537            carried = Some(match (op, carried) {
538                (Connective::And, _) => answered,
539                (Connective::Or, None) => answered.complement(rows),
540                (Connective::Or, Some(carried)) => carried.without(&answered),
541            });
542            // Keep a shared step alive when a later operand still reads it.
543            for step in from..=operand {
544                if self.last_use[step] <= operand {
545                    scratch.slots[step] = None;
546                }
547            }
548        }
549        order.relearn();
550        scratch.orders[index] = Some(order);
551        Ok(match (op, carried) {
552            // A connective with no operands, which the binder does not build and which is answered
553            // here rather than left to index arithmetic: an empty `AND` is every row and an empty
554            // `OR` is none.
555            (Connective::And, None) => live.cloned().unwrap_or_else(|| Selection::identity(rows)),
556            (Connective::And, Some(kept)) => kept,
557            (Connective::Or, None) => Selection::empty(),
558            (Connective::Or, Some(missed)) => match live {
559                None => missed.complement(rows),
560                Some(live) => live.without(&missed),
561            },
562        })
563    }
564
565    /// What each operand of a connective costs to run over a chunk, for the ordering to divide by.
566    ///
567    /// An operand costs what its whole subtree costs, which is the steps from where the operand
568    /// before it ended up to the operand itself.
569    fn weights(&self, operands: &[usize], begin: usize) -> Vec<f64> {
570        let mut costs = Vec::with_capacity(operands.len());
571        let mut from = begin;
572        for &operand in operands {
573            costs.push((from..=operand).map(|step| self.weight(step)).sum());
574            from = operand + 1;
575        }
576        costs
577    }
578
579    /// Roughly what one step costs to run over a chunk, against a comparison of two fixed width
580    /// columns as the unit.
581    ///
582    /// A ranking rather than a prediction. Nothing downstream reads the number itself, only which
583    /// of two of them is larger, and the differences that decide an order are the big ones: a
584    /// column reference costs nothing because it is read in place, a string function costs many
585    /// times what an integer comparison costs, and a comparison over a variable length type costs
586    /// several times what the same comparison over a fixed width one costs. Everything finer than
587    /// that is below the noise of what the window is measuring anyway.
588    fn weight(&self, index: usize) -> f64 {
589        match &self.steps[index] {
590            // Read straight out of the chunk at the point an operand is wanted, so there is no step
591            // to run and nothing to charge for.
592            Step::Column(_) => 0.0,
593            // One vector built per chunk, however many rows the chunk has.
594            Step::Constant(_) => 0.25,
595            // The operands carry the cost of a connective, and they are steps of their own.
596            Step::Conjunction { .. } => 0.0,
597            Step::Cast { input, .. } => 2.0 * touching(&self.types[*input]),
598            Step::Compare { left, .. } => touching(&self.types[*left]),
599            // One hash and one probe a row, whatever the list holds, which is the point of it. It
600            // is dearer than a comparison and much cheaper than the chain of them it replaced.
601            Step::InSet { input, .. } => 2.0 * touching(&self.types[*input]),
602            Step::Function { start, len, .. } => {
603                let widest = self.operands[*start..*start + *len]
604                    .iter()
605                    .map(|&argument| touching(&self.types[argument]))
606                    .fold(1.0, f64::max);
607                4.0 * widest
608            }
609            // A branch per arm, each of which is a prepared expression of its own that this does
610            // not look inside. Charging for the arms alone understates it and says the right thing
611            // about the order, which is that a `CASE` is not what you want in front.
612            Step::Case { arms, .. } => 4.0 * arms.len() as f64,
613        }
614    }
615
616    /// One operand of a connective, over the rows it is still worth asking about.
617    ///
618    /// `begin` is the first step of the operand's subtree, which the caller knows because the steps
619    /// are in post order.
620    fn thread(
621        &self,
622        index: usize,
623        begin: usize,
624        chunk: &Chunk,
625        scratch: &mut Scratch,
626        live: Option<&Selection>,
627    ) -> Result<Selection> {
628        if matches!(self.steps[index], Step::Conjunction { .. }) {
629            return self.branches(index, begin, chunk, scratch, live);
630        }
631        for step in begin..index {
632            self.run_step(step, chunk, scratch)?;
633        }
634        if let Step::Compare { op, left, right, held } = &self.steps[index] {
635            let one = self.operand(*left, chunk, &scratch.slots)?;
636            let other = self.operand(*right, chunk, &scratch.slots)?;
637            let held = held.as_ref();
638            return match live {
639                // The first operand has every row in play, and asking the threaded kernel for that
640                // would be a pass over an identity selection the unthreaded one does not need.
641                None => Ok(selection(&compare_prepared(*op, one, other, held)?, chunk.len())),
642                Some(live) => refine_prepared(*op, one, other, live, held),
643            };
644        }
645        self.run_step(index, chunk, scratch)?;
646        let flags = self.operand(index, chunk, &scratch.slots)?;
647        match live {
648            None => Ok(selection(flags, chunk.len())),
649            Some(live) => refine_flags(flags, live),
650        }
651    }
652
653    /// Runs every step in order, filling the slots.
654    fn run(&self, chunk: &Chunk, scratch: &mut Scratch) -> Result<()> {
655        scratch.slots.clear();
656        scratch.slots.resize_with(self.steps.len(), || None);
657        for index in 0..self.steps.len() {
658            self.run_step(index, chunk, scratch)?;
659        }
660        Ok(())
661    }
662
663    /// Runs one step and empties the slot of every operand this was the last step to read.
664    fn run_step(&self, index: usize, chunk: &Chunk, scratch: &mut Scratch) -> Result<()> {
665        let produced = self.step(index, chunk, &scratch.slots)?;
666        scratch.slots[index] = produced;
667        let slots = &mut scratch.slots;
668        self.for_each_operand(index, |operand| {
669            if self.last_use[operand] == index {
670                slots[operand] = None;
671            }
672        });
673        Ok(())
674    }
675
676    /// Runs one step, given what the steps before it produced.
677    fn step(
678        &self,
679        index: usize,
680        chunk: &Chunk,
681        slots: &[Option<Vector>],
682    ) -> Result<Option<Vector>> {
683        let ty = &self.types[index];
684        let produced = match &self.steps[index] {
685            Step::Column(_) => None,
686            Step::Constant(value) => Some(Vector::constant(ty.clone(), value.clone(), chunk.len())),
687            Step::Cast { input, try_cast } => {
688                Some(cast(self.operand(*input, chunk, slots)?, ty, *try_cast)?)
689            }
690            Step::Compare { op, left, right, held } => Some(compare_prepared(
691                *op,
692                self.operand(*left, chunk, slots)?,
693                self.operand(*right, chunk, slots)?,
694                held.as_ref(),
695            )?),
696            Step::Conjunction { op, start, len } => {
697                Some(
698                    self.with_operands(*start, *len, chunk, slots, |children| {
699                        combine(*op, children)
700                    })?,
701                )
702            }
703            Step::Function { recipe, written, start, len } => {
704                Some(self.with_operands(*start, *len, chunk, slots, |args| {
705                    rudb_kernels::call_prepared(recipe, args, ty, Some(&|| written.clone()))
706                })?)
707            }
708            Step::InSet { input, members } => {
709                Some(in_set(self.operand(*input, chunk, slots)?, members, ty)?)
710            }
711            Step::Case { arms, otherwise } => {
712                Some(self.case(chunk, arms, otherwise.as_ref(), ty)?)
713            }
714        };
715        Ok(produced)
716    }
717
718    /// The vector a step produced, or the chunk's column if the step is a column reference.
719    fn operand<'v>(
720        &self,
721        index: usize,
722        chunk: &'v Chunk,
723        slots: &'v [Option<Vector>],
724    ) -> Result<&'v Vector> {
725        if let Step::Column(position) = self.steps[index] {
726            return chunk.column(position);
727        }
728        slots[index].as_ref().ok_or_else(|| missing(index))
729    }
730
731    /// Hands a kernel the references to an operand list, without allocating for the usual widths.
732    ///
733    /// One, two and three because those are what a bound tree is made of: every scalar function in
734    /// the catalog is unary or binary, a comparison is binary, and a conjunction is two or three
735    /// often enough to be worth a line. A stack array for those means a chain of eight additions
736    /// makes zero allocations for its operand lists over a chunk instead of eight, and eight
737    /// allocations a chunk at the rate a pipeline produces chunks is a real number rather than a
738    /// tidiness argument. Anything wider falls back to [`gather`](Self::gather), which is a `Vec`
739    /// of pointers and still moves no data.
740    fn with_operands<'v, T>(
741        &self,
742        start: usize,
743        len: usize,
744        chunk: &'v Chunk,
745        slots: &'v [Option<Vector>],
746        run: impl FnOnce(&[&'v Vector]) -> Result<T>,
747    ) -> Result<T> {
748        match self.operands[start..start + len] {
749            [a] => run(&[self.operand(a, chunk, slots)?]),
750            [a, b] => run(&[self.operand(a, chunk, slots)?, self.operand(b, chunk, slots)?]),
751            [a, b, c] => run(&[
752                self.operand(a, chunk, slots)?,
753                self.operand(b, chunk, slots)?,
754                self.operand(c, chunk, slots)?,
755            ]),
756            _ => {
757                let gathered = self.gather(start, len, chunk, slots)?;
758                run(&gathered)
759            }
760        }
761    }
762
763    /// References to an operand list, for a kernel that takes a slice of them.
764    ///
765    /// The `Vec` here is the allocation the module documentation names: it holds pointers rather
766    /// than vectors, so it is a dozen bytes an operand and no data moves.
767    fn gather<'v>(
768        &self,
769        start: usize,
770        len: usize,
771        chunk: &'v Chunk,
772        slots: &'v [Option<Vector>],
773    ) -> Result<Vec<&'v Vector>> {
774        let mut gathered = Vec::with_capacity(len);
775        for &operand in &self.operands[start..start + len] {
776            gathered.push(self.operand(operand, chunk, slots)?);
777        }
778        Ok(gathered)
779    }
780
781    /// A searched `CASE` over the rows no earlier arm claimed.
782    ///
783    /// The same shape [`evaluate`](crate::evaluate) has, because the thing that makes it that shape
784    /// is a correctness rule rather than a performance one: `CASE WHEN x <> 0 THEN 1 / x ELSE 0 END`
785    /// divides by zero on the rows the arm excludes if the arm is evaluated for them. What is left
786    /// of it after #57 is the same rule expressed as a selection rather than as a narrowed chunk,
787    /// with the answers scattered back instead of assembled out of a `Vec<Value>`.
788    fn case(
789        &self,
790        chunk: &Chunk,
791        arms: &[PreparedArm],
792        otherwise: Option<&Prepared>,
793        ty: &LogicalType,
794    ) -> Result<Vector> {
795        let mut answers = vec![Value::Null; chunk.len()];
796        let mut pending: Vec<usize> = (0..chunk.len()).collect();
797        for arm in arms {
798            if pending.is_empty() {
799                break;
800            }
801            let narrowed = narrow(chunk, &pending)?;
802            let mut scratch = arm.when.scratch();
803            let flags = arm.when.evaluate_one(&narrowed, &mut scratch)?;
804            let mut taken = Vec::new();
805            let mut still = Vec::new();
806            // row at a time: the scatter that replaces these three loops is #57, and this variant
807            // goes with it.
808            for (at, &row) in pending.iter().enumerate() {
809                if is_true(&flags.value_at(at)) {
810                    taken.push((at, row));
811                } else {
812                    still.push(row);
813                }
814            }
815            if !taken.is_empty() {
816                let positions: Vec<usize> = taken.iter().map(|&(at, _)| at).collect();
817                let matched = narrow(&narrowed, &positions)?;
818                let mut scratch = arm.then.scratch();
819                let results = arm.then.evaluate_one(&matched, &mut scratch)?;
820                // row at a time: the scatter this wants is #57, same as the loop above.
821                for (slot, &(_, row)) in taken.iter().enumerate() {
822                    answers[row] = results.value_at(slot);
823                }
824            }
825            pending = still;
826        }
827        if let Some(otherwise) = otherwise {
828            if !pending.is_empty() {
829                let narrowed = narrow(chunk, &pending)?;
830                let mut scratch = otherwise.scratch();
831                let results = otherwise.evaluate_one(&narrowed, &mut scratch)?;
832                // row at a time: the scatter this wants is #57, same as the two above.
833                for (slot, &row) in pending.iter().enumerate() {
834                    answers[row] = results.value_at(slot);
835                }
836            }
837        }
838        Vector::from_values(ty.clone(), &answers)
839    }
840
841    /// Flattens one expression, appending its steps and returning the index of its last one.
842    fn push(&mut self, plan: &Plan, expr: ExprRef, schema: &Schema) -> Result<usize> {
843        if self.share {
844            if let Some(&step) = self.shared.get(&expr) {
845                return Ok(step);
846            }
847        }
848        let ty = plan.expr_type(expr).clone();
849        let step = match *plan.expr(expr) {
850            Expr::Column(binding) => {
851                let position = schema.position_of(binding).ok_or_else(|| {
852                    Error::internal(format!(
853                        "column #{}.{} is not in the schema this operator was given",
854                        binding.table, binding.column
855                    ))
856                })?;
857                Step::Column(position)
858            }
859            Expr::Constant(reference) => Step::Constant(plan.value(reference).clone()),
860            Expr::Cast { input, try_cast } => {
861                Step::Cast { input: self.push(plan, input, schema)?, try_cast }
862            }
863            Expr::Compare { op, left, right } => {
864                let left = self.push(plan, left, schema)?;
865                let right = self.push(plan, right, schema)?;
866                Step::Compare { op: comparison(op), left, right, held: self.held(left, right) }
867            }
868            Expr::Conjunction { op, children } => {
869                let list = plan.expr_list(children).to_vec();
870                match self.membership(plan, connective(op), &list, schema)? {
871                    Some(step) => step,
872                    None => {
873                        let (start, len) = self.push_list(plan, &list, schema)?;
874                        Step::Conjunction { op: connective(op), start, len }
875                    }
876                }
877            }
878            Expr::Function { name, args } => {
879                let (start, len) = self.push_list(plan, plan.expr_list(args), schema)?;
880                Step::Function {
881                    recipe: Recipe::new(plan.string(name), &self.literals(start, len)),
882                    written: written(plan, expr, schema),
883                    start,
884                    len,
885                }
886            }
887            Expr::Aggregate { name, .. } => {
888                return Err(Error::internal(format!(
889                    "the {} aggregate was evaluated as an ordinary expression",
890                    plan.string(name)
891                )));
892            }
893            Expr::Case { arms, otherwise } => {
894                let mut prepared = Vec::new();
895                for &arm in plan.arm_list(arms) {
896                    prepared.push(PreparedArm {
897                        when: Self::one(plan, arm.when, schema)?,
898                        then: Self::one(plan, arm.then, schema)?,
899                    });
900                }
901                let otherwise = match otherwise {
902                    Some(otherwise) => Some(Self::one(plan, otherwise, schema)?),
903                    None => None,
904                };
905                Step::Case { arms: prepared, otherwise }
906            }
907        };
908        self.steps.push(step);
909        self.types.push(ty);
910        let step = self.steps.len() - 1;
911        if self.share {
912            self.shared.insert(expr, step);
913        }
914        Ok(step)
915    }
916
917    /// Flattens a list of expressions and records where its operand run starts and how long it is.
918    ///
919    /// The operand run is written after every child has been flattened rather than as they go,
920    /// because a child that is itself a list would otherwise interleave its run with this one.
921    fn push_list(
922        &mut self,
923        plan: &Plan,
924        exprs: &[ExprRef],
925        schema: &Schema,
926    ) -> Result<(usize, usize)> {
927        let mut indices = Vec::with_capacity(exprs.len());
928        for &expr in exprs {
929            indices.push(self.push(plan, expr, schema)?);
930        }
931        let start = self.operands.len();
932        let len = indices.len();
933        self.operands.extend(indices);
934        Ok((start, len))
935    }
936
937    /// This connective folded back into the `IN` the user wrote, or `None` when it is not one.
938    ///
939    /// What the binder writes for `x IN (1, 2, 3)` is `x = 1 OR x = 2 OR x = 3`, and for
940    /// `x NOT IN (1, 2, 3)` it is `x <> 1 AND x <> 2 AND x <> 3`. So the shape looked for is every
941    /// child a comparison of the one direction, every left the same expression, and every right a
942    /// literal. Anything else is left alone, which covers the `OR` that was written as an `OR` and
943    /// the one where an `IN` has been flattened together with another branch. The second is a fold
944    /// this could make and does not, and it is worth having later out of a query that wants it
945    /// rather than now out of a guess.
946    ///
947    /// This runs before the children are pushed, and that is the whole reason it is here rather than
948    /// as a pass over the finished array. A step that nothing reads is still a step the walk runs,
949    /// because the walk over a subtree is a range and not a graph, so folding after the fact would
950    /// leave every equality in place and running.
951    fn membership(
952        &mut self,
953        plan: &Plan,
954        op: Connective,
955        children: &[ExprRef],
956        schema: &Schema,
957    ) -> Result<Option<Step>> {
958        let wanted = match op {
959            Connective::Or => CompareOp::Equal,
960            Connective::And => CompareOp::NotEqual,
961        };
962        let mut subject: Option<ExprRef> = None;
963        let mut values = Vec::with_capacity(children.len());
964        for &child in children {
965            let Expr::Compare { op: found, left, right } = *plan.expr(child) else {
966                return Ok(None);
967            };
968            if found != wanted || !same(plan, *subject.get_or_insert(left), left) {
969                return Ok(None);
970            }
971            let Expr::Constant(reference) = *plan.expr(right) else {
972                return Ok(None);
973            };
974            values.push(plan.value(reference).clone());
975        }
976        let (Some(subject), Some(members)) = (subject, Members::of(&values, op == Connective::And))
977        else {
978            return Ok(None);
979        };
980        Ok(Some(Step::InSet { input: self.push(plan, subject, schema)?, members }))
981    }
982
983    /// The literal side of a comparison, in the one row column the comparison reads it through.
984    ///
985    /// The right side first, because that is the side the binder puts a literal on and the side the
986    /// loops are written for. Two literals is a comparison the optimizer folded, and if it did not
987    /// then the kernel answers it once for the whole vector and never reads either column, so
988    /// neither side is built here.
989    fn held(&self, left: usize, right: usize) -> Option<Held> {
990        let (at, other) = match (&self.steps[left], &self.steps[right]) {
991            (Step::Constant(_), Step::Constant(_)) => return None,
992            (_, Step::Constant(value)) => (right, value),
993            (Step::Constant(value), _) => (left, value),
994            _ => return None,
995        };
996        Held::of(&self.types[at], other)
997    }
998
999    /// The literal behind each argument in a run of the operand list, and `None` for an argument
1000    /// that is anything else.
1001    ///
1002    /// This is what a [`Recipe`] hoists from. An argument that is a literal in the plan arrives as a
1003    /// constant vector holding exactly this value on every chunk, so what a kernel reads here is
1004    /// what it would have read per chunk. An argument that is a cast of a literal reads as `None`,
1005    /// which is a call the kernel decides per chunk as it always did, and the optimizer folds most
1006    /// of those before the plan gets here anyway.
1007    fn literals(&self, start: usize, len: usize) -> Vec<Option<Value>> {
1008        self.operands[start..start + len]
1009            .iter()
1010            .map(|&operand| match &self.steps[operand] {
1011                Step::Constant(value) => Some(value.clone()),
1012                _ => None,
1013            })
1014            .collect()
1015    }
1016}
1017
1018/// Whether two expressions of one plan are the same expression, written once or written twice.
1019///
1020/// The binder binds the subject of an `IN` once and points every comparison it writes at that one
1021/// reference, so the answer is almost always the first line. A plan that has been through a rewrite,
1022/// and a plan read back from its own text, hold two copies of the same tree instead, and for the
1023/// fold in [`Prepared::membership`] those are the same expression.
1024///
1025/// The four shapes handled are what an `IN` is written over: a column, a literal, a cast of either,
1026/// and a call, which is TPC-H query 22 asking whether the first two digits of a phone number are in
1027/// a list. Anything else answers no, which costs a fold that could have happened rather than a wrong
1028/// one. The walk is bounded by the size of the subject and a subject is small.
1029fn same(plan: &Plan, left: ExprRef, right: ExprRef) -> bool {
1030    if left == right {
1031        return true;
1032    }
1033    if plan.expr_type(left) != plan.expr_type(right) {
1034        return false;
1035    }
1036    match (plan.expr(left), plan.expr(right)) {
1037        (Expr::Column(one), Expr::Column(other)) => one == other,
1038        (Expr::Constant(one), Expr::Constant(other)) => plan.value(*one) == plan.value(*other),
1039        (
1040            Expr::Cast { input: one, try_cast: first },
1041            Expr::Cast { input: other, try_cast: second },
1042        ) => first == second && same(plan, *one, *other),
1043        (
1044            Expr::Function { name: one, args: first },
1045            Expr::Function { name: other, args: second },
1046        ) => {
1047            let (first, second) = (plan.expr_list(*first), plan.expr_list(*second));
1048            plan.string(*one) == plan.string(*other)
1049                && first.len() == second.len()
1050                && first.iter().zip(second).all(|(&one, &other)| same(plan, one, other))
1051        }
1052        _ => false,
1053    }
1054}
1055
1056/// What touching a value of this type costs, against a fixed width one as the unit.
1057///
1058/// A variable length value is a pointer to follow and a length that is not the same twice, and a
1059/// nested one is that per element. Four is not measured, and what it has to be is large enough that
1060/// the ordering puts a fixed width comparison in front of a string one and small enough that it does
1061/// not put one in front of a string comparison that rejects every row.
1062fn touching(ty: &LogicalType) -> f64 {
1063    match ty.physical() {
1064        PhysicalType::Varlen => 4.0,
1065        PhysicalType::List | PhysicalType::Array | PhysicalType::Struct => 8.0,
1066        _ => 1.0,
1067    }
1068}
1069
1070/// The error for a slot that should have held something and did not.
1071///
1072/// This cannot happen while the array is in post order, since every operand's index is smaller than
1073/// the index of the step using it and every step runs in order. It is an error rather than a panic
1074/// because the property it depends on is a property of [`Prepared::push`], and the day somebody
1075/// writes a pass that reorders the array is the day it stops holding.
1076fn missing(index: usize) -> Error {
1077    Error::internal(format!("step {index} was used as an operand before it produced anything"))
1078}
1079
1080/// The chunk cut down to the given rows.
1081///
1082/// The reason `CASE` is written with this rather than by evaluating every arm over the whole chunk
1083/// and picking afterwards. `CASE WHEN x <> 0 THEN 1 // x ELSE 0 END` divides by zero on the rows the
1084/// arm does not apply to if the arm is evaluated for them, and a `CASE` that raises on a row it was
1085/// written to exclude is the classic wrong answer this shape prevents.
1086pub(crate) fn narrow(chunk: &Chunk, rows: &[usize]) -> Result<Chunk> {
1087    let mut selection = Selection::with_capacity(rows.len());
1088    for &row in rows {
1089        selection.push(row);
1090    }
1091    chunk.clone().select(&selection)
1092}
1093
1094/// The kernels' comparison for the plan's.
1095///
1096/// A translation rather than one shared enum, because the kernels are rank 3 and the plan is rank
1097/// 9. This function is the whole of what that separation costs.
1098pub(crate) fn comparison(op: CompareOp) -> Comparison {
1099    match op {
1100        CompareOp::Equal => Comparison::Equal,
1101        CompareOp::NotEqual => Comparison::NotEqual,
1102        CompareOp::Less => Comparison::Less,
1103        CompareOp::LessOrEqual => Comparison::LessOrEqual,
1104        CompareOp::Greater => Comparison::Greater,
1105        CompareOp::GreaterOrEqual => Comparison::GreaterOrEqual,
1106        CompareOp::DistinctFrom => Comparison::DistinctFrom,
1107        CompareOp::NotDistinctFrom => Comparison::NotDistinctFrom,
1108    }
1109}
1110
1111/// The kernels' connective for the plan's.
1112pub(crate) fn connective(op: ConjunctionOp) -> Connective {
1113    match op {
1114        ConjunctionOp::And => Connective::And,
1115        ConjunctionOp::Or => Connective::Or,
1116    }
1117}
1118
1119#[cfg(test)]
1120mod tests {
1121    use rudb_common::{Field, LogicalType, Value};
1122    use rudb_kernels::is_true;
1123    use rudb_plan::{ExprRef, Node, Plan};
1124    use rudb_vector::{Chunk, Selection, Vector};
1125
1126    use super::{Prepared, narrow};
1127    use crate::expr::evaluate;
1128    use crate::schema::Schema;
1129
1130    /// Two columns with a null in each, because every disagreement between these two evaluators
1131    /// that is worth finding is a disagreement about which rows are null.
1132    fn input() -> (Schema, Chunk) {
1133        let schema = Schema::numbered(
1134            vec![Field::new("x", LogicalType::Integer), Field::new("s", LogicalType::Varchar)],
1135            0,
1136        );
1137        let x = Vector::from_values(
1138            LogicalType::Integer,
1139            &[Value::Integer(3), Value::Integer(1), Value::Null, Value::Integer(2)],
1140        )
1141        .expect("four integers");
1142        let s = Vector::from_values(
1143            LogicalType::Varchar,
1144            &[
1145                Value::Varchar("a".to_string()),
1146                Value::Null,
1147                Value::Varchar("c".to_string()),
1148                Value::Varchar("a".to_string()),
1149            ],
1150        )
1151        .expect("four strings");
1152        (schema, Chunk::new(vec![x, s]).expect("two columns of four rows"))
1153    }
1154
1155    /// The expressions of a projection written in the plan's textual form, over the two columns
1156    /// [`input`] produces.
1157    ///
1158    /// Going through the text rather than the arena builders for the reason the other test module
1159    /// gives: a test that says what it evaluates in the notation a plan dump uses is a test whose
1160    /// failure can be pasted into a plan and vice versa.
1161    fn projection(exprs: &str) -> (Plan, Vec<ExprRef>) {
1162        let text =
1163            format!("Project #1 [{exprs}]\n  Get memory.main.t AS t #0 [x::INTEGER, s::VARCHAR]");
1164        let plan = Plan::parse(&text).expect("a well formed plan");
1165        let Node::Project { exprs, .. } = *plan.node(plan.root()) else {
1166            panic!("the root of that text is a projection");
1167        };
1168        let list = plan.expr_list(exprs).to_vec();
1169        (plan, list)
1170    }
1171
1172    /// Every expression shape, evaluated both ways over the same chunk.
1173    ///
1174    /// This is the agreement the module documentation claims and it is the only thing that makes
1175    /// the prepared form safe to put in front of the tree walk. The generated well typed trees the
1176    /// test gate of #57 asks for are a wider version of this and are worth building once the
1177    /// selection threaded shapes exist to disagree about.
1178    fn agrees(exprs: &str) {
1179        let (schema, chunk) = input();
1180        let (plan, list) = projection(exprs);
1181        let prepared = Prepared::new(&plan, &list, &schema).expect("the expressions resolve");
1182        let mut scratch = prepared.scratch();
1183        let mut fast = Vec::new();
1184        prepared.evaluate(&chunk, &mut scratch, &mut fast).expect("the prepared form runs");
1185        for (at, &expr) in list.iter().enumerate() {
1186            let slow = evaluate(&plan, expr, &schema, &chunk).expect("the tree walk runs");
1187            for row in 0..chunk.len() {
1188                assert_eq!(
1189                    fast[at].value_at(row),
1190                    slow.value_at(row),
1191                    "expression {at} of `{exprs}` at row {row}"
1192                );
1193            }
1194        }
1195    }
1196
1197    #[test]
1198    fn a_column_reference_agrees() {
1199        agrees("#0.0::INTEGER AS a, #0.1::VARCHAR AS b");
1200    }
1201
1202    #[test]
1203    fn a_constant_agrees() {
1204        agrees("7::INTEGER AS a, NULL::INTEGER AS b");
1205    }
1206
1207    #[test]
1208    fn a_cast_agrees() {
1209        agrees("CAST(#0.0::INTEGER)::BIGINT AS a, CAST(#0.0::INTEGER)::VARCHAR AS b");
1210    }
1211
1212    #[test]
1213    fn a_comparison_agrees() {
1214        agrees("(#0.0::INTEGER > 1::INTEGER)::BOOLEAN AS a");
1215    }
1216
1217    #[test]
1218    fn a_conjunction_agrees() {
1219        agrees(
1220            "((#0.0::INTEGER > 1::INTEGER)::BOOLEAN AND (#0.0::INTEGER < 3::INTEGER)::BOOLEAN)\
1221             ::BOOLEAN AS a",
1222        );
1223    }
1224
1225    #[test]
1226    fn a_function_agrees() {
1227        agrees("\"+\"(#0.0::INTEGER, 1::INTEGER)::INTEGER AS a");
1228    }
1229
1230    /// The two evaluators quote the same expression when a divisor is zero. Per #262.
1231    ///
1232    /// This is the one message in the engine that depends on how an expression is written rather
1233    /// than on what it computes, and the two evaluators render it at different times: the prepared
1234    /// form when the pipeline is built, the tree walk on the row that fails. Same renderer, so the
1235    /// same sentence, and this is what says so.
1236    #[test]
1237    fn both_evaluators_quote_the_same_expression_when_a_divisor_is_zero() {
1238        let (schema, chunk) = input();
1239        let (plan, list) = projection("\"//\"(#0.0::INTEGER, 0::INTEGER)::INTEGER AS a");
1240        let prepared = Prepared::new(&plan, &list, &schema).expect("the expression resolves");
1241        let mut scratch = prepared.scratch();
1242        let mut out = Vec::new();
1243        let fast = prepared.evaluate(&chunk, &mut scratch, &mut out).expect_err("divides by zero");
1244        let slow = evaluate(&plan, list[0], &schema, &chunk).expect_err("divides by zero");
1245        assert_eq!(fast.message(), slow.message());
1246        assert!(fast.message().starts_with("Division by zero in expression (x // 0)."), "{fast}");
1247    }
1248
1249    #[test]
1250    fn a_case_agrees() {
1251        agrees(
1252            "CASE WHEN (#0.0::INTEGER > 1::INTEGER)::BOOLEAN THEN 10::INTEGER \
1253             ELSE 20::INTEGER END::INTEGER AS a",
1254        );
1255    }
1256
1257    /// The same expression twice, which is where the tree walk copies the column twice and this
1258    /// does not, and the answers still have to be identical.
1259    #[test]
1260    fn a_column_mentioned_three_times_agrees() {
1261        agrees("\"+\"(\"+\"(#0.0::INTEGER, #0.0::INTEGER)::INTEGER, #0.0::INTEGER)::INTEGER AS a");
1262    }
1263
1264    /// The intermediates of a chain are not all held to the end of it.
1265    ///
1266    /// This is the whole difference between the prepared form being faster than the tree walk on a
1267    /// deep chain and being slower than it, and it is a property of the slot array rather than of
1268    /// any answer, so it is asserted here rather than left to the benchmark to catch.
1269    #[test]
1270    fn a_chain_holds_one_intermediate_at_a_time() {
1271        let (schema, chunk) = input();
1272        let mut expr = "#0.0::INTEGER".to_string();
1273        for _ in 0..8 {
1274            expr = format!("\"+\"({expr}, 1::INTEGER)::INTEGER");
1275        }
1276        let (plan, list) = projection(&format!("{expr} AS a"));
1277        let prepared = Prepared::new(&plan, &list, &schema).expect("the chain resolves");
1278        let mut scratch = prepared.scratch();
1279        prepared.run(&chunk, &mut scratch).expect("the chain runs");
1280        let live = scratch.slots.iter().filter(|slot| slot.is_some()).count();
1281        assert_eq!(live, 1, "a chain that has run should be holding its answer and nothing else");
1282    }
1283
1284    /// The rows a threaded filter keeps are the rows the tree walk says the predicate is true for.
1285    ///
1286    /// Every threaded conjunct is a chance to disagree with the unthreaded answer about a null,
1287    /// about a row an earlier conjunct had already dropped, or about a chunk nothing survives, and
1288    /// the answer is a set of row numbers rather than a vector, so this is checked against the tree
1289    /// walk read a row at a time rather than against the prepared form it is part of.
1290    fn filters(predicate: &str) {
1291        let (schema, chunk) = input();
1292        let (plan, list) = projection(&format!("{predicate} AS p"));
1293        let prepared = Prepared::new(&plan, &list, &schema).expect("the predicate resolves");
1294        let mut scratch = prepared.scratch();
1295        let threaded = prepared.evaluate_filter(&chunk, &mut scratch).expect("the filter runs");
1296        let flags = evaluate(&plan, list[0], &schema, &chunk).expect("the tree walk runs");
1297        let expected = Selection::from_predicate(chunk.len(), |row| is_true(&flags.value_at(row)));
1298        assert_eq!(threaded, expected, "`{predicate}`");
1299        // And running it again over the same scratch is the same answer, because a pipeline calls
1300        // this once a chunk and a slot left behind by the conjunct before would show up here.
1301        let again = prepared.evaluate_filter(&chunk, &mut scratch).expect("the filter runs again");
1302        assert_eq!(again, expected, "`{predicate}` a second time");
1303    }
1304
1305    /// A predicate with no `AND` in it is not threaded and has to keep saying the same thing.
1306    #[test]
1307    fn a_single_comparison_filters_the_same_rows() {
1308        filters("(#0.0::INTEGER > 1::INTEGER)::BOOLEAN");
1309        filters("(#0.1::VARCHAR = 'a'::VARCHAR)::BOOLEAN");
1310        filters("(#0.0::INTEGER IS NOT DISTINCT FROM NULL::INTEGER)::BOOLEAN");
1311    }
1312
1313    #[test]
1314    fn a_chain_of_conjuncts_keeps_what_all_of_them_keep() {
1315        filters(
1316            "((#0.0::INTEGER > 1::INTEGER)::BOOLEAN AND (#0.0::INTEGER < 3::INTEGER)::BOOLEAN)\
1317             ::BOOLEAN",
1318        );
1319        filters(
1320            "((#0.0::INTEGER >= 1::INTEGER)::BOOLEAN AND (#0.0::INTEGER <= 3::INTEGER)::BOOLEAN \
1321             AND (#0.1::VARCHAR = 'a'::VARCHAR)::BOOLEAN AND (#0.0::INTEGER <> 2::INTEGER)\
1322             ::BOOLEAN)::BOOLEAN",
1323        );
1324    }
1325
1326    /// A conjunct that rejects every row, in front of one that would have kept some. The rows are
1327    /// the same either way and the point of the shape is that the second conjunct never runs.
1328    #[test]
1329    fn a_conjunct_that_keeps_nothing_ends_the_predicate() {
1330        filters(
1331            "((#0.0::INTEGER > 9::INTEGER)::BOOLEAN AND (#0.0::INTEGER < 9::INTEGER)::BOOLEAN)\
1332             ::BOOLEAN",
1333        );
1334    }
1335
1336    /// A conjunct whose operands are computed rather than read, which is the shape where the
1337    /// comparison is threaded and the arithmetic under it is not.
1338    #[test]
1339    fn a_conjunct_over_a_computed_operand_keeps_the_same_rows() {
1340        filters(
1341            "((#0.0::INTEGER > 1::INTEGER)::BOOLEAN AND \
1342             (\"+\"(#0.0::INTEGER, 1::INTEGER)::INTEGER < 4::INTEGER)::BOOLEAN)::BOOLEAN",
1343        );
1344    }
1345
1346    /// A conjunct that is not a comparison at all, which is the one that goes through the flag
1347    /// kernel rather than the comparison kernel.
1348    #[test]
1349    fn a_conjunct_that_is_not_a_comparison_is_threaded_too() {
1350        filters(
1351            "((#0.0::INTEGER > 1::INTEGER)::BOOLEAN AND ((#0.1::VARCHAR = 'a'::VARCHAR)::BOOLEAN \
1352             OR (#0.0::INTEGER = 1::INTEGER)::BOOLEAN)::BOOLEAN)::BOOLEAN",
1353        );
1354        filters(
1355            "(((#0.1::VARCHAR = 'c'::VARCHAR)::BOOLEAN OR (#0.0::INTEGER = 3::INTEGER)::BOOLEAN)\
1356             ::BOOLEAN AND (#0.0::INTEGER <> 1::INTEGER)::BOOLEAN)::BOOLEAN",
1357        );
1358    }
1359
1360    /// An `OR` at the top threads the complement: the second branch only sees the rows the first
1361    /// one did not accept, and the rows it accepts are added to them rather than replacing them.
1362    ///
1363    /// The input has a row where the first branch is true, one where the second is, one where both
1364    /// are false and one where the first is null and the second is true, which is the row that says
1365    /// whether the complement was taken over "not true" or over "false".
1366    #[test]
1367    fn an_or_at_the_top_threads_the_complement() {
1368        filters(
1369            "((#0.0::INTEGER > 2::INTEGER)::BOOLEAN OR (#0.1::VARCHAR = 'c'::VARCHAR)::BOOLEAN)\
1370             ::BOOLEAN",
1371        );
1372        filters(
1373            "((#0.0::INTEGER = 1::INTEGER)::BOOLEAN OR (#0.1::VARCHAR = 'a'::VARCHAR)::BOOLEAN \
1374             OR (#0.0::INTEGER > 2::INTEGER)::BOOLEAN)::BOOLEAN",
1375        );
1376    }
1377
1378    /// A branch that accepts every row, in front of one that would have accepted none. The rows are
1379    /// the same either way and the point of the shape is that the second branch never runs.
1380    #[test]
1381    fn a_branch_that_keeps_everything_ends_the_predicate() {
1382        filters(
1383            "((#0.0::INTEGER IS NOT DISTINCT FROM #0.0::INTEGER)::BOOLEAN OR \
1384             (#0.0::INTEGER > 9::INTEGER)::BOOLEAN)::BOOLEAN",
1385        );
1386    }
1387
1388    /// The branches after one that has accepted every row really are skipped.
1389    ///
1390    /// Every other test here says the threaded answer matches the unthreaded one, which it would
1391    /// even if nothing were threaded at all. This one puts a division by zero behind a branch that
1392    /// accepts everything, so the predicate raises if the second branch runs and does not if the
1393    /// walk stopped where it was supposed to.
1394    #[test]
1395    fn a_branch_behind_one_that_accepted_every_row_does_not_run() {
1396        let (schema, chunk) = input();
1397        let predicate = "((#0.0::INTEGER IS NOT DISTINCT FROM #0.0::INTEGER)::BOOLEAN OR \
1398                         (\"//\"(#0.0::INTEGER, 0::INTEGER)::INTEGER > 0::INTEGER)::BOOLEAN)\
1399                         ::BOOLEAN";
1400        let (plan, list) = projection(&format!("{predicate} AS p"));
1401        let prepared = Prepared::new(&plan, &list, &schema).expect("the predicate resolves");
1402        let mut scratch = prepared.scratch();
1403        let kept =
1404            prepared.evaluate_filter(&chunk, &mut scratch).expect("the second branch never runs");
1405        assert_eq!(kept, Selection::identity(chunk.len()));
1406        // And the same predicate evaluated as an expression does divide by zero, which is what says
1407        // the test is testing the threading rather than a predicate that happens not to raise.
1408        evaluate(&plan, list[0], &schema, &chunk).expect_err("the tree walk divides by zero");
1409    }
1410
1411    /// The conjunct that rejects the most rows ends up in front of the one that rejects none.
1412    ///
1413    /// The predicate is written the wrong way round on purpose. The plan order costs two passes a
1414    /// chunk where one would do, and after a chunk of watching it the filter runs the selective one
1415    /// first and the other one stops running at all.
1416    #[test]
1417    fn a_filter_learns_which_conjunct_to_run_first() {
1418        let (schema, chunk) = input();
1419        let predicate = "((#0.0::INTEGER > 0::INTEGER)::BOOLEAN AND (#0.0::INTEGER > 9::INTEGER)\
1420                         ::BOOLEAN)::BOOLEAN";
1421        let (plan, list) = projection(&format!("{predicate} AS p"));
1422        let prepared = Prepared::new(&plan, &list, &schema).expect("the predicate resolves");
1423        let mut scratch = prepared.scratch();
1424        let root = prepared.roots[0];
1425        assert_eq!(scratch.order(root), None, "nothing has run yet");
1426        let kept = prepared.evaluate_filter(&chunk, &mut scratch).expect("the filter runs");
1427        assert!(kept.is_empty());
1428        assert_eq!(scratch.order(root), Some(&[1, 0][..]), "the second conjunct rejects the most");
1429        // And it stays there, because the conjunct that now runs first empties the selection and
1430        // the one behind it keeps the history it already had rather than losing it.
1431        let kept = prepared.evaluate_filter(&chunk, &mut scratch).expect("the filter runs again");
1432        assert!(kept.is_empty());
1433        assert_eq!(scratch.order(root), Some(&[1, 0][..]));
1434    }
1435
1436    /// Whatever order it settles on, the rows are the rows.
1437    ///
1438    /// Run for longer than the window is wide, because an order that changes halfway through a scan
1439    /// is the shape where a walk that got the subtree bookkeeping wrong would start reading the
1440    /// wrong steps, and the first chunk would not show it.
1441    #[test]
1442    fn reordering_never_changes_which_rows_survive() {
1443        let (schema, chunk) = input();
1444        let predicate = "((#0.0::INTEGER >= 1::INTEGER)::BOOLEAN AND \
1445                         (\"+\"(#0.0::INTEGER, 1::INTEGER)::INTEGER < 4::INTEGER)::BOOLEAN AND \
1446                         (#0.1::VARCHAR = 'a'::VARCHAR)::BOOLEAN)::BOOLEAN";
1447        let (plan, list) = projection(&format!("{predicate} AS p"));
1448        let prepared = Prepared::new(&plan, &list, &schema).expect("the predicate resolves");
1449        let mut scratch = prepared.scratch();
1450        let flags = evaluate(&plan, list[0], &schema, &chunk).expect("the tree walk runs");
1451        let expected = Selection::from_predicate(chunk.len(), |row| is_true(&flags.value_at(row)));
1452        for round in 0..40 {
1453            let kept = prepared.evaluate_filter(&chunk, &mut scratch).expect("the filter runs");
1454            assert_eq!(kept, expected, "round {round}");
1455        }
1456    }
1457
1458    /// A nested connective is threaded rather than evaluated into flags.
1459    ///
1460    /// The inner `AND` keeps nothing, so its second conjunct is never reached and the division by
1461    /// zero in it never happens. Evaluating the branch as an expression and narrowing the flags
1462    /// afterwards, which is what an operand that is not a connective still does, would have run it.
1463    #[test]
1464    fn a_nested_connective_stops_where_the_outer_one_would() {
1465        let (schema, chunk) = input();
1466        let predicate = "((#0.0::INTEGER > 9::INTEGER)::BOOLEAN OR ((#0.0::INTEGER > 9::INTEGER)\
1467                         ::BOOLEAN AND (\"//\"(#0.0::INTEGER, 0::INTEGER)::INTEGER > 0::INTEGER)\
1468                         ::BOOLEAN)::BOOLEAN)::BOOLEAN";
1469        let (plan, list) = projection(&format!("{predicate} AS p"));
1470        let prepared = Prepared::new(&plan, &list, &schema).expect("the predicate resolves");
1471        let mut scratch = prepared.scratch();
1472        let kept =
1473            prepared.evaluate_filter(&chunk, &mut scratch).expect("the division never happens");
1474        assert!(kept.is_empty());
1475        evaluate(&plan, list[0], &schema, &chunk).expect_err("the tree walk divides by zero");
1476    }
1477
1478    /// A branch that is not a comparison, which is the one that goes through the flag kernel.
1479    #[test]
1480    fn an_or_branch_that_is_not_a_comparison_is_threaded_too() {
1481        filters(
1482            "((#0.0::INTEGER > 2::INTEGER)::BOOLEAN OR \
1483             \"~~\"(#0.1::VARCHAR, 'a%'::VARCHAR)::BOOLEAN)::BOOLEAN",
1484        );
1485        filters(
1486            "(\"~~\"(#0.1::VARCHAR, 'c%'::VARCHAR)::BOOLEAN OR (#0.0::INTEGER = 1::INTEGER)\
1487             ::BOOLEAN)::BOOLEAN",
1488        );
1489    }
1490
1491    /// A connective inside a connective, which recurses rather than falling back to flags.
1492    ///
1493    /// Both nestings, because the two carry opposite things: an `AND` under an `OR` starts from the
1494    /// rows no branch has accepted, and an `OR` under an `AND` starts from the rows every conjunct
1495    /// has kept, and getting either one backwards is a wrong set of rows.
1496    #[test]
1497    fn a_connective_inside_a_connective_threads_both_ways() {
1498        filters(
1499            "(((#0.0::INTEGER >= 2::INTEGER)::BOOLEAN AND (#0.1::VARCHAR = 'a'::VARCHAR)::BOOLEAN)\
1500             ::BOOLEAN OR ((#0.0::INTEGER < 2::INTEGER)::BOOLEAN AND (#0.1::VARCHAR <> 'c'\
1501             ::VARCHAR)::BOOLEAN)::BOOLEAN)::BOOLEAN",
1502        );
1503        filters(
1504            "(((#0.1::VARCHAR = 'c'::VARCHAR)::BOOLEAN OR (#0.0::INTEGER = 3::INTEGER)::BOOLEAN)\
1505             ::BOOLEAN AND ((#0.0::INTEGER <> 1::INTEGER)::BOOLEAN OR (#0.1::VARCHAR = 'a'\
1506             ::VARCHAR)::BOOLEAN)::BOOLEAN)::BOOLEAN",
1507        );
1508        // Three deep, since two levels is where an off by one in the subtree bookkeeping can still
1509        // be hidden by the ranges lining up.
1510        filters(
1511            "((#0.0::INTEGER > 9::INTEGER)::BOOLEAN OR ((#0.0::INTEGER >= 1::INTEGER)::BOOLEAN \
1512             AND ((#0.1::VARCHAR = 'a'::VARCHAR)::BOOLEAN OR (#0.0::INTEGER = 1::INTEGER)\
1513             ::BOOLEAN)::BOOLEAN)::BOOLEAN)::BOOLEAN",
1514        );
1515    }
1516
1517    /// A predicate where one side is null and the other is true, in both orders. `OR` is true there
1518    /// and a complement taken over the rows a branch rejected rather than the rows it accepted
1519    /// would drop the row, which is the one way this can be wrong and is not a wrong vector but a
1520    /// missing row.
1521    #[test]
1522    fn a_null_branch_beside_a_true_one_keeps_the_row() {
1523        filters(
1524            "((#0.0::INTEGER > 2::INTEGER)::BOOLEAN OR (#0.1::VARCHAR = 'c'::VARCHAR)::BOOLEAN \
1525             OR (#0.0::INTEGER IS NOT DISTINCT FROM NULL::INTEGER)::BOOLEAN)::BOOLEAN",
1526        );
1527        filters(
1528            "((#0.1::VARCHAR > 'b'::VARCHAR)::BOOLEAN OR (#0.0::INTEGER = 1::INTEGER)::BOOLEAN)\
1529             ::BOOLEAN",
1530        );
1531    }
1532
1533    /// A filter over a chunk that has already been narrowed, which is what a second filter in a
1534    /// pipeline sees and is the form pair the threaded kernels have to handle rather than fall
1535    /// through on.
1536    #[test]
1537    fn a_filter_over_a_selected_chunk_keeps_the_same_rows() {
1538        let (schema, chunk) = input();
1539        let predicate = "((#0.0::INTEGER >= 1::INTEGER)::BOOLEAN AND \
1540                         (#0.1::VARCHAR = 'a'::VARCHAR)::BOOLEAN)::BOOLEAN";
1541        let (plan, list) = projection(&format!("{predicate} AS p"));
1542        let prepared = Prepared::new(&plan, &list, &schema).expect("the predicate resolves");
1543        let mut scratch = prepared.scratch();
1544        let narrowed = narrow(&chunk, &[0, 3]).expect("two of the four rows");
1545        let threaded = prepared.evaluate_filter(&narrowed, &mut scratch).expect("the filter runs");
1546        let flags = evaluate(&plan, list[0], &schema, &narrowed).expect("the tree walk runs");
1547        let expected =
1548            Selection::from_predicate(narrowed.len(), |row| is_true(&flags.value_at(row)));
1549        assert_eq!(threaded, expected);
1550    }
1551
1552    /// Preparing is per pipeline and evaluating is per chunk, so the scratch has to survive being
1553    /// used again and give the same answer the second time.
1554    #[test]
1555    fn a_scratch_used_twice_gives_the_same_answer_twice() {
1556        let (schema, chunk) = input();
1557        let (plan, list) = projection("\"+\"(#0.0::INTEGER, 1::INTEGER)::INTEGER AS a");
1558        let prepared = Prepared::new(&plan, &list, &schema).expect("the expressions resolve");
1559        let mut scratch = prepared.scratch();
1560        let mut once = Vec::new();
1561        prepared.evaluate(&chunk, &mut scratch, &mut once).expect("the first chunk runs");
1562        let mut twice = Vec::new();
1563        prepared.evaluate(&chunk, &mut scratch, &mut twice).expect("the second chunk runs");
1564        assert_eq!(once, twice);
1565    }
1566
1567    #[test]
1568    fn a_shared_computed_root_is_compiled_once() {
1569        let (schema, chunk) = input();
1570        let (plan, list) = projection("\"+\"(#0.0::INTEGER, 1::INTEGER)::INTEGER AS a");
1571        let prepared = Prepared::shared(&plan, &[list[0], list[0]], &schema)
1572            .expect("the shared expression resolves");
1573        assert_eq!(prepared.steps.len(), 3);
1574        let mut scratch = prepared.scratch();
1575        let mut answers = Vec::new();
1576        prepared.evaluate(&chunk, &mut scratch, &mut answers).expect("both roots are returned");
1577        assert_eq!(answers[0], answers[1]);
1578    }
1579
1580    /// A chunk shorter than the last one, because a scan's final chunk is that and a constant
1581    /// materialized to the wrong length would be an out of range read rather than a wrong answer.
1582    #[test]
1583    fn a_shorter_chunk_after_a_longer_one_is_evaluated_at_its_own_length() {
1584        let (schema, chunk) = input();
1585        let (plan, list) = projection("7::INTEGER AS a");
1586        let prepared = Prepared::new(&plan, &list, &schema).expect("the expressions resolve");
1587        let mut scratch = prepared.scratch();
1588        let mut full = Vec::new();
1589        prepared.evaluate(&chunk, &mut scratch, &mut full).expect("the full chunk runs");
1590        assert_eq!(full[0].len(), 4);
1591        let short = chunk
1592            .clone()
1593            .select(&{
1594                let mut selection = Selection::with_capacity(2);
1595                selection.push(0);
1596                selection.push(2);
1597                selection
1598            })
1599            .expect("two of the four rows");
1600        let mut cut = Vec::new();
1601        prepared.evaluate(&short, &mut scratch, &mut cut).expect("the short chunk runs");
1602        assert_eq!(cut[0].len(), 2);
1603    }
1604
1605    /// An aggregate is not an expression and saying so when the pipeline is built is better than
1606    /// saying it on the first chunk.
1607    #[test]
1608    fn an_aggregate_is_refused_when_it_is_prepared() {
1609        let (schema, _) = input();
1610        let text = "Aggregate #1 groups=[] aggregates=[sum(#0.0::INTEGER)::HUGEINT]\n  \
1611                    Get memory.main.t AS t #0 [x::INTEGER, s::VARCHAR]";
1612        let plan = Plan::parse(text).expect("a well formed plan");
1613        let Node::Aggregate { aggregates, .. } = *plan.node(plan.root()) else {
1614            panic!("the root of that text is an aggregate");
1615        };
1616        let list = plan.expr_list(aggregates).to_vec();
1617        let error = Prepared::new(&plan, &list, &schema).expect_err("sum is not a scalar");
1618        assert!(error.message().contains("sum"), "{error}");
1619    }
1620
1621    /// How many of an expression's function steps worked something out when it was prepared, and
1622    /// whether the answer it gives is still the tree walk's answer.
1623    ///
1624    /// The count is the point of the assertion, because an answer that moved would be a bug. The
1625    /// agreement is what says the answer did not move.
1626    fn prepares(expr: &str, lifted: usize) {
1627        let (schema, _) = input();
1628        let projected = format!("{expr} AS a");
1629        let (plan, list) = projection(&projected);
1630        let prepared = Prepared::new(&plan, &list, &schema).expect("the expression resolves");
1631        assert_eq!(prepared.hoisted(), lifted, "`{expr}`");
1632        agrees(&projected);
1633    }
1634
1635    /// A pattern the user wrote is compiled where the plan is, which is once.
1636    #[test]
1637    fn a_literal_pattern_is_compiled_when_the_pipeline_is_built() {
1638        prepares("\"~~\"(#0.1::VARCHAR, 'a%'::VARCHAR)::BOOLEAN", 1);
1639        prepares("\"~~*\"(#0.1::VARCHAR, '%A%'::VARCHAR)::BOOLEAN", 1);
1640    }
1641
1642    /// A regular expression, which is the one where the compiling is worth real time.
1643    ///
1644    /// ClickBench query 29 runs one pattern over a hundred million rows, which is a hundred thousand
1645    /// chunks, and before this each of those hundred thousand compiled the pattern again.
1646    #[test]
1647    fn a_regular_expression_is_compiled_when_the_pipeline_is_built() {
1648        prepares("\"regexp_matches\"(#0.1::VARCHAR, '^a'::VARCHAR)::BOOLEAN", 1);
1649        prepares("\"regexp_replace\"(#0.1::VARCHAR, 'a'::VARCHAR, 'b'::VARCHAR)::VARCHAR", 1);
1650    }
1651
1652    /// A pattern that is not a literal, which is legal SQL and is decided per chunk as it was.
1653    #[test]
1654    fn a_pattern_that_is_not_a_literal_is_left_to_the_chunk() {
1655        prepares("\"~~\"(#0.1::VARCHAR, #0.1::VARCHAR)::BOOLEAN", 0);
1656    }
1657
1658    /// A function with nothing to work out, which is almost all of them.
1659    #[test]
1660    fn a_function_with_no_prepare_step_prepares_nothing() {
1661        prepares("\"upper\"(#0.1::VARCHAR)::VARCHAR", 0);
1662    }
1663
1664    /// How many of an expression's steps are a folded `IN`, and whether the answer still agrees.
1665    fn folds(expr: &str, sets: usize) {
1666        let (schema, _) = input();
1667        let projected = format!("{expr} AS a");
1668        let (plan, list) = projection(&projected);
1669        let prepared = Prepared::new(&plan, &list, &schema).expect("the expression resolves");
1670        assert_eq!(prepared.sets(), sets, "`{expr}`");
1671        agrees(&projected);
1672    }
1673
1674    /// What the binder writes for `x IN (1, 3)`, folded back into one lookup.
1675    ///
1676    /// The test goes through the plan's text, where the three mentions of the column are three
1677    /// expressions rather than one, which is the case `same` exists for. A plan the binder built has
1678    /// one mention and takes the first line of it.
1679    #[test]
1680    fn an_in_list_becomes_one_lookup() {
1681        folds(
1682            "((#0.0::INTEGER = 1::INTEGER)::BOOLEAN OR (#0.0::INTEGER = 3::INTEGER)::BOOLEAN)\
1683             ::BOOLEAN",
1684            1,
1685        );
1686        folds(
1687            "((#0.1::VARCHAR = 'a'::VARCHAR)::BOOLEAN OR (#0.1::VARCHAR = 'z'::VARCHAR)::BOOLEAN)\
1688             ::BOOLEAN",
1689            1,
1690        );
1691    }
1692
1693    /// `NOT IN`, which the binder writes as an `AND` of inequalities and which reads the same
1694    /// lookup the other way round.
1695    #[test]
1696    fn a_not_in_list_becomes_the_same_lookup() {
1697        folds(
1698            "((#0.0::INTEGER <> 1::INTEGER)::BOOLEAN AND (#0.0::INTEGER <> 3::INTEGER)::BOOLEAN)\
1699             ::BOOLEAN",
1700            1,
1701        );
1702    }
1703
1704    /// A list with a null in it, which is the rule that makes an `IN` not a set lookup.
1705    ///
1706    /// A row that is not in the list is null rather than false, because it might have equalled the
1707    /// value the null stands for. `agrees` is what says the fold kept that, since the `OR` of
1708    /// comparisons it is checked against gets it from three valued logic for free.
1709    #[test]
1710    fn a_list_with_a_null_in_it_folds_and_keeps_the_null_rule() {
1711        folds(
1712            "((#0.0::INTEGER = 1::INTEGER)::BOOLEAN OR (#0.0::INTEGER = NULL::INTEGER)::BOOLEAN \
1713             OR (#0.0::INTEGER = 3::INTEGER)::BOOLEAN)::BOOLEAN",
1714            1,
1715        );
1716        folds(
1717            "((#0.0::INTEGER <> 1::INTEGER)::BOOLEAN AND (#0.0::INTEGER <> NULL::INTEGER)\
1718             ::BOOLEAN AND (#0.0::INTEGER <> 3::INTEGER)::BOOLEAN)::BOOLEAN",
1719            1,
1720        );
1721    }
1722
1723    /// The connectives that are not an `IN`, each for its own reason.
1724    #[test]
1725    fn a_connective_that_is_not_an_in_list_is_left_alone() {
1726        // Two different columns.
1727        folds(
1728            "((#0.0::INTEGER = 1::INTEGER)::BOOLEAN OR (#0.1::VARCHAR = 'a'::VARCHAR)::BOOLEAN)\
1729             ::BOOLEAN",
1730            0,
1731        );
1732        // One equality and one of something else.
1733        folds(
1734            "((#0.0::INTEGER = 1::INTEGER)::BOOLEAN OR (#0.0::INTEGER > 3::INTEGER)::BOOLEAN)\
1735             ::BOOLEAN",
1736            0,
1737        );
1738        // The right hand side is a column rather than a literal.
1739        folds(
1740            "((#0.0::INTEGER = 1::INTEGER)::BOOLEAN OR (#0.0::INTEGER = #0.0::INTEGER)::BOOLEAN)\
1741             ::BOOLEAN",
1742            0,
1743        );
1744        // An `AND` of equalities is not a `NOT IN`, it is a predicate that is false unless the two
1745        // literals are the same. Folding it as one would answer true where it answers false.
1746        folds(
1747            "((#0.0::INTEGER = 1::INTEGER)::BOOLEAN AND (#0.0::INTEGER = 3::INTEGER)::BOOLEAN)\
1748             ::BOOLEAN",
1749            0,
1750        );
1751    }
1752
1753    /// The same thing in a filter, which is the shape it is written in.
1754    #[test]
1755    fn an_in_list_filters_the_same_rows() {
1756        filters(
1757            "((#0.0::INTEGER = 1::INTEGER)::BOOLEAN OR (#0.0::INTEGER = 3::INTEGER)::BOOLEAN)\
1758             ::BOOLEAN",
1759        );
1760        filters(
1761            "((#0.0::INTEGER <> 1::INTEGER)::BOOLEAN AND (#0.0::INTEGER <> 3::INTEGER)::BOOLEAN)\
1762             ::BOOLEAN",
1763        );
1764        // Inside a larger predicate, where the fold is one operand of the connective above it.
1765        filters(
1766            "(((#0.0::INTEGER = 1::INTEGER)::BOOLEAN OR (#0.0::INTEGER = 3::INTEGER)::BOOLEAN)\
1767             ::BOOLEAN AND (#0.1::VARCHAR = 'a'::VARCHAR)::BOOLEAN)::BOOLEAN",
1768        );
1769    }
1770
1771    /// The literal side of a comparison is turned into a column when the pipeline is built.
1772    #[test]
1773    fn a_comparison_against_a_literal_builds_it_once() {
1774        let (schema, _) = input();
1775        for (expr, built) in [
1776            ("(#0.1::VARCHAR = 'a'::VARCHAR)::BOOLEAN AS p", 1),
1777            ("(#0.0::INTEGER > 1::INTEGER)::BOOLEAN AS p", 1),
1778            // The literal on the left, which is the same comparison written the other way round.
1779            ("(1::INTEGER < #0.0::INTEGER)::BOOLEAN AS p", 1),
1780            // Two columns, which has no literal side to build.
1781            ("(#0.0::INTEGER = #0.0::INTEGER)::BOOLEAN AS p", 0),
1782            // Two literals, which the kernel answers once for the whole vector without reading a
1783            // column, so building one would be work that nothing reads.
1784            ("(1::INTEGER = 2::INTEGER)::BOOLEAN AS p", 0),
1785        ] {
1786            let (plan, list) = projection(expr);
1787            let prepared = Prepared::new(&plan, &list, &schema).expect("the expression resolves");
1788            assert_eq!(prepared.literals_built(), built, "`{expr}`");
1789            agrees(expr);
1790        }
1791    }
1792
1793    /// A pattern that does not compile still fails where the query said it does.
1794    ///
1795    /// Preparing is not allowed to move an error earlier. Compiling at build time and reporting
1796    /// there would raise before a row had been read, and under a `CASE` arm it would raise on a
1797    /// query whose rows never reach the call at all.
1798    #[test]
1799    fn a_pattern_that_does_not_compile_fails_on_the_chunk_and_not_before() {
1800        let (schema, chunk) = input();
1801        let (plan, list) =
1802            projection("\"regexp_matches\"(#0.1::VARCHAR, 'a('::VARCHAR)::BOOLEAN AS a");
1803        let prepared = Prepared::new(&plan, &list, &schema).expect("preparing does not compile it");
1804        assert_eq!(prepared.hoisted(), 0);
1805        let mut scratch = prepared.scratch();
1806        let mut out = Vec::new();
1807        prepared.evaluate(&chunk, &mut scratch, &mut out).expect_err("the chunk raises");
1808    }
1809}