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