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