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        // Straight to the rows it keeps, and only among the ones still in play, where the list and
879        // the column allow it. See [`rudb_kernels::select_in`].
880        if let Step::InSet { input, members } = &self.steps[index] {
881            let column = self.operand(*input, chunk, &scratch.slots)?;
882            if let Some(kept) = rudb_kernels::select_in(column, members, live) {
883                return Ok(kept);
884            }
885        }
886        if let Step::Compare { op, left, right, held } = &self.steps[index] {
887            let one = self.operand(*left, chunk, &scratch.slots)?;
888            let other = self.operand(*right, chunk, &scratch.slots)?;
889            let held = held.as_ref();
890            return match live {
891                // The first operand has every row in play, and asking the threaded kernel for that
892                // would be a pass over an identity selection the unthreaded one does not need.
893                None => select_prepared(*op, one, other, held),
894                Some(live) => refine_prepared(*op, one, other, live, held),
895            };
896        }
897        // A later LIKE in a threaded filter often sees only a handful of survivors.
898        // Gather its arguments, not the whole chunk, while preserving the stable
899        // dictionary behind a gathered string column. The ordinary full-vector
900        // path remains cheaper when most rows are still live.
901        if let (Some(live), Step::Function { recipe, written, start, len }) =
902            (live, &self.steps[index])
903        {
904            if matches!(recipe.name(), "~~" | "!~~" | "~~*" | "!~~*")
905                && live.len().saturating_mul(4) <= chunk.len()
906            {
907                let flags = self
908                    .with_operands(*start, *len, chunk, &scratch.slots, |args| {
909                        let gathered = args
910                            .iter()
911                            .map(|arg| arg.gather(live.indices()))
912                            .collect::<Result<Vec<_>>>()?;
913                        let narrowed = gathered.iter().collect::<Vec<_>>();
914                        rudb_kernels::call_prepared(
915                            recipe,
916                            &narrowed,
917                            &self.types[index],
918                            Some(&|| written.clone()),
919                        )
920                    })
921                    .map_err(|error| error.with_fallback_span(self.spans[index]))?;
922                return Ok(selection(&flags, live.len()).compose(live));
923            }
924        }
925        self.run_step(index, chunk, scratch)?;
926        let flags = self.operand(index, chunk, &scratch.slots)?;
927        match live {
928            None => Ok(selection(flags, chunk.len())),
929            Some(live) => refine_flags(flags, live),
930        }
931    }
932
933    /// Runs every step in order, filling the slots.
934    fn run(&self, chunk: &Chunk, scratch: &mut Scratch) -> Result<()> {
935        scratch.slots.clear();
936        scratch.slots.resize_with(self.steps.len(), || None);
937        for index in 0..self.steps.len() {
938            self.run_step(index, chunk, scratch)?;
939        }
940        Ok(())
941    }
942
943    /// Runs one step and empties the slot of every operand this was the last step to read.
944    fn run_step(&self, index: usize, chunk: &Chunk, scratch: &mut Scratch) -> Result<()> {
945        let produced = self
946            .step(index, chunk, &scratch.slots)
947            .map_err(|error| error.with_fallback_span(self.spans[index]))?;
948        scratch.slots[index] = produced;
949        let slots = &mut scratch.slots;
950        self.for_each_operand(index, |operand| {
951            if self.last_use[operand] == index {
952                slots[operand] = None;
953            }
954        });
955        Ok(())
956    }
957
958    /// Runs one step, given what the steps before it produced.
959    fn step(
960        &self,
961        index: usize,
962        chunk: &Chunk,
963        slots: &[Option<Vector>],
964    ) -> Result<Option<Vector>> {
965        let ty = &self.types[index];
966        let produced = match &self.steps[index] {
967            Step::Column(_) => None,
968            Step::Constant(value) => Some(Vector::constant(ty.clone(), value.clone(), chunk.len())),
969            Step::Cast { input, try_cast } => Some(cast_in_time_zone(
970                self.operand(*input, chunk, slots)?,
971                ty,
972                *try_cast,
973                Some(self.time_zone),
974            )?),
975            Step::Compare { op, left, right, held } => Some(compare_prepared(
976                *op,
977                self.operand(*left, chunk, slots)?,
978                self.operand(*right, chunk, slots)?,
979                held.as_ref(),
980            )?),
981            Step::Conjunction { op, start, len } => {
982                Some(
983                    self.with_operands(*start, *len, chunk, slots, |children| {
984                        combine(*op, children)
985                    })?,
986                )
987            }
988            Step::Function { recipe, written, start, len } => {
989                Some(self.with_operands(*start, *len, chunk, slots, |args| {
990                    rudb_kernels::call_prepared(recipe, args, ty, Some(&|| written.clone()))
991                })?)
992            }
993            Step::InSet { input, members } => {
994                Some(in_set(self.operand(*input, chunk, slots)?, members, ty)?)
995            }
996            Step::Case { arms, otherwise, blend } => {
997                Some(self.case(chunk, arms, otherwise.as_ref(), blend.as_ref(), ty)?)
998            }
999            Step::Fused { fused, fallback } => Some(match fused.run(chunk) {
1000                Some(answer) => answer,
1001                None => fallback.evaluate_one(chunk, &mut fallback.scratch())?.clone(),
1002            }),
1003            Step::Lambda { inputs, runner, body } => {
1004                let mut operands = Vec::with_capacity(inputs.len());
1005                for &input in inputs {
1006                    operands.push(self.operand(input, chunk, slots)?);
1007                }
1008                let mut scratch = body.scratch();
1009                Some(runner.run(&operands, chunk, &mut |inner| {
1010                    body.evaluate_one(inner, &mut scratch).cloned()
1011                })?)
1012            }
1013        };
1014        Ok(produced)
1015    }
1016
1017    /// The vector a step produced, or the chunk's column if the step is a column reference.
1018    fn operand<'v>(
1019        &self,
1020        index: usize,
1021        chunk: &'v Chunk,
1022        slots: &'v [Option<Vector>],
1023    ) -> Result<&'v Vector> {
1024        if let Step::Column(position) = self.steps[index] {
1025            return chunk.column(position);
1026        }
1027        slots[index].as_ref().ok_or_else(|| missing(index))
1028    }
1029
1030    /// Hands a kernel the references to an operand list, without allocating for the usual widths.
1031    ///
1032    /// One, two and three because those are what a bound tree is made of: every scalar function in
1033    /// the catalog is unary or binary, a comparison is binary, and a conjunction is two or three
1034    /// often enough to be worth a line. A stack array for those means a chain of eight additions
1035    /// makes zero allocations for its operand lists over a chunk instead of eight, and eight
1036    /// allocations a chunk at the rate a pipeline produces chunks is a real number rather than a
1037    /// tidiness argument. Anything wider falls back to [`gather`](Self::gather), which is a `Vec`
1038    /// of pointers and still moves no data.
1039    fn with_operands<'v, T>(
1040        &self,
1041        start: usize,
1042        len: usize,
1043        chunk: &'v Chunk,
1044        slots: &'v [Option<Vector>],
1045        run: impl FnOnce(&[&'v Vector]) -> Result<T>,
1046    ) -> Result<T> {
1047        match self.operands[start..start + len] {
1048            [a] => run(&[self.operand(a, chunk, slots)?]),
1049            [a, b] => run(&[self.operand(a, chunk, slots)?, self.operand(b, chunk, slots)?]),
1050            [a, b, c] => run(&[
1051                self.operand(a, chunk, slots)?,
1052                self.operand(b, chunk, slots)?,
1053                self.operand(c, chunk, slots)?,
1054            ]),
1055            _ => {
1056                let gathered = self.gather(start, len, chunk, slots)?;
1057                run(&gathered)
1058            }
1059        }
1060    }
1061
1062    /// References to an operand list, for a kernel that takes a slice of them.
1063    ///
1064    /// The `Vec` here is the allocation the module documentation names: it holds pointers rather
1065    /// than vectors, so it is a dozen bytes an operand and no data moves.
1066    fn gather<'v>(
1067        &self,
1068        start: usize,
1069        len: usize,
1070        chunk: &'v Chunk,
1071        slots: &'v [Option<Vector>],
1072    ) -> Result<Vec<&'v Vector>> {
1073        let mut gathered = Vec::with_capacity(len);
1074        for &operand in &self.operands[start..start + len] {
1075            gathered.push(self.operand(operand, chunk, slots)?);
1076        }
1077        Ok(gathered)
1078    }
1079
1080    /// A searched `CASE` over the rows no earlier arm claimed.
1081    ///
1082    /// The same shape [`evaluate`](crate::evaluate) has, because the thing that makes it that shape
1083    /// is a correctness rule rather than a performance one: `CASE WHEN x <> 0 THEN 1 / x ELSE 0 END`
1084    /// divides by zero on the rows the arm excludes if the arm is evaluated for them.
1085    ///
1086    /// Each arm answers the rows no earlier arm claimed, so the answers come back short and out of
1087    /// order and have to be put back in the order the rows arrived in. That is what [`Assembly`] is:
1088    /// the arms are laid end to end into one run of data and the interleave is a single typed copy
1089    /// over it. It used to be a `Vec<Value>` filled a row at a time and handed to
1090    /// `Vector::from_values`, which is a heap allocation and a drop for every string in the answer.
1091    /// On the ClickBench query that groups by a `CASE` over `Referer` that was about a quarter of
1092    /// the whole query.
1093    ///
1094    /// What is left of #57 here is the narrowing. An arm still narrows the whole chunk rather than
1095    /// the columns it reads, and the selection threading that replaces the narrowing entirely is
1096    /// the item this one was carved out of.
1097    fn case(
1098        &self,
1099        chunk: &Chunk,
1100        arms: &[PreparedArm],
1101        otherwise: Option<&Prepared>,
1102        blend: Option<&Blend>,
1103        ty: &LogicalType,
1104    ) -> Result<Vector> {
1105        let claimed = self.claims(chunk, arms)?;
1106        if let Some(blend) = blend {
1107            if let Some(blended) = blended(chunk, &claimed, blend)? {
1108                return Ok(blended);
1109            }
1110        }
1111        let mut built = Assembly::new(ty.clone(), chunk.len())?;
1112        let branches = arms.iter().map(|arm| &arm.then).map(Some).chain([otherwise]);
1113        for (branch, rows) in branches.zip(&claimed) {
1114            let (Some(branch), false) = (branch, rows.is_empty()) else { continue };
1115            // The same cut the conditions skip above, skipped here for the same reason: a branch
1116            // that claimed every row claimed them in order, so narrowing to them is a copy of every
1117            // column in the chunk to arrive back at the chunk.
1118            let cut;
1119            let matched = if rows.len() == chunk.len() {
1120                chunk
1121            } else {
1122                cut = narrow(chunk, rows)?;
1123                &cut
1124            };
1125            let mut scratch = branch.scratch();
1126            let results = branch.evaluate_one(matched, &mut scratch)?;
1127            built.place(&placed(rows)?, results)?;
1128        }
1129        built.finish()
1130    }
1131
1132    /// The rows each branch of a `CASE` answers, one list per arm in order and the `ELSE` last.
1133    ///
1134    /// Only the conditions are run here, which is what keeps the rule the doc above states: an arm's
1135    /// condition is evaluated over the rows no earlier arm claimed, so a condition that would raise
1136    /// on a row an earlier arm took is never asked about it. The results are worked out afterwards,
1137    /// once, from these lists, and both ways of working them out want the same thing, which is the
1138    /// rows of one branch in the order they arrived in.
1139    fn claims(&self, chunk: &Chunk, arms: &[PreparedArm]) -> Result<Vec<Vec<usize>>> {
1140        let mut claimed = Vec::with_capacity(arms.len() + 1);
1141        let mut pending: Vec<usize> = (0..chunk.len()).collect();
1142        for arm in arms {
1143            if pending.is_empty() {
1144                claimed.push(Vec::new());
1145                continue;
1146            }
1147            // `pending` starts as every row in order and only ever shrinks, so the same length is
1148            // the same rows in the same order and there is nothing to cut. That is the whole of the
1149            // first arm of a one armed `CASE`, which is the shape of the ClickBench query this was
1150            // measured on, and cutting it was a copy of every column in the chunk for nothing.
1151            let cut;
1152            let narrowed = if pending.len() == chunk.len() {
1153                chunk
1154            } else {
1155                cut = narrow(chunk, &pending)?;
1156                &cut
1157            };
1158            let mut scratch = arm.when.scratch();
1159            let flags = arm.when.evaluate_one(narrowed, &mut scratch)?;
1160            let mut taken = Vec::new();
1161            let mut still = Vec::new();
1162            // row at a time: splitting the rows an arm claims from the ones it leaves is a test per
1163            // row, and what replaces it is the selection threading the rest of #57 asks for rather
1164            // than anything that can be done here.
1165            for (at, &row) in pending.iter().enumerate() {
1166                if is_true(&flags.value_at(at)) {
1167                    taken.push(row);
1168                } else {
1169                    still.push(row);
1170                }
1171            }
1172            claimed.push(taken);
1173            pending = still;
1174        }
1175        claimed.push(pending);
1176        Ok(claimed)
1177    }
1178
1179    /// Flattens one expression, appending its steps and returning the index of its last one.
1180    fn push(&mut self, plan: &Plan, expr: ExprRef, schema: &Schema) -> Result<usize> {
1181        if self.share {
1182            if let Some(&step) = self.shared.get(&expr) {
1183                return Ok(step);
1184            }
1185        }
1186        let ty = plan.expr_type(expr).clone();
1187        if self.fuse {
1188            if let Some(fused) = Fused::compile(plan, expr, schema) {
1189                let fallback = Self::built(plan, &[expr], schema, false, false)?;
1190                let step = Step::Fused { fused: Box::new(fused), fallback: Box::new(fallback) };
1191                return Ok(self.place(plan, expr, step, ty));
1192            }
1193        }
1194        if let Some((stamp, count)) = stamped_seconds(plan, expr) {
1195            let (start, len) = self.push_list(plan, &[stamp, count], schema)?;
1196            let step = Step::Function {
1197                recipe: Recipe::new("__rudb_stamp_seconds", &self.literals(start, len)),
1198                written: written(plan, expr, schema),
1199                start,
1200                len,
1201            };
1202            return Ok(self.place(plan, expr, step, ty));
1203        }
1204        let step = match *plan.expr(expr) {
1205            Expr::Column(binding) => {
1206                let position = schema.position_of(binding).ok_or_else(|| {
1207                    Error::internal(format!(
1208                        "column #{}.{} is not in the schema this operator was given",
1209                        binding.table, binding.column
1210                    ))
1211                })?;
1212                Step::Column(position)
1213            }
1214            Expr::Constant(reference) => Step::Constant(plan.value(reference).clone()),
1215            Expr::Cast { input, try_cast } => {
1216                Step::Cast { input: self.push(plan, input, schema)?, try_cast }
1217            }
1218            Expr::Compare { op, left, right } => {
1219                let left = self.push(plan, left, schema)?;
1220                let right = self.push(plan, right, schema)?;
1221                Step::Compare { op: comparison(op), left, right, held: self.held(left, right) }
1222            }
1223            Expr::Conjunction { op, children } => {
1224                let list = plan.expr_list(children).to_vec();
1225                match self.membership(plan, connective(op), &list, schema)? {
1226                    Some(step) => step,
1227                    None => {
1228                        let (start, len) = self.push_list(plan, &list, schema)?;
1229                        Step::Conjunction { op: connective(op), start, len }
1230                    }
1231                }
1232            }
1233            Expr::Function { name, args } if lambda_call(plan, args).is_some() => {
1234                let Some((lambda, inputs)) = lambda_call(plan, args) else {
1235                    return Err(Error::internal("a lambda call without a lambda"));
1236                };
1237                let Expr::Lambda { body, .. } = *plan.expr(lambda) else {
1238                    return Err(Error::internal("a lambda call without a lambda"));
1239                };
1240                let runner = Lambda::new(plan, plan.string(name), lambda, &inputs, schema)?;
1241                let body = Self::one(plan, body, runner.schema())?;
1242                let mut steps = Vec::with_capacity(inputs.len());
1243                for &input in &inputs {
1244                    steps.push(self.push(plan, input, schema)?);
1245                }
1246                Step::Lambda { inputs: steps, runner: Box::new(runner), body: Box::new(body) }
1247            }
1248            Expr::LambdaParam(binding) => {
1249                let position = schema.position_of(binding).ok_or_else(|| {
1250                    Error::internal(format!(
1251                        "lambda parameter @{}.{} is not in the schema its body was given",
1252                        binding.table, binding.column
1253                    ))
1254                })?;
1255                Step::Column(position)
1256            }
1257            Expr::Lambda { .. } => {
1258                return Err(Error::internal(
1259                    "a lambda was evaluated outside the function that takes it",
1260                ));
1261            }
1262            Expr::Function { name, args } => {
1263                let (start, len) = self.push_list(plan, plan.expr_list(args), schema)?;
1264                Step::Function {
1265                    recipe: Recipe::new(plan.string(name), &self.literals(start, len)),
1266                    written: written(plan, expr, schema),
1267                    start,
1268                    len,
1269                }
1270            }
1271            Expr::Aggregate { name, .. } => {
1272                return Err(Error::internal(format!(
1273                    "the {} aggregate was evaluated as an ordinary expression",
1274                    plan.string(name)
1275                )));
1276            }
1277            Expr::Window { name, .. } => {
1278                return Err(Error::internal(format!(
1279                    "the {} window function was evaluated as an ordinary expression",
1280                    plan.string(name)
1281                )));
1282            }
1283            Expr::Case { arms, otherwise } => {
1284                let mut prepared = Vec::new();
1285                for &arm in plan.arm_list(arms) {
1286                    prepared.push(PreparedArm {
1287                        when: Self::one(plan, arm.when, schema)?,
1288                        then: Self::one(plan, arm.then, schema)?,
1289                    });
1290                }
1291                let otherwise = match otherwise {
1292                    Some(otherwise) => Some(Self::one(plan, otherwise, schema)?),
1293                    None => None,
1294                };
1295                let blend = blending(&ty, &prepared, otherwise.as_ref());
1296                Step::Case { arms: prepared, otherwise, blend }
1297            }
1298        };
1299        Ok(self.place(plan, expr, step, ty))
1300    }
1301
1302    /// Appends a built step and answers its index.
1303    fn place(&mut self, plan: &Plan, expr: ExprRef, step: Step, ty: LogicalType) -> usize {
1304        self.steps.push(step);
1305        self.types.push(ty);
1306        self.spans.push(plan.expr_span(expr));
1307        let step = self.steps.len() - 1;
1308        if self.share {
1309            self.shared.insert(expr, step);
1310        }
1311        step
1312    }
1313
1314    /// Flattens a list of expressions and records where its operand run starts and how long it is.
1315    ///
1316    /// The operand run is written after every child has been flattened rather than as they go,
1317    /// because a child that is itself a list would otherwise interleave its run with this one.
1318    fn push_list(
1319        &mut self,
1320        plan: &Plan,
1321        exprs: &[ExprRef],
1322        schema: &Schema,
1323    ) -> Result<(usize, usize)> {
1324        let mut indices = Vec::with_capacity(exprs.len());
1325        for &expr in exprs {
1326            indices.push(self.push(plan, expr, schema)?);
1327        }
1328        let start = self.operands.len();
1329        let len = indices.len();
1330        self.operands.extend(indices);
1331        Ok((start, len))
1332    }
1333
1334    /// This connective folded back into the `IN` the user wrote, or `None` when it is not one.
1335    ///
1336    /// What the binder writes for `x IN (1, 2, 3)` is `x = 1 OR x = 2 OR x = 3`, and for
1337    /// `x NOT IN (1, 2, 3)` it is `x <> 1 AND x <> 2 AND x <> 3`. So the shape looked for is every
1338    /// child a comparison of the one direction, every left the same expression, and every right a
1339    /// literal. Anything else is left alone, which covers the `OR` that was written as an `OR` and
1340    /// the one where an `IN` has been flattened together with another branch. The second is a fold
1341    /// this could make and does not, and it is worth having later out of a query that wants it
1342    /// rather than now out of a guess.
1343    ///
1344    /// This runs before the children are pushed, and that is the whole reason it is here rather than
1345    /// as a pass over the finished array. A step that nothing reads is still a step the walk runs,
1346    /// because the walk over a subtree is a range and not a graph, so folding after the fact would
1347    /// leave every equality in place and running.
1348    fn membership(
1349        &mut self,
1350        plan: &Plan,
1351        op: Connective,
1352        children: &[ExprRef],
1353        schema: &Schema,
1354    ) -> Result<Option<Step>> {
1355        let wanted = match op {
1356            Connective::Or => CompareOp::Equal,
1357            Connective::And => CompareOp::NotEqual,
1358        };
1359        let mut subject: Option<ExprRef> = None;
1360        let mut values = Vec::with_capacity(children.len());
1361        for &child in children {
1362            let Expr::Compare { op: found, left, right } = *plan.expr(child) else {
1363                return Ok(None);
1364            };
1365            if found != wanted || !same(plan, *subject.get_or_insert(left), left) {
1366                return Ok(None);
1367            }
1368            let Expr::Constant(reference) = *plan.expr(right) else {
1369                return Ok(None);
1370            };
1371            values.push(plan.value(reference).clone());
1372        }
1373        let (Some(subject), Some(members)) = (subject, Members::of(&values, op == Connective::And))
1374        else {
1375            return Ok(None);
1376        };
1377        Ok(Some(Step::InSet { input: self.push(plan, subject, schema)?, members }))
1378    }
1379
1380    /// The literal side of a comparison, in the one row column the comparison reads it through.
1381    ///
1382    /// The right side first, because that is the side the binder puts a literal on and the side the
1383    /// loops are written for. Two literals is a comparison the optimizer folded, and if it did not
1384    /// then the kernel answers it once for the whole vector and never reads either column, so
1385    /// neither side is built here.
1386    fn held(&self, left: usize, right: usize) -> Option<Held> {
1387        let (at, other) = match (&self.steps[left], &self.steps[right]) {
1388            (Step::Constant(_), Step::Constant(_)) => return None,
1389            (_, Step::Constant(value)) => (right, value),
1390            (Step::Constant(value), _) => (left, value),
1391            _ => return None,
1392        };
1393        Held::of(&self.types[at], other)
1394    }
1395
1396    /// The literal behind each argument in a run of the operand list, and `None` for an argument
1397    /// that is anything else.
1398    ///
1399    /// This is what a [`Recipe`] hoists from. An argument that is a literal in the plan arrives as a
1400    /// constant vector holding exactly this value on every chunk, so what a kernel reads here is
1401    /// what it would have read per chunk. An argument that is a cast of a literal reads as `None`,
1402    /// which is a call the kernel decides per chunk as it always did, and the optimizer folds most
1403    /// of those before the plan gets here anyway.
1404    fn literals(&self, start: usize, len: usize) -> Vec<Option<Value>> {
1405        self.operands[start..start + len]
1406            .iter()
1407            .map(|&operand| match &self.steps[operand] {
1408                Step::Constant(value) => Some(value.clone()),
1409                _ => None,
1410            })
1411            .collect()
1412    }
1413}
1414
1415/// Whether two expressions of one plan are the same expression, written once or written twice.
1416///
1417/// The binder binds the subject of an `IN` once and points every comparison it writes at that one
1418/// reference, so the answer is almost always the first line. A plan that has been through a rewrite,
1419/// and a plan read back from its own text, hold two copies of the same tree instead, and for the
1420/// fold in [`Prepared::membership`] those are the same expression.
1421///
1422/// The four shapes handled are what an `IN` is written over: a column, a literal, a cast of either,
1423/// and a call, which is TPC-H query 22 asking whether the first two digits of a phone number are in
1424/// a list. Anything else answers no, which costs a fold that could have happened rather than a wrong
1425/// one. The walk is bounded by the size of the subject and a subject is small.
1426/// The timestamp and the whole count of `stamp + to_seconds(CAST(count AS DOUBLE))`, the shape the
1427/// benchmark view writes `INTERVAL (EventTime) SECOND` in, and `None` for anything else.
1428///
1429/// It runs as one call, [`rudb_kernels`]'s `__rudb_stamp_seconds`, rather than as a cast to a
1430/// double, an interval per row and a shift by it.
1431fn stamped_seconds(plan: &Plan, expr: ExprRef) -> Option<(ExprRef, ExprRef)> {
1432    let Expr::Function { name, args } = *plan.expr(expr) else { return None };
1433    if plan.string(name) != "+" || plan.expr_type(expr) != &LogicalType::Timestamp {
1434        return None;
1435    }
1436    let &[one, other] = plan.expr_list(args) else { return None };
1437    let (stamp, interval) =
1438        if plan.expr_type(one) == &LogicalType::Timestamp { (one, other) } else { (other, one) };
1439    if plan.expr_type(stamp) != &LogicalType::Timestamp {
1440        return None;
1441    }
1442    let Expr::Function { name, args } = *plan.expr(interval) else { return None };
1443    let &[cast] = plan.expr_list(args) else { return None };
1444    let Expr::Cast { input, try_cast: false } = *plan.expr(cast) else { return None };
1445    let whole = matches!(
1446        plan.expr_type(input),
1447        LogicalType::TinyInt
1448            | LogicalType::SmallInt
1449            | LogicalType::Integer
1450            | LogicalType::BigInt
1451            | LogicalType::UTinyInt
1452            | LogicalType::USmallInt
1453            | LogicalType::UInteger
1454    );
1455    (plan.string(name) == "to_seconds" && plan.expr_type(cast) == &LogicalType::Double && whole)
1456        .then_some((stamp, input))
1457}
1458
1459fn same(plan: &Plan, left: ExprRef, right: ExprRef) -> bool {
1460    if left == right {
1461        return true;
1462    }
1463    if plan.expr_type(left) != plan.expr_type(right) {
1464        return false;
1465    }
1466    match (plan.expr(left), plan.expr(right)) {
1467        (Expr::Column(one), Expr::Column(other)) => one == other,
1468        (Expr::Constant(one), Expr::Constant(other)) => plan.value(*one) == plan.value(*other),
1469        (
1470            Expr::Cast { input: one, try_cast: first },
1471            Expr::Cast { input: other, try_cast: second },
1472        ) => first == second && same(plan, *one, *other),
1473        (
1474            Expr::Function { name: one, args: first },
1475            Expr::Function { name: other, args: second },
1476        ) => {
1477            let (first, second) = (plan.expr_list(*first), plan.expr_list(*second));
1478            plan.string(*one) == plan.string(*other)
1479                && first.len() == second.len()
1480                && first.iter().zip(second).all(|(&one, &other)| same(plan, one, other))
1481        }
1482        _ => false,
1483    }
1484}
1485
1486/// What touching a value of this type costs, against a fixed width one as the unit.
1487///
1488/// A variable length value is a pointer to follow and a length that is not the same twice, and a
1489/// nested one is that per element. Four is not measured, and what it has to be is large enough that
1490/// the ordering puts a fixed width comparison in front of a string one and small enough that it does
1491/// not put one in front of a string comparison that rejects every row.
1492fn touching(ty: &LogicalType) -> f64 {
1493    match ty.physical() {
1494        PhysicalType::Varlen => 4.0,
1495        PhysicalType::List | PhysicalType::Array | PhysicalType::Struct => 8.0,
1496        _ => 1.0,
1497    }
1498}
1499
1500/// The error for a slot that should have held something and did not.
1501///
1502/// This cannot happen while the array is in post order, since every operand's index is smaller than
1503/// the index of the step using it and every step runs in order. It is an error rather than a panic
1504/// because the property it depends on is a property of [`Prepared::push`], and the day somebody
1505/// writes a pass that reorders the array is the day it stops holding.
1506fn missing(index: usize) -> Error {
1507    Error::internal(format!("step {index} was used as an operand before it produced anything"))
1508}
1509
1510/// Chunk rows as the positions an [`Assembly`] places a piece at.
1511///
1512/// A chunk is at most [`VECTOR_SIZE`](rudb_vector::VECTOR_SIZE) rows, so the conversion cannot fail
1513/// in practice. It is checked rather than cast because a silent truncation here would put a value in
1514/// the wrong row, and a wrong row is the one kind of bug nothing downstream can notice.
1515fn placed(rows: &[usize]) -> Result<Vec<u32>> {
1516    rows.iter()
1517        .map(|&row| {
1518            u32::try_from(row).map_err(|_| Error::internal("a chunk of more than u32 rows"))
1519        })
1520        .collect()
1521}
1522
1523/// A `CASE` answered as codes over the dictionary its branches share, or `None` for a chunk that
1524/// cannot be.
1525///
1526/// Declined per chunk rather than once, because whether a column arrives coded is a fact about the
1527/// chunk and not about the expression. The same query reads codes out of a native file and plain
1528/// strings out of rows held in memory, and one file can hand a column over as a dictionary in one
1529/// part and as plain data in the next. Everything that declines does so before a code is written, so
1530/// the caller starts the general path from nothing rather than from a half filled answer.
1531fn blended(chunk: &Chunk, claimed: &[Vec<usize>], blend: &Blend) -> Result<Option<Vector>> {
1532    let Some((dictionary, literals)) = agreed(chunk, blend)? else { return Ok(None) };
1533    let mut codes = vec![0; chunk.len()];
1534    for (branch, rows) in blend.branches.iter().zip(claimed) {
1535        match *branch {
1536            Branch::Column(position) => {
1537                let Some((from, _)) = chunk.column(position)?.stable_dictionary_parts() else {
1538                    return Ok(None);
1539                };
1540                for &row in rows {
1541                    codes[row] = from[row];
1542                }
1543            }
1544            Branch::Literal(at) => {
1545                for &row in rows {
1546                    codes[row] = literals[at];
1547                }
1548            }
1549        }
1550    }
1551    Vector::stable_dictionary(codes, dictionary).map(Some)
1552}
1553
1554/// The one dictionary every branch of a blend names values in, and the code each literal sits at.
1555///
1556/// Three things say no. A column that did not arrive as a stable dictionary has no codes to copy. A
1557/// second column over a different dictionary would have codes that mean something else, and a code
1558/// is a position in one dictionary and nothing anywhere else. And a literal the dictionary does not
1559/// hold has no code at all, which for `ELSE ''` over a column where no row is empty is the honest
1560/// answer rather than a missing one.
1561///
1562/// The null check is the fourth. A dictionary keeps its nulls in the values it points at rather than
1563/// beside its codes, so a column carrying its own validity is one whose codes do not say everything
1564/// the column says, and copying them would turn its nulls into whatever their codes happen to name.
1565fn agreed(chunk: &Chunk, blend: &Blend) -> Result<Option<(Arc<Vector>, Vec<u32>)>> {
1566    let mut held: Option<(&Vector, &Arc<Vector>)> = None;
1567    for branch in &blend.branches {
1568        let Branch::Column(position) = *branch else { continue };
1569        let column = chunk.column(position)?;
1570        let Some((_, dictionary)) = column.stable_dictionary_parts() else { return Ok(None) };
1571        if column.validity().has_nulls(chunk.len()) {
1572            return Ok(None);
1573        }
1574        match held {
1575            Some((_, first)) if !Arc::ptr_eq(first, dictionary) => return Ok(None),
1576            Some(_) => {}
1577            None => held = Some((column, dictionary)),
1578        }
1579    }
1580    let Some((column, dictionary)) = held else { return Ok(None) };
1581    let mut codes = Vec::with_capacity(blend.literals.len());
1582    for (text, lookup) in &blend.literals {
1583        match lookup.find(column, text.as_bytes()) {
1584            Some(Ok(Found::At(code))) => codes.push(code),
1585            Some(Err(error)) => return Err(error),
1586            Some(Ok(Found::Absent)) | None => return Ok(None),
1587        }
1588    }
1589    Ok(Some((Arc::clone(dictionary), codes)))
1590}
1591
1592/// The blend a `CASE` can be answered by, or `None` for one that has to read its branches' values.
1593fn blending(ty: &LogicalType, arms: &[PreparedArm], otherwise: Option<&Prepared>) -> Option<Blend> {
1594    if !matches!(ty, LogicalType::Varchar) {
1595        return None;
1596    }
1597    let otherwise = otherwise?;
1598    let mut branches = Vec::with_capacity(arms.len() + 1);
1599    let mut literals = Vec::new();
1600    for branch in arms.iter().map(|arm| &arm.then).chain([otherwise]) {
1601        branches.push(named(branch, &mut literals)?);
1602    }
1603    // All of them literals means there is no dictionary to name any of them in, and a `CASE` whose
1604    // every branch is a constant is not a thing anybody writes.
1605    let any = branches.iter().any(|branch| matches!(branch, Branch::Column(_)));
1606    any.then_some(Blend { branches, literals })
1607}
1608
1609/// The branch a prepared expression stands for, when it names a value rather than computing one.
1610fn named(prepared: &Prepared, literals: &mut Vec<(String, Lookup)>) -> Option<Branch> {
1611    match prepared.steps.as_slice() {
1612        [Step::Column(position)] => Some(Branch::Column(*position)),
1613        [Step::Constant(Value::Varchar(text))] => {
1614            literals.push((text.clone(), Lookup::default()));
1615            Some(Branch::Literal(literals.len() - 1))
1616        }
1617        _ => None,
1618    }
1619}
1620
1621/// The chunk cut down to the given rows.
1622///
1623/// The reason `CASE` is written with this rather than by evaluating every arm over the whole chunk
1624/// and picking afterwards. `CASE WHEN x <> 0 THEN 1 // x ELSE 0 END` divides by zero on the rows the
1625/// arm does not apply to if the arm is evaluated for them, and a `CASE` that raises on a row it was
1626/// written to exclude is the classic wrong answer this shape prevents.
1627pub(crate) fn narrow(chunk: &Chunk, rows: &[usize]) -> Result<Chunk> {
1628    let mut selection = Selection::with_capacity(rows.len());
1629    for &row in rows {
1630        selection.push(row);
1631    }
1632    chunk.clone().select(&selection)
1633}
1634
1635/// The kernels' comparison for the plan's.
1636///
1637/// A translation rather than one shared enum, because the kernels are rank 3 and the plan is rank
1638/// 9. This function is the whole of what that separation costs.
1639pub(crate) fn comparison(op: CompareOp) -> Comparison {
1640    match op {
1641        CompareOp::Equal => Comparison::Equal,
1642        CompareOp::NotEqual => Comparison::NotEqual,
1643        CompareOp::Less => Comparison::Less,
1644        CompareOp::LessOrEqual => Comparison::LessOrEqual,
1645        CompareOp::Greater => Comparison::Greater,
1646        CompareOp::GreaterOrEqual => Comparison::GreaterOrEqual,
1647        CompareOp::DistinctFrom => Comparison::DistinctFrom,
1648        CompareOp::NotDistinctFrom => Comparison::NotDistinctFrom,
1649    }
1650}
1651
1652/// The kernels' connective for the plan's.
1653pub(crate) fn connective(op: ConjunctionOp) -> Connective {
1654    match op {
1655        ConjunctionOp::And => Connective::And,
1656        ConjunctionOp::Or => Connective::Or,
1657    }
1658}
1659
1660#[cfg(test)]
1661mod tests {
1662    use rudb_common::{Field, LogicalType, Value};
1663    use rudb_kernels::is_true;
1664    use rudb_plan::{ExprRef, Node, Plan};
1665    use rudb_vector::{Chunk, Selection, Vector};
1666
1667    use super::{Prepared, narrow};
1668    use crate::expr::evaluate;
1669    use crate::schema::Schema;
1670
1671    /// Two columns with a null in each, because every disagreement between these two evaluators
1672    /// that is worth finding is a disagreement about which rows are null.
1673    fn input() -> (Schema, Chunk) {
1674        let schema = Schema::numbered(
1675            vec![Field::new("x", LogicalType::Integer), Field::new("s", LogicalType::Varchar)],
1676            0,
1677        );
1678        let x = Vector::from_values(
1679            LogicalType::Integer,
1680            &[Value::Integer(3), Value::Integer(1), Value::Null, Value::Integer(2)],
1681        )
1682        .expect("four integers");
1683        let s = Vector::from_values(
1684            LogicalType::Varchar,
1685            &[
1686                Value::Varchar("a".to_string()),
1687                Value::Null,
1688                Value::Varchar("c".to_string()),
1689                Value::Varchar("a".to_string()),
1690            ],
1691        )
1692        .expect("four strings");
1693        (schema, Chunk::new(vec![x, s]).expect("two columns of four rows"))
1694    }
1695
1696    /// The expressions of a projection written in the plan's textual form, over the two columns
1697    /// [`input`] produces.
1698    ///
1699    /// Going through the text rather than the arena builders for the reason the other test module
1700    /// gives: a test that says what it evaluates in the notation a plan dump uses is a test whose
1701    /// failure can be pasted into a plan and vice versa.
1702    fn projection(exprs: &str) -> (Plan, Vec<ExprRef>) {
1703        let text =
1704            format!("Project #1 [{exprs}]\n  Get memory.main.t AS t #0 [x::INTEGER, s::VARCHAR]");
1705        let plan = Plan::parse(&text).expect("a well formed plan");
1706        let Node::Project { exprs, .. } = *plan.node(plan.root()) else {
1707            panic!("the root of that text is a projection");
1708        };
1709        let list = plan.expr_list(exprs).to_vec();
1710        (plan, list)
1711    }
1712
1713    /// Every expression shape, evaluated both ways over the same chunk.
1714    ///
1715    /// This is the agreement the module documentation claims and it is the only thing that makes
1716    /// the prepared form safe to put in front of the tree walk. The generated well typed trees the
1717    /// test gate of #57 asks for are a wider version of this and are worth building once the
1718    /// selection threaded shapes exist to disagree about.
1719    fn agrees(exprs: &str) {
1720        let (schema, chunk) = input();
1721        let (plan, list) = projection(exprs);
1722        let prepared = Prepared::new(&plan, &list, &schema).expect("the expressions resolve");
1723        let mut scratch = prepared.scratch();
1724        let mut fast = Vec::new();
1725        prepared.evaluate(&chunk, &mut scratch, &mut fast).expect("the prepared form runs");
1726        for (at, &expr) in list.iter().enumerate() {
1727            let slow = evaluate(&plan, expr, &schema, &chunk).expect("the tree walk runs");
1728            for row in 0..chunk.len() {
1729                assert_eq!(
1730                    fast[at].value_at(row),
1731                    slow.value_at(row),
1732                    "expression {at} of `{exprs}` at row {row}"
1733                );
1734            }
1735        }
1736    }
1737
1738    /// Three decimal columns of TPC-H's shape, in the form `form` puts them in.
1739    fn decimals(prices: &[i128], form: fn(Vector) -> Vector) -> (Schema, Chunk) {
1740        let ty = LogicalType::Decimal { width: 15, scale: 2 };
1741        let schema = Schema::numbered(
1742            vec![
1743                Field::new("p", ty.clone()),
1744                Field::new("d", ty.clone()),
1745                Field::new("t", ty.clone()),
1746            ],
1747            0,
1748        );
1749        let column =
1750            |values: Vec<Value>| form(Vector::from_values(ty.clone(), &values).expect("decimals"));
1751        let decimal = |unscaled| Value::Decimal { unscaled, width: 15, scale: 2 };
1752        let p = column(prices.iter().map(|&v| decimal(v)).collect());
1753        let d = column((0..prices.len() as i128).map(|v| decimal(v % 11)).collect());
1754        let t = column((0..prices.len() as i128).map(|v| decimal(v % 9)).collect());
1755        (schema, Chunk::new(vec![p, d, t]).expect("three columns"))
1756    }
1757
1758    /// q01's charge, as the binder writes it.
1759    const CHARGE: &str = "\"*\"(\"*\"(CAST(#0.0::DECIMAL(15,2))::DECIMAL(18,2), \
1760        CAST(\"-\"(1.00::DECIMAL(16,2), CAST(#0.1::DECIMAL(15,2))::DECIMAL(16,2))::DECIMAL(16,2))\
1761        ::DECIMAL(18,2))::DECIMAL(18,4), CAST(\"+\"(1.00::DECIMAL(16,2), \
1762        CAST(#0.2::DECIMAL(15,2))::DECIMAL(16,2))::DECIMAL(16,2))::DECIMAL(18,2))::DECIMAL(18,6) AS a";
1763
1764    /// The fused answer, the unfused one and the tree walk's, over one chunk.
1765    fn three_ways(chunk: &Chunk, schema: &Schema) -> [rudb_common::Result<Vec<Value>>; 3] {
1766        let text = format!(
1767            "Project #1 [{CHARGE}]\n  Get memory.main.t AS t #0 \
1768             [p::DECIMAL(15,2), d::DECIMAL(15,2), t::DECIMAL(15,2)]"
1769        );
1770        let plan = Plan::parse(&text).expect("a well formed plan");
1771        let Node::Project { exprs, .. } = *plan.node(plan.root()) else {
1772            panic!("the root of that text is a projection");
1773        };
1774        let expr = plan.expr_list(exprs)[0];
1775        let values = |vector: &Vector| (0..chunk.len()).map(|row| vector.value_at(row)).collect();
1776        let fused = Prepared::one(&plan, expr, schema).expect("resolves");
1777        assert_eq!(fused.fused(), 1, "the whole tree is one step");
1778        let unfused = Prepared::built(&plan, &[expr], schema, false, false).expect("resolves");
1779        assert_eq!(unfused.fused(), 0);
1780        let run = |prepared: &Prepared| {
1781            prepared.evaluate_one(chunk, &mut prepared.scratch()).map(&values)
1782        };
1783        [run(&fused), run(&unfused), evaluate(&plan, expr, schema, chunk).map(|v| values(&v))]
1784    }
1785
1786    fn all_agree(chunk: &Chunk, schema: &Schema) {
1787        let [fused, unfused, walked] = three_ways(chunk, schema);
1788        let fused = fused.expect("fits");
1789        assert_eq!(fused, unfused.expect("fits"));
1790        assert_eq!(fused, walked.expect("fits"));
1791    }
1792
1793    /// The epoch plus a whole count of seconds runs as one call, and agrees with the cast, the
1794    /// interval and the shift it stands for, on both sides of the count where the double stops
1795    /// being exact and on a count that takes the answer out of range.
1796    #[test]
1797    fn a_timestamp_plus_whole_seconds_agrees_with_the_interval_it_stands_for() {
1798        let schema = Schema::numbered(vec![Field::new("x", LogicalType::BigInt)], 0);
1799        let counts = [
1800            Value::BigInt(1_373_000_000),
1801            Value::BigInt(-5),
1802            Value::Null,
1803            Value::BigInt(9_007_199_254),
1804            Value::BigInt(9_007_199_255),
1805            Value::BigInt(9_000_000_000_123),
1806        ];
1807        let x = Vector::from_values(LogicalType::BigInt, &counts).expect("six counts");
1808        let chunk = Chunk::new(vec![x]).expect("one column");
1809        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]";
1810        let plan = Plan::parse(text).expect("a well formed plan");
1811        let Node::Project { exprs, .. } = *plan.node(plan.root()) else {
1812            panic!("the root of that text is a projection");
1813        };
1814        let list = plan.expr_list(exprs).to_vec();
1815        let prepared = Prepared::new(&plan, &list, &schema).expect("the expression resolves");
1816        assert!(
1817            prepared.steps.iter().any(
1818                |step| matches!(step, super::Step::Function { recipe, .. } if recipe.name() == "__rudb_stamp_seconds")
1819            ),
1820            "the shift is one call"
1821        );
1822        let mut scratch = prepared.scratch();
1823        let mut fast = Vec::new();
1824        prepared.evaluate(&chunk, &mut scratch, &mut fast).expect("the prepared form runs");
1825        let slow = evaluate(&plan, list[0], &schema, &chunk).expect("the tree walk runs");
1826        for row in 0..chunk.len() {
1827            assert_eq!(fast[0].value_at(row), slow.value_at(row), "row {row}");
1828        }
1829        assert_eq!(fast[0].value_at(0), Value::Timestamp(1_373_000_000_000_000));
1830
1831        let far = Vector::from_values(LogicalType::BigInt, &[Value::BigInt(9_300_000_000_000)])
1832            .expect("one count");
1833        let chunk = Chunk::new(vec![far]).expect("one column");
1834        let mut fast = Vec::new();
1835        let fused = prepared.evaluate(&chunk, &mut scratch, &mut fast);
1836        let slow = evaluate(&plan, list[0], &schema, &chunk).map(|_| ());
1837        assert!(fused.is_err() && slow.is_err(), "past the last timestamp both raise");
1838    }
1839
1840    #[test]
1841    fn decimal_arithmetic_run_as_one_loop_agrees_in_every_form() {
1842        let prices: Vec<i128> = (0..2500).map(|v| 90_000 + v * 37).collect();
1843        let packed = |vector: Vector| vector.bit_packed().expect("packs");
1844        let coded = |vector: Vector| {
1845            let rows = vector.len();
1846            let codes = (0..rows as u32).rev().collect();
1847            Vector::dictionary(codes, vector.bit_packed().expect("packs")).expect("in range")
1848        };
1849        // Codes too far apart for a block to unpack the run they cover.
1850        let scattered = |vector: Vector| {
1851            let rows = vector.len() as u32;
1852            let codes = (0..rows).map(|row| row * 997 % rows).collect();
1853            Vector::dictionary(codes, vector.bit_packed().expect("packs")).expect("in range")
1854        };
1855        for form in [std::convert::identity, packed, coded, scattered] {
1856            let (schema, chunk) = decimals(&prices, form);
1857            all_agree(&chunk, &schema);
1858        }
1859    }
1860
1861    #[test]
1862    fn a_chunk_the_ranges_cannot_prove_raises_what_the_steps_raise() {
1863        // The large price in the second block, so a flat column gets as far as running the first.
1864        let mut prices = vec![5; 300];
1865        prices.push(999_999_999_999_999);
1866        let packed = |vector: Vector| vector.bit_packed().expect("packs");
1867        for form in [std::convert::identity, packed] {
1868            let (schema, chunk) = decimals(&prices, form);
1869            let [fused, unfused, _] = three_ways(&chunk, &schema);
1870            let (fused, unfused) = (fused.expect_err("overflows"), unfused.expect_err("overflows"));
1871            assert_eq!(fused.message(), unfused.message());
1872        }
1873    }
1874
1875    #[test]
1876    fn a_chunk_with_a_null_goes_through_the_steps() {
1877        let ty = LogicalType::Decimal { width: 15, scale: 2 };
1878        let (schema, mut chunk) = decimals(&[100, 200, 300], std::convert::identity);
1879        let with_null = Vector::from_values(
1880            ty,
1881            &[Value::Decimal { unscaled: 5, width: 15, scale: 2 }, Value::Null, Value::Null],
1882        )
1883        .expect("decimals");
1884        chunk = Chunk::new(vec![
1885            chunk.column(0).expect("p").clone(),
1886            with_null,
1887            chunk.column(2).expect("t").clone(),
1888        ])
1889        .expect("three columns");
1890        all_agree(&chunk, &schema);
1891    }
1892
1893    #[test]
1894    fn a_column_reference_agrees() {
1895        agrees("#0.0::INTEGER AS a, #0.1::VARCHAR AS b");
1896    }
1897
1898    #[test]
1899    fn a_constant_agrees() {
1900        agrees("7::INTEGER AS a, NULL::INTEGER AS b");
1901    }
1902
1903    #[test]
1904    fn a_cast_agrees() {
1905        agrees("CAST(#0.0::INTEGER)::BIGINT AS a, CAST(#0.0::INTEGER)::VARCHAR AS b");
1906    }
1907
1908    #[test]
1909    fn a_comparison_agrees() {
1910        agrees("(#0.0::INTEGER > 1::INTEGER)::BOOLEAN AS a");
1911    }
1912
1913    #[test]
1914    fn a_conjunction_agrees() {
1915        agrees(
1916            "((#0.0::INTEGER > 1::INTEGER)::BOOLEAN AND (#0.0::INTEGER < 3::INTEGER)::BOOLEAN)\
1917             ::BOOLEAN AS a",
1918        );
1919    }
1920
1921    #[test]
1922    fn a_function_agrees() {
1923        agrees("\"+\"(#0.0::INTEGER, 1::INTEGER)::INTEGER AS a");
1924    }
1925
1926    /// The two evaluators quote the same expression when a divisor is zero. Per #262.
1927    ///
1928    /// This is the one message in the engine that depends on how an expression is written rather
1929    /// than on what it computes, and the two evaluators render it at different times: the prepared
1930    /// form when the pipeline is built, the tree walk on the row that fails. Same renderer, so the
1931    /// same sentence, and this is what says so.
1932    #[test]
1933    fn both_evaluators_quote_the_same_expression_when_a_divisor_is_zero() {
1934        let (schema, chunk) = input();
1935        let (plan, list) = projection("\"//\"(#0.0::INTEGER, 0::INTEGER)::INTEGER AS a");
1936        let prepared = Prepared::new(&plan, &list, &schema).expect("the expression resolves");
1937        let mut scratch = prepared.scratch();
1938        let mut out = Vec::new();
1939        let fast = prepared.evaluate(&chunk, &mut scratch, &mut out).expect_err("divides by zero");
1940        let slow = evaluate(&plan, list[0], &schema, &chunk).expect_err("divides by zero");
1941        assert_eq!(fast.message(), slow.message());
1942        assert!(fast.message().starts_with("Division by zero in expression (x // 0)."), "{fast}");
1943    }
1944
1945    #[test]
1946    fn a_case_agrees() {
1947        agrees(
1948            "CASE WHEN (#0.0::INTEGER > 1::INTEGER)::BOOLEAN THEN 10::INTEGER \
1949             ELSE 20::INTEGER END::INTEGER AS a",
1950        );
1951    }
1952
1953    /// A second arm, which is the first one that sees a cut chunk rather than the whole one.
1954    ///
1955    /// The first arm of any `CASE` runs over every row, so it takes the path that does not cut at
1956    /// all, and a `CASE` of one arm never exercises the other one. Two arms and an `ELSE` puts a
1957    /// different set of rows in front of each of the three.
1958    ///
1959    /// That this is the only test here reaching the cut was checked rather than assumed, by gating a
1960    /// panic on it and rerunning the seven. This one failed and the other six did not.
1961    #[test]
1962    fn a_case_of_two_arms_agrees() {
1963        agrees(
1964            "CASE WHEN (#0.0::INTEGER > 2::INTEGER)::BOOLEAN THEN 10::INTEGER \
1965             WHEN (#0.0::INTEGER > 1::INTEGER)::BOOLEAN THEN 20::INTEGER \
1966             ELSE 30::INTEGER END::INTEGER AS a",
1967        );
1968    }
1969
1970    /// No `ELSE`, so the rows no arm claims are null rather than anything.
1971    ///
1972    /// The case a run of data with a hole in it gets wrong: a null still occupies a position, and an
1973    /// assembly that skipped it would put every value after it one row early.
1974    #[test]
1975    fn a_case_with_no_else_agrees() {
1976        agrees(
1977            "CASE WHEN (#0.0::INTEGER > 2::INTEGER)::BOOLEAN THEN 10::INTEGER \
1978             END::INTEGER AS a",
1979        );
1980    }
1981
1982    /// An arm no row takes, so it contributes nothing to the answer and must not shift it.
1983    #[test]
1984    fn a_case_whose_arm_claims_nothing_agrees() {
1985        agrees(
1986            "CASE WHEN (#0.0::INTEGER > 99::INTEGER)::BOOLEAN THEN 10::INTEGER \
1987             ELSE 20::INTEGER END::INTEGER AS a",
1988        );
1989    }
1990
1991    /// Strings, which is the case that used to allocate one of them per row and drop it afterwards.
1992    ///
1993    /// The arm reads a column and the `ELSE` is a constant, which is the shape of the ClickBench
1994    /// query this path was rewritten for: the arm arrives as views over an arena and the `ELSE` as
1995    /// one value repeated, and the two have to be laid end to end into a single arena.
1996    #[test]
1997    fn a_case_over_strings_agrees() {
1998        agrees(
1999            "CASE WHEN (#0.0::INTEGER > 1::INTEGER)::BOOLEAN THEN #0.1::VARCHAR \
2000             ELSE ''::VARCHAR END::VARCHAR AS a",
2001        );
2002    }
2003
2004    /// A null inside an arm, which is a different thing from a row no arm claimed.
2005    ///
2006    /// Both come out null and they reach the validity mask by different routes, so a mask built for
2007    /// one of them and not the other reads correct on whichever test only has the other in it.
2008    #[test]
2009    fn a_case_whose_arm_answers_null_agrees() {
2010        agrees(
2011            "CASE WHEN (#0.0::INTEGER > 1::INTEGER)::BOOLEAN THEN #0.1::VARCHAR \
2012             ELSE NULL::VARCHAR END::VARCHAR AS a",
2013        );
2014    }
2015
2016    /// A `WHEN` over a column that is null on some rows, which is neither true nor false there.
2017    ///
2018    /// A three valued `WHEN` is what decides whether a row goes to the arm or falls through, and
2019    /// treating unknown as true would claim a row the `ELSE` should have had.
2020    #[test]
2021    fn a_case_whose_test_is_null_on_some_rows_agrees() {
2022        agrees(
2023            "CASE WHEN (#0.1::VARCHAR = 'a'::VARCHAR)::BOOLEAN THEN 10::INTEGER \
2024             ELSE 20::INTEGER END::INTEGER AS a",
2025        );
2026    }
2027
2028    /// The same expression twice, which is where the tree walk copies the column twice and this
2029    /// does not, and the answers still have to be identical.
2030    #[test]
2031    fn a_column_mentioned_three_times_agrees() {
2032        agrees("\"+\"(\"+\"(#0.0::INTEGER, #0.0::INTEGER)::INTEGER, #0.0::INTEGER)::INTEGER AS a");
2033    }
2034
2035    /// The intermediates of a chain are not all held to the end of it.
2036    ///
2037    /// This is the whole difference between the prepared form being faster than the tree walk on a
2038    /// deep chain and being slower than it, and it is a property of the slot array rather than of
2039    /// any answer, so it is asserted here rather than left to the benchmark to catch.
2040    #[test]
2041    fn a_chain_holds_one_intermediate_at_a_time() {
2042        let (schema, chunk) = input();
2043        let mut expr = "#0.0::INTEGER".to_string();
2044        for _ in 0..8 {
2045            expr = format!("\"+\"({expr}, 1::INTEGER)::INTEGER");
2046        }
2047        let (plan, list) = projection(&format!("{expr} AS a"));
2048        let prepared = Prepared::new(&plan, &list, &schema).expect("the chain resolves");
2049        let mut scratch = prepared.scratch();
2050        prepared.run(&chunk, &mut scratch).expect("the chain runs");
2051        let live = scratch.slots.iter().filter(|slot| slot.is_some()).count();
2052        assert_eq!(live, 1, "a chain that has run should be holding its answer and nothing else");
2053    }
2054
2055    /// The rows a threaded filter keeps are the rows the tree walk says the predicate is true for.
2056    ///
2057    /// Every threaded conjunct is a chance to disagree with the unthreaded answer about a null,
2058    /// about a row an earlier conjunct had already dropped, or about a chunk nothing survives, and
2059    /// the answer is a set of row numbers rather than a vector, so this is checked against the tree
2060    /// walk read a row at a time rather than against the prepared form it is part of.
2061    fn filters(predicate: &str) {
2062        let (schema, chunk) = input();
2063        let (plan, list) = projection(&format!("{predicate} AS p"));
2064        let prepared = Prepared::new(&plan, &list, &schema).expect("the predicate resolves");
2065        let mut scratch = prepared.scratch();
2066        let threaded = prepared.evaluate_filter(&chunk, &mut scratch).expect("the filter runs");
2067        let flags = evaluate(&plan, list[0], &schema, &chunk).expect("the tree walk runs");
2068        let expected = Selection::from_predicate(chunk.len(), |row| is_true(&flags.value_at(row)));
2069        assert_eq!(threaded, expected, "`{predicate}`");
2070        // And running it again over the same scratch is the same answer, because a pipeline calls
2071        // this once a chunk and a slot left behind by the conjunct before would show up here.
2072        let again = prepared.evaluate_filter(&chunk, &mut scratch).expect("the filter runs again");
2073        assert_eq!(again, expected, "`{predicate}` a second time");
2074    }
2075
2076    /// A predicate with no `AND` in it is not threaded and has to keep saying the same thing.
2077    #[test]
2078    fn a_single_comparison_filters_the_same_rows() {
2079        filters("(#0.0::INTEGER > 1::INTEGER)::BOOLEAN");
2080        filters("(#0.1::VARCHAR = 'a'::VARCHAR)::BOOLEAN");
2081        filters("(#0.0::INTEGER IS NOT DISTINCT FROM NULL::INTEGER)::BOOLEAN");
2082    }
2083
2084    #[test]
2085    fn a_chain_of_conjuncts_keeps_what_all_of_them_keep() {
2086        filters(
2087            "((#0.0::INTEGER > 1::INTEGER)::BOOLEAN AND (#0.0::INTEGER < 3::INTEGER)::BOOLEAN)\
2088             ::BOOLEAN",
2089        );
2090        filters(
2091            "((#0.0::INTEGER >= 1::INTEGER)::BOOLEAN AND (#0.0::INTEGER <= 3::INTEGER)::BOOLEAN \
2092             AND (#0.1::VARCHAR = 'a'::VARCHAR)::BOOLEAN AND (#0.0::INTEGER <> 2::INTEGER)\
2093             ::BOOLEAN)::BOOLEAN",
2094        );
2095    }
2096
2097    /// An operand the caller says is settled is not run, which shows as the rows it would have
2098    /// thrown away coming through: the answer is the other operand's alone. Settling nothing, or
2099    /// handing over the wrong number of operands, is the plain filter.
2100    #[test]
2101    fn a_settled_conjunct_is_left_out_of_the_filter() {
2102        let (schema, chunk) = input();
2103        let both = "((#0.0::INTEGER > 1::INTEGER)::BOOLEAN AND (#0.0::INTEGER < 3::INTEGER)::BOOLEAN)\
2104                    ::BOOLEAN AS p";
2105        let (plan, list) = projection(both);
2106        let prepared = Prepared::new(&plan, &list, &schema).expect("the predicate resolves");
2107        assert_eq!(prepared.conjuncts(), Some(2));
2108        let mut scratch = prepared.scratch();
2109        let wanted = |predicate: &str| {
2110            let (plan, list) = projection(&format!("{predicate} AS p"));
2111            let flags = evaluate(&plan, list[0], &schema, &chunk).expect("the tree walk runs");
2112            Selection::from_predicate(chunk.len(), |row| is_true(&flags.value_at(row)))
2113        };
2114        let second = prepared.evaluate_settled(&chunk, &mut scratch, &[true, false]);
2115        assert_eq!(
2116            second.expect("the filter runs"),
2117            wanted("(#0.0::INTEGER < 3::INTEGER)::BOOLEAN")
2118        );
2119        let first = prepared.evaluate_settled(&chunk, &mut scratch, &[false, true]);
2120        assert_eq!(
2121            first.expect("the filter runs"),
2122            wanted("(#0.0::INTEGER > 1::INTEGER)::BOOLEAN")
2123        );
2124        let neither = prepared.evaluate_settled(&chunk, &mut scratch, &[true, true]);
2125        assert_eq!(neither.expect("the filter runs"), Selection::identity(chunk.len()));
2126        let whole = wanted(&both[..both.len() - " AS p".len()]);
2127        let none = prepared.evaluate_settled(&chunk, &mut scratch, &[false, false]);
2128        assert_eq!(none.expect("the filter runs"), whole);
2129        let short = prepared.evaluate_settled(&chunk, &mut scratch, &[true]);
2130        assert_eq!(short.expect("the filter runs"), whole, "a list that does not fit is ignored");
2131    }
2132
2133    /// A conjunct that rejects every row, in front of one that would have kept some. The rows are
2134    /// the same either way and the point of the shape is that the second conjunct never runs.
2135    #[test]
2136    fn a_conjunct_that_keeps_nothing_ends_the_predicate() {
2137        filters(
2138            "((#0.0::INTEGER > 9::INTEGER)::BOOLEAN AND (#0.0::INTEGER < 9::INTEGER)::BOOLEAN)\
2139             ::BOOLEAN",
2140        );
2141    }
2142
2143    /// A conjunct whose operands are computed rather than read, which is the shape where the
2144    /// comparison is threaded and the arithmetic under it is not.
2145    #[test]
2146    fn a_conjunct_over_a_computed_operand_keeps_the_same_rows() {
2147        filters(
2148            "((#0.0::INTEGER > 1::INTEGER)::BOOLEAN AND \
2149             (\"+\"(#0.0::INTEGER, 1::INTEGER)::INTEGER < 4::INTEGER)::BOOLEAN)::BOOLEAN",
2150        );
2151    }
2152
2153    /// A conjunct that is not a comparison at all, which is the one that goes through the flag
2154    /// kernel rather than the comparison kernel.
2155    #[test]
2156    fn a_conjunct_that_is_not_a_comparison_is_threaded_too() {
2157        filters(
2158            "((#0.0::INTEGER > 1::INTEGER)::BOOLEAN AND ((#0.1::VARCHAR = 'a'::VARCHAR)::BOOLEAN \
2159             OR (#0.0::INTEGER = 1::INTEGER)::BOOLEAN)::BOOLEAN)::BOOLEAN",
2160        );
2161        filters(
2162            "(((#0.1::VARCHAR = 'c'::VARCHAR)::BOOLEAN OR (#0.0::INTEGER = 3::INTEGER)::BOOLEAN)\
2163             ::BOOLEAN AND (#0.0::INTEGER <> 1::INTEGER)::BOOLEAN)::BOOLEAN",
2164        );
2165    }
2166
2167    #[test]
2168    fn a_selective_conjunct_evaluates_later_like_on_its_survivors() {
2169        filters(
2170            "((#0.0::INTEGER > 2::INTEGER)::BOOLEAN AND \
2171             \"~~\"(#0.1::VARCHAR, '%a%'::VARCHAR)::BOOLEAN)::BOOLEAN",
2172        );
2173        filters(
2174            "((#0.0::INTEGER > 2::INTEGER)::BOOLEAN AND \
2175             \"!~~\"(#0.1::VARCHAR, '%a%'::VARCHAR)::BOOLEAN)::BOOLEAN",
2176        );
2177    }
2178
2179    /// An `OR` at the top threads the complement: the second branch only sees the rows the first
2180    /// one did not accept, and the rows it accepts are added to them rather than replacing them.
2181    ///
2182    /// The input has a row where the first branch is true, one where the second is, one where both
2183    /// are false and one where the first is null and the second is true, which is the row that says
2184    /// whether the complement was taken over "not true" or over "false".
2185    #[test]
2186    fn an_or_at_the_top_threads_the_complement() {
2187        filters(
2188            "((#0.0::INTEGER > 2::INTEGER)::BOOLEAN OR (#0.1::VARCHAR = 'c'::VARCHAR)::BOOLEAN)\
2189             ::BOOLEAN",
2190        );
2191        filters(
2192            "((#0.0::INTEGER = 1::INTEGER)::BOOLEAN OR (#0.1::VARCHAR = 'a'::VARCHAR)::BOOLEAN \
2193             OR (#0.0::INTEGER > 2::INTEGER)::BOOLEAN)::BOOLEAN",
2194        );
2195    }
2196
2197    /// A branch that accepts every row, in front of one that would have accepted none. The rows are
2198    /// the same either way and the point of the shape is that the second branch never runs.
2199    #[test]
2200    fn a_branch_that_keeps_everything_ends_the_predicate() {
2201        filters(
2202            "((#0.0::INTEGER IS NOT DISTINCT FROM #0.0::INTEGER)::BOOLEAN OR \
2203             (#0.0::INTEGER > 9::INTEGER)::BOOLEAN)::BOOLEAN",
2204        );
2205    }
2206
2207    /// The branches after one that has accepted every row really are skipped.
2208    ///
2209    /// Every other test here says the threaded answer matches the unthreaded one, which it would
2210    /// even if nothing were threaded at all. This one puts a division by zero behind a branch that
2211    /// accepts everything, so the predicate raises if the second branch runs and does not if the
2212    /// walk stopped where it was supposed to.
2213    #[test]
2214    fn a_branch_behind_one_that_accepted_every_row_does_not_run() {
2215        let (schema, chunk) = input();
2216        let predicate = "((#0.0::INTEGER IS NOT DISTINCT FROM #0.0::INTEGER)::BOOLEAN OR \
2217                         (\"//\"(#0.0::INTEGER, 0::INTEGER)::INTEGER > 0::INTEGER)::BOOLEAN)\
2218                         ::BOOLEAN";
2219        let (plan, list) = projection(&format!("{predicate} AS p"));
2220        let prepared = Prepared::new(&plan, &list, &schema).expect("the predicate resolves");
2221        let mut scratch = prepared.scratch();
2222        let kept =
2223            prepared.evaluate_filter(&chunk, &mut scratch).expect("the second branch never runs");
2224        assert_eq!(kept, Selection::identity(chunk.len()));
2225        // And the same predicate evaluated as an expression does divide by zero, which is what says
2226        // the test is testing the threading rather than a predicate that happens not to raise.
2227        evaluate(&plan, list[0], &schema, &chunk).expect_err("the tree walk divides by zero");
2228    }
2229
2230    /// The conjunct that rejects the most rows ends up in front of the one that rejects none.
2231    ///
2232    /// The predicate is written the wrong way round on purpose. The plan order costs two passes a
2233    /// chunk where one would do, and after a chunk of watching it the filter runs the selective one
2234    /// first and the other one stops running at all.
2235    #[test]
2236    fn a_filter_learns_which_conjunct_to_run_first() {
2237        let (schema, chunk) = input();
2238        let predicate = "((#0.0::INTEGER > 0::INTEGER)::BOOLEAN AND (#0.0::INTEGER > 9::INTEGER)\
2239                         ::BOOLEAN)::BOOLEAN";
2240        let (plan, list) = projection(&format!("{predicate} AS p"));
2241        let prepared = Prepared::new(&plan, &list, &schema).expect("the predicate resolves");
2242        let mut scratch = prepared.scratch();
2243        let root = prepared.roots[0];
2244        assert_eq!(scratch.order(root), None, "nothing has run yet");
2245        let kept = prepared.evaluate_filter(&chunk, &mut scratch).expect("the filter runs");
2246        assert!(kept.is_empty());
2247        assert_eq!(scratch.order(root), Some(&[1, 0][..]), "the second conjunct rejects the most");
2248        // And it stays there, because the conjunct that now runs first empties the selection and
2249        // the one behind it keeps the history it already had rather than losing it.
2250        let kept = prepared.evaluate_filter(&chunk, &mut scratch).expect("the filter runs again");
2251        assert!(kept.is_empty());
2252        assert_eq!(scratch.order(root), Some(&[1, 0][..]));
2253    }
2254
2255    /// Whatever order it settles on, the rows are the rows.
2256    ///
2257    /// Run for longer than the window is wide, because an order that changes halfway through a scan
2258    /// is the shape where a walk that got the subtree bookkeeping wrong would start reading the
2259    /// wrong steps, and the first chunk would not show it.
2260    #[test]
2261    fn reordering_never_changes_which_rows_survive() {
2262        let (schema, chunk) = input();
2263        let predicate = "((#0.0::INTEGER >= 1::INTEGER)::BOOLEAN AND \
2264                         (\"+\"(#0.0::INTEGER, 1::INTEGER)::INTEGER < 4::INTEGER)::BOOLEAN AND \
2265                         (#0.1::VARCHAR = 'a'::VARCHAR)::BOOLEAN)::BOOLEAN";
2266        let (plan, list) = projection(&format!("{predicate} AS p"));
2267        let prepared = Prepared::new(&plan, &list, &schema).expect("the predicate resolves");
2268        let mut scratch = prepared.scratch();
2269        let flags = evaluate(&plan, list[0], &schema, &chunk).expect("the tree walk runs");
2270        let expected = Selection::from_predicate(chunk.len(), |row| is_true(&flags.value_at(row)));
2271        for round in 0..40 {
2272            let kept = prepared.evaluate_filter(&chunk, &mut scratch).expect("the filter runs");
2273            assert_eq!(kept, expected, "round {round}");
2274        }
2275    }
2276
2277    /// A nested connective is threaded rather than evaluated into flags.
2278    ///
2279    /// The inner `AND` keeps nothing, so its second conjunct is never reached and the division by
2280    /// zero in it never happens. Evaluating the branch as an expression and narrowing the flags
2281    /// afterwards, which is what an operand that is not a connective still does, would have run it.
2282    #[test]
2283    fn a_nested_connective_stops_where_the_outer_one_would() {
2284        let (schema, chunk) = input();
2285        let predicate = "((#0.0::INTEGER > 9::INTEGER)::BOOLEAN OR ((#0.0::INTEGER > 9::INTEGER)\
2286                         ::BOOLEAN AND (\"//\"(#0.0::INTEGER, 0::INTEGER)::INTEGER > 0::INTEGER)\
2287                         ::BOOLEAN)::BOOLEAN)::BOOLEAN";
2288        let (plan, list) = projection(&format!("{predicate} AS p"));
2289        let prepared = Prepared::new(&plan, &list, &schema).expect("the predicate resolves");
2290        let mut scratch = prepared.scratch();
2291        let kept =
2292            prepared.evaluate_filter(&chunk, &mut scratch).expect("the division never happens");
2293        assert!(kept.is_empty());
2294        evaluate(&plan, list[0], &schema, &chunk).expect_err("the tree walk divides by zero");
2295    }
2296
2297    /// A branch that is not a comparison, which is the one that goes through the flag kernel.
2298    #[test]
2299    fn an_or_branch_that_is_not_a_comparison_is_threaded_too() {
2300        filters(
2301            "((#0.0::INTEGER > 2::INTEGER)::BOOLEAN OR \
2302             \"~~\"(#0.1::VARCHAR, 'a%'::VARCHAR)::BOOLEAN)::BOOLEAN",
2303        );
2304        filters(
2305            "(\"~~\"(#0.1::VARCHAR, 'c%'::VARCHAR)::BOOLEAN OR (#0.0::INTEGER = 1::INTEGER)\
2306             ::BOOLEAN)::BOOLEAN",
2307        );
2308    }
2309
2310    /// A connective inside a connective, which recurses rather than falling back to flags.
2311    ///
2312    /// Both nestings, because the two carry opposite things: an `AND` under an `OR` starts from the
2313    /// rows no branch has accepted, and an `OR` under an `AND` starts from the rows every conjunct
2314    /// has kept, and getting either one backwards is a wrong set of rows.
2315    #[test]
2316    fn a_connective_inside_a_connective_threads_both_ways() {
2317        filters(
2318            "(((#0.0::INTEGER >= 2::INTEGER)::BOOLEAN AND (#0.1::VARCHAR = 'a'::VARCHAR)::BOOLEAN)\
2319             ::BOOLEAN OR ((#0.0::INTEGER < 2::INTEGER)::BOOLEAN AND (#0.1::VARCHAR <> 'c'\
2320             ::VARCHAR)::BOOLEAN)::BOOLEAN)::BOOLEAN",
2321        );
2322        filters(
2323            "(((#0.1::VARCHAR = 'c'::VARCHAR)::BOOLEAN OR (#0.0::INTEGER = 3::INTEGER)::BOOLEAN)\
2324             ::BOOLEAN AND ((#0.0::INTEGER <> 1::INTEGER)::BOOLEAN OR (#0.1::VARCHAR = 'a'\
2325             ::VARCHAR)::BOOLEAN)::BOOLEAN)::BOOLEAN",
2326        );
2327        // Three deep, since two levels is where an off by one in the subtree bookkeeping can still
2328        // be hidden by the ranges lining up.
2329        filters(
2330            "((#0.0::INTEGER > 9::INTEGER)::BOOLEAN OR ((#0.0::INTEGER >= 1::INTEGER)::BOOLEAN \
2331             AND ((#0.1::VARCHAR = 'a'::VARCHAR)::BOOLEAN OR (#0.0::INTEGER = 1::INTEGER)\
2332             ::BOOLEAN)::BOOLEAN)::BOOLEAN)::BOOLEAN",
2333        );
2334    }
2335
2336    /// A predicate where one side is null and the other is true, in both orders. `OR` is true there
2337    /// and a complement taken over the rows a branch rejected rather than the rows it accepted
2338    /// would drop the row, which is the one way this can be wrong and is not a wrong vector but a
2339    /// missing row.
2340    #[test]
2341    fn a_null_branch_beside_a_true_one_keeps_the_row() {
2342        filters(
2343            "((#0.0::INTEGER > 2::INTEGER)::BOOLEAN OR (#0.1::VARCHAR = 'c'::VARCHAR)::BOOLEAN \
2344             OR (#0.0::INTEGER IS NOT DISTINCT FROM NULL::INTEGER)::BOOLEAN)::BOOLEAN",
2345        );
2346        filters(
2347            "((#0.1::VARCHAR > 'b'::VARCHAR)::BOOLEAN OR (#0.0::INTEGER = 1::INTEGER)::BOOLEAN)\
2348             ::BOOLEAN",
2349        );
2350    }
2351
2352    /// A filter over a chunk that has already been narrowed, which is what a second filter in a
2353    /// pipeline sees and is the form pair the threaded kernels have to handle rather than fall
2354    /// through on.
2355    #[test]
2356    fn a_filter_over_a_selected_chunk_keeps_the_same_rows() {
2357        let (schema, chunk) = input();
2358        let predicate = "((#0.0::INTEGER >= 1::INTEGER)::BOOLEAN AND \
2359                         (#0.1::VARCHAR = 'a'::VARCHAR)::BOOLEAN)::BOOLEAN";
2360        let (plan, list) = projection(&format!("{predicate} AS p"));
2361        let prepared = Prepared::new(&plan, &list, &schema).expect("the predicate resolves");
2362        let mut scratch = prepared.scratch();
2363        let narrowed = narrow(&chunk, &[0, 3]).expect("two of the four rows");
2364        let threaded = prepared.evaluate_filter(&narrowed, &mut scratch).expect("the filter runs");
2365        let flags = evaluate(&plan, list[0], &schema, &narrowed).expect("the tree walk runs");
2366        let expected =
2367            Selection::from_predicate(narrowed.len(), |row| is_true(&flags.value_at(row)));
2368        assert_eq!(threaded, expected);
2369    }
2370
2371    /// Preparing is per pipeline and evaluating is per chunk, so the scratch has to survive being
2372    /// used again and give the same answer the second time.
2373    #[test]
2374    fn a_scratch_used_twice_gives_the_same_answer_twice() {
2375        let (schema, chunk) = input();
2376        let (plan, list) = projection("\"+\"(#0.0::INTEGER, 1::INTEGER)::INTEGER AS a");
2377        let prepared = Prepared::new(&plan, &list, &schema).expect("the expressions resolve");
2378        let mut scratch = prepared.scratch();
2379        let mut once = Vec::new();
2380        prepared.evaluate(&chunk, &mut scratch, &mut once).expect("the first chunk runs");
2381        let mut twice = Vec::new();
2382        prepared.evaluate(&chunk, &mut scratch, &mut twice).expect("the second chunk runs");
2383        assert_eq!(once, twice);
2384    }
2385
2386    #[test]
2387    fn taking_the_chunk_answers_what_borrowing_it_does() {
2388        let (schema, chunk) = input();
2389        let (plan, list) = projection(
2390            "#0.0::INTEGER AS a, \"+\"(#0.0::INTEGER, 1::INTEGER)::INTEGER AS b, #0.0::INTEGER AS c",
2391        );
2392        let prepared = Prepared::new(&plan, &list, &schema).expect("the expressions resolve");
2393        let mut scratch = prepared.scratch();
2394        let mut borrowed = Vec::new();
2395        prepared.evaluate(&chunk, &mut scratch, &mut borrowed).expect("the borrowed chunk runs");
2396        let mut taken = Vec::new();
2397        prepared.evaluate_taking(chunk, &mut scratch, &mut taken).expect("the taken chunk runs");
2398        assert_eq!(borrowed, taken);
2399    }
2400
2401    #[test]
2402    fn a_shared_computed_root_is_compiled_once() {
2403        let (schema, chunk) = input();
2404        let (plan, list) = projection("\"+\"(#0.0::INTEGER, 1::INTEGER)::INTEGER AS a");
2405        let prepared = Prepared::shared(&plan, &[list[0], list[0]], &schema)
2406            .expect("the shared expression resolves");
2407        assert_eq!(prepared.steps.len(), 3);
2408        let mut scratch = prepared.scratch();
2409        let mut answers = Vec::new();
2410        prepared.evaluate(&chunk, &mut scratch, &mut answers).expect("both roots are returned");
2411        assert_eq!(answers[0], answers[1]);
2412    }
2413
2414    /// A chunk shorter than the last one, because a scan's final chunk is that and a constant
2415    /// materialized to the wrong length would be an out of range read rather than a wrong answer.
2416    #[test]
2417    fn a_shorter_chunk_after_a_longer_one_is_evaluated_at_its_own_length() {
2418        let (schema, chunk) = input();
2419        let (plan, list) = projection("7::INTEGER AS a");
2420        let prepared = Prepared::new(&plan, &list, &schema).expect("the expressions resolve");
2421        let mut scratch = prepared.scratch();
2422        let mut full = Vec::new();
2423        prepared.evaluate(&chunk, &mut scratch, &mut full).expect("the full chunk runs");
2424        assert_eq!(full[0].len(), 4);
2425        let short = chunk
2426            .clone()
2427            .select(&{
2428                let mut selection = Selection::with_capacity(2);
2429                selection.push(0);
2430                selection.push(2);
2431                selection
2432            })
2433            .expect("two of the four rows");
2434        let mut cut = Vec::new();
2435        prepared.evaluate(&short, &mut scratch, &mut cut).expect("the short chunk runs");
2436        assert_eq!(cut[0].len(), 2);
2437    }
2438
2439    /// An aggregate is not an expression and saying so when the pipeline is built is better than
2440    /// saying it on the first chunk.
2441    #[test]
2442    fn an_aggregate_is_refused_when_it_is_prepared() {
2443        let (schema, _) = input();
2444        let text = "Aggregate #1 groups=[] aggregates=[sum(#0.0::INTEGER)::HUGEINT]\n  \
2445                    Get memory.main.t AS t #0 [x::INTEGER, s::VARCHAR]";
2446        let plan = Plan::parse(text).expect("a well formed plan");
2447        let Node::Aggregate { aggregates, .. } = *plan.node(plan.root()) else {
2448            panic!("the root of that text is an aggregate");
2449        };
2450        let list = plan.expr_list(aggregates).to_vec();
2451        let error = Prepared::new(&plan, &list, &schema).expect_err("sum is not a scalar");
2452        assert!(error.message().contains("sum"), "{error}");
2453    }
2454
2455    /// How many of an expression's function steps worked something out when it was prepared, and
2456    /// whether the answer it gives is still the tree walk's answer.
2457    ///
2458    /// The count is the point of the assertion, because an answer that moved would be a bug. The
2459    /// agreement is what says the answer did not move.
2460    fn prepares(expr: &str, lifted: usize) {
2461        let (schema, _) = input();
2462        let projected = format!("{expr} AS a");
2463        let (plan, list) = projection(&projected);
2464        let prepared = Prepared::new(&plan, &list, &schema).expect("the expression resolves");
2465        assert_eq!(prepared.hoisted(), lifted, "`{expr}`");
2466        agrees(&projected);
2467    }
2468
2469    /// A pattern the user wrote is compiled where the plan is, which is once.
2470    #[test]
2471    fn a_literal_pattern_is_compiled_when_the_pipeline_is_built() {
2472        prepares("\"~~\"(#0.1::VARCHAR, 'a%'::VARCHAR)::BOOLEAN", 1);
2473        prepares("\"~~*\"(#0.1::VARCHAR, '%A%'::VARCHAR)::BOOLEAN", 1);
2474    }
2475
2476    /// A regular expression, which is the one where the compiling is worth real time.
2477    ///
2478    /// ClickBench query 29 runs one pattern over a hundred million rows, which is a hundred thousand
2479    /// chunks, and before this each of those hundred thousand compiled the pattern again.
2480    #[test]
2481    fn a_regular_expression_is_compiled_when_the_pipeline_is_built() {
2482        prepares("\"regexp_matches\"(#0.1::VARCHAR, '^a'::VARCHAR)::BOOLEAN", 1);
2483        prepares("\"regexp_replace\"(#0.1::VARCHAR, 'a'::VARCHAR, 'b'::VARCHAR)::VARCHAR", 1);
2484    }
2485
2486    /// A pattern that is not a literal, which is legal SQL and is decided per chunk as it was.
2487    #[test]
2488    fn a_pattern_that_is_not_a_literal_is_left_to_the_chunk() {
2489        prepares("\"~~\"(#0.1::VARCHAR, #0.1::VARCHAR)::BOOLEAN", 0);
2490    }
2491
2492    /// A function with nothing to work out, which is almost all of them.
2493    #[test]
2494    fn a_function_with_no_prepare_step_prepares_nothing() {
2495        prepares("\"upper\"(#0.1::VARCHAR)::VARCHAR", 0);
2496    }
2497
2498    /// How many of an expression's steps are a folded `IN`, and whether the answer still agrees.
2499    fn folds(expr: &str, sets: usize) {
2500        let (schema, _) = input();
2501        let projected = format!("{expr} AS a");
2502        let (plan, list) = projection(&projected);
2503        let prepared = Prepared::new(&plan, &list, &schema).expect("the expression resolves");
2504        assert_eq!(prepared.sets(), sets, "`{expr}`");
2505        agrees(&projected);
2506    }
2507
2508    /// What the binder writes for `x IN (1, 3)`, folded back into one lookup.
2509    ///
2510    /// The test goes through the plan's text, where the three mentions of the column are three
2511    /// expressions rather than one, which is the case `same` exists for. A plan the binder built has
2512    /// one mention and takes the first line of it.
2513    #[test]
2514    fn an_in_list_becomes_one_lookup() {
2515        folds(
2516            "((#0.0::INTEGER = 1::INTEGER)::BOOLEAN OR (#0.0::INTEGER = 3::INTEGER)::BOOLEAN)\
2517             ::BOOLEAN",
2518            1,
2519        );
2520        folds(
2521            "((#0.1::VARCHAR = 'a'::VARCHAR)::BOOLEAN OR (#0.1::VARCHAR = 'z'::VARCHAR)::BOOLEAN)\
2522             ::BOOLEAN",
2523            1,
2524        );
2525    }
2526
2527    /// `NOT IN`, which the binder writes as an `AND` of inequalities and which reads the same
2528    /// lookup the other way round.
2529    #[test]
2530    fn a_not_in_list_becomes_the_same_lookup() {
2531        folds(
2532            "((#0.0::INTEGER <> 1::INTEGER)::BOOLEAN AND (#0.0::INTEGER <> 3::INTEGER)::BOOLEAN)\
2533             ::BOOLEAN",
2534            1,
2535        );
2536    }
2537
2538    /// A list with a null in it, which is the rule that makes an `IN` not a set lookup.
2539    ///
2540    /// A row that is not in the list is null rather than false, because it might have equalled the
2541    /// value the null stands for. `agrees` is what says the fold kept that, since the `OR` of
2542    /// comparisons it is checked against gets it from three valued logic for free.
2543    #[test]
2544    fn a_list_with_a_null_in_it_folds_and_keeps_the_null_rule() {
2545        folds(
2546            "((#0.0::INTEGER = 1::INTEGER)::BOOLEAN OR (#0.0::INTEGER = NULL::INTEGER)::BOOLEAN \
2547             OR (#0.0::INTEGER = 3::INTEGER)::BOOLEAN)::BOOLEAN",
2548            1,
2549        );
2550        folds(
2551            "((#0.0::INTEGER <> 1::INTEGER)::BOOLEAN AND (#0.0::INTEGER <> NULL::INTEGER)\
2552             ::BOOLEAN AND (#0.0::INTEGER <> 3::INTEGER)::BOOLEAN)::BOOLEAN",
2553            1,
2554        );
2555    }
2556
2557    /// The connectives that are not an `IN`, each for its own reason.
2558    #[test]
2559    fn a_connective_that_is_not_an_in_list_is_left_alone() {
2560        // Two different columns.
2561        folds(
2562            "((#0.0::INTEGER = 1::INTEGER)::BOOLEAN OR (#0.1::VARCHAR = 'a'::VARCHAR)::BOOLEAN)\
2563             ::BOOLEAN",
2564            0,
2565        );
2566        // One equality and one of something else.
2567        folds(
2568            "((#0.0::INTEGER = 1::INTEGER)::BOOLEAN OR (#0.0::INTEGER > 3::INTEGER)::BOOLEAN)\
2569             ::BOOLEAN",
2570            0,
2571        );
2572        // The right hand side is a column rather than a literal.
2573        folds(
2574            "((#0.0::INTEGER = 1::INTEGER)::BOOLEAN OR (#0.0::INTEGER = #0.0::INTEGER)::BOOLEAN)\
2575             ::BOOLEAN",
2576            0,
2577        );
2578        // An `AND` of equalities is not a `NOT IN`, it is a predicate that is false unless the two
2579        // literals are the same. Folding it as one would answer true where it answers false.
2580        folds(
2581            "((#0.0::INTEGER = 1::INTEGER)::BOOLEAN AND (#0.0::INTEGER = 3::INTEGER)::BOOLEAN)\
2582             ::BOOLEAN",
2583            0,
2584        );
2585    }
2586
2587    /// The same thing in a filter, which is the shape it is written in.
2588    #[test]
2589    fn an_in_list_filters_the_same_rows() {
2590        filters(
2591            "((#0.0::INTEGER = 1::INTEGER)::BOOLEAN OR (#0.0::INTEGER = 3::INTEGER)::BOOLEAN)\
2592             ::BOOLEAN",
2593        );
2594        filters(
2595            "((#0.0::INTEGER <> 1::INTEGER)::BOOLEAN AND (#0.0::INTEGER <> 3::INTEGER)::BOOLEAN)\
2596             ::BOOLEAN",
2597        );
2598        // Inside a larger predicate, where the fold is one operand of the connective above it.
2599        filters(
2600            "(((#0.0::INTEGER = 1::INTEGER)::BOOLEAN OR (#0.0::INTEGER = 3::INTEGER)::BOOLEAN)\
2601             ::BOOLEAN AND (#0.1::VARCHAR = 'a'::VARCHAR)::BOOLEAN)::BOOLEAN",
2602        );
2603    }
2604
2605    /// The literal side of a comparison is turned into a column when the pipeline is built.
2606    #[test]
2607    fn a_comparison_against_a_literal_builds_it_once() {
2608        let (schema, _) = input();
2609        for (expr, built) in [
2610            ("(#0.1::VARCHAR = 'a'::VARCHAR)::BOOLEAN AS p", 1),
2611            ("(#0.0::INTEGER > 1::INTEGER)::BOOLEAN AS p", 1),
2612            // The literal on the left, which is the same comparison written the other way round.
2613            ("(1::INTEGER < #0.0::INTEGER)::BOOLEAN AS p", 1),
2614            // Two columns, which has no literal side to build.
2615            ("(#0.0::INTEGER = #0.0::INTEGER)::BOOLEAN AS p", 0),
2616            // Two literals, which the kernel answers once for the whole vector without reading a
2617            // column, so building one would be work that nothing reads.
2618            ("(1::INTEGER = 2::INTEGER)::BOOLEAN AS p", 0),
2619        ] {
2620            let (plan, list) = projection(expr);
2621            let prepared = Prepared::new(&plan, &list, &schema).expect("the expression resolves");
2622            assert_eq!(prepared.literals_built(), built, "`{expr}`");
2623            agrees(expr);
2624        }
2625    }
2626
2627    /// A pattern that does not compile still fails where the query said it does.
2628    ///
2629    /// Preparing is not allowed to move an error earlier. Compiling at build time and reporting
2630    /// there would raise before a row had been read, and under a `CASE` arm it would raise on a
2631    /// query whose rows never reach the call at all.
2632    #[test]
2633    fn a_pattern_that_does_not_compile_fails_on_the_chunk_and_not_before() {
2634        let (schema, chunk) = input();
2635        let (plan, list) =
2636            projection("\"regexp_matches\"(#0.1::VARCHAR, 'a('::VARCHAR)::BOOLEAN AS a");
2637        let prepared = Prepared::new(&plan, &list, &schema).expect("preparing does not compile it");
2638        assert_eq!(prepared.hoisted(), 0);
2639        let mut scratch = prepared.scratch();
2640        let mut out = Vec::new();
2641        prepared.evaluate(&chunk, &mut scratch, &mut out).expect_err("the chunk raises");
2642    }
2643}