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