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 /// Evaluates a single expression over `chunk`, handing back a reference to the answer.
538 ///
539 /// A reference rather than a vector, because the caller of this is a filter, which reads the
540 /// flags to build a selection and then drops them. Nothing about that wants ownership, and a
541 /// predicate that is a bare column reference, which `WHERE flag` is, would otherwise copy the
542 /// column to hand it over.
543 ///
544 /// # Errors
545 ///
546 /// Anything a kernel reports, and an internal error if this was not built from exactly one
547 /// expression.
548 pub fn evaluate_one<'s>(
549 &'s self,
550 chunk: &'s Chunk,
551 scratch: &'s mut Scratch,
552 ) -> Result<&'s Vector> {
553 let [root] = self.roots[..] else {
554 return Err(Error::internal(format!(
555 "evaluate_one over a prepared expression of {} roots",
556 self.roots.len()
557 )));
558 };
559 self.run(chunk, scratch)?;
560 self.operand(root, chunk, &scratch.slots)
561 }
562
563 /// Evaluates a single expression as a filter, handing back the rows it keeps.
564 ///
565 /// The difference between this and [`evaluate_one`](Self::evaluate_one) followed by
566 /// [`selection`] is the whole of what a threaded filter is. An `AND` evaluated as an expression
567 /// runs every conjunct over every row and then combines the flag vectors, so a predicate of four
568 /// conjuncts that each pass a fifth of the rows does five times the work of one that stops
569 /// looking at a row as soon as a conjunct rejects it. TPC-H Q6 is exactly that predicate.
570 ///
571 /// So the conjuncts of a top level `AND` are run one at a time, each over the rows the ones
572 /// before it left, and the moment nothing is left the rest of the predicate is not run at all.
573 /// The order they run in starts as the order the plan gives and then moves, because which
574 /// conjunct is worth running first is a question about the data and the scan is the thing
575 /// holding the answer. The `ordering` module has what is measured and how.
576 ///
577 /// A top level `OR` is threaded the same way against the complement. A row the first branch
578 /// accepts is a row the filter keeps whatever the rest of the predicate says about it, so each
579 /// branch is run over the rows no branch before it accepted, and the moment every row has been
580 /// accepted the rest of the predicate is not run either. That is the mirror of the `AND` case
581 /// and not an approximation of it: the answer is the same set of rows, because `OR` over three
582 /// valued logic is true wherever any branch is true and nothing a later branch says can take a
583 /// row back. It is worth less than the `AND` case in practice, since an `OR` of selective
584 /// branches leaves almost every row in play for the branch after, and it is worth having anyway
585 /// because the cost of finding that out is one merge per branch.
586 ///
587 /// What is threaded is the operand's own comparison rather than the whole of its subtree. A
588 /// conjunct of `a + b > 5` still adds over the whole chunk, because the scalar kernels take a
589 /// vector rather than a selection, and it is the comparison and everything downstream of it that
590 /// reads only the rows still in play. An operand that is a bare column or a function produces
591 /// flags over the chunk and is narrowed with [`refine_flags`], which is what keeps one awkward
592 /// operand from putting the others back on the unthreaded path. An operand that is itself a
593 /// connective recurses, so the two conjuncts of each half of `(a AND b) OR (c AND d)` are
594 /// threaded the same way the halves are.
595 ///
596 /// None of this is available to a projection. `SELECT a > 5 AND b LIKE 'x%'` wants a value per
597 /// row and the rows a selection dropped have no value in it, so [`evaluate`](Self::evaluate) and
598 /// [`evaluate_one`](Self::evaluate_one) evaluate the whole tree over the whole chunk and combine
599 /// flags. The two are separate entry points picked when the pipeline is built rather than one
600 /// path with a flag in it, because conflating them is a wrong answer rather than a slow one.
601 ///
602 /// # Errors
603 ///
604 /// Anything a kernel reports, and an internal error if this was not built from exactly one
605 /// expression.
606 pub fn evaluate_filter(&self, chunk: &Chunk, scratch: &mut Scratch) -> Result<Selection> {
607 let [root] = self.roots[..] else {
608 return Err(Error::internal(format!(
609 "evaluate_filter over a prepared expression of {} roots",
610 self.roots.len()
611 )));
612 };
613 scratch.slots.clear();
614 scratch.slots.resize_with(self.steps.len(), || None);
615 // A predicate that is not a connective at all is the same walk over one operand, which is
616 // where [`thread`](Self::thread) starts: it runs the tree and turns the flags into a
617 // selection, with no narrowing to do because nothing has narrowed anything yet.
618 self.thread(root, 0, chunk, scratch, None)
619 }
620
621 /// The operands of one connective, run in order, each over the rows the ones before it left.
622 ///
623 /// `live` is the rows this connective has to decide about and `None` means every row of the
624 /// chunk, which is not the same as a selection of all of them: it lets the first operand take
625 /// the unthreaded kernel rather than a pass over an identity selection. The answer is the rows
626 /// out of `live` the connective is true for.
627 ///
628 /// The walk is the same for both connectives and only the bookkeeping differs. `AND` carries the
629 /// rows every operand so far has kept, so each answer replaces it. `OR` carries the rows no
630 /// operand so far has accepted, so each answer comes out of it and the rows the connective keeps
631 /// are the ones that went missing along the way.
632 ///
633 /// The operand is not `steps[begin..=operand]` evaluated and then narrowed. Its subtree is run
634 /// over the whole chunk and it is the operand itself that reads only the rows in play, except
635 /// where the operand is another connective, which recurses and threads its own operands from
636 /// here rather than falling back to a flag vector. That is what makes `(a AND b) OR (c AND d)`
637 /// four threaded comparisons rather than two threaded ones and two flag passes.
638 fn branches(
639 &self,
640 index: usize,
641 begin: usize,
642 chunk: &Chunk,
643 scratch: &mut Scratch,
644 live: Option<&Selection>,
645 ) -> Result<Selection> {
646 let Step::Conjunction { op, start, len } = self.steps[index] else {
647 return Err(Error::internal("a connective walk over a step that is not a connective"));
648 };
649 let operands = &self.operands[start..start + len];
650 let rows = chunk.len();
651 // Out of the scratch for the length of the walk, because the walk runs steps and running a
652 // step wants the scratch. It goes back at the end, which is also where it learns. A walk
653 // that fails leaves the slot empty and the next chunk starts the connective over, which is
654 // a history lost on a query that is about to stop running anyway.
655 let mut order = scratch.orders[index]
656 .take()
657 .unwrap_or_else(|| Ordering::new(op, self.weights(operands, begin)));
658 let mut carried: Option<Selection> = live.cloned();
659 for slot in 0..len {
660 if carried.as_ref().is_some_and(Selection::is_empty) {
661 break;
662 }
663 let which = order.at(slot);
664 let operand = operands[which];
665 // The array is in post order and an operand's whole subtree sits between the operand
666 // before it and the operand itself, which is a range the run order cannot move. That is
667 // what lets the operands run in any order at all without a second structure to say
668 // where each one starts.
669 let from = if which == 0 { begin } else { operands[which - 1] + 1 };
670 let given = carried.as_ref().map_or(rows, Selection::len);
671 let answered = self.thread(operand, from, chunk, scratch, carried.as_ref())?;
672 order.observed(which, given, answered.len());
673 carried = Some(match (op, carried) {
674 (Connective::And, _) => answered,
675 (Connective::Or, None) => answered.complement(rows),
676 (Connective::Or, Some(carried)) => carried.without(&answered),
677 });
678 // Keep a shared step alive when a later operand still reads it.
679 for step in from..=operand {
680 if self.last_use[step] <= operand {
681 scratch.slots[step] = None;
682 }
683 }
684 }
685 order.relearn();
686 scratch.orders[index] = Some(order);
687 Ok(match (op, carried) {
688 // A connective with no operands, which the binder does not build and which is answered
689 // here rather than left to index arithmetic: an empty `AND` is every row and an empty
690 // `OR` is none.
691 (Connective::And, None) => live.cloned().unwrap_or_else(|| Selection::identity(rows)),
692 (Connective::And, Some(kept)) => kept,
693 (Connective::Or, None) => Selection::empty(),
694 (Connective::Or, Some(missed)) => match live {
695 None => missed.complement(rows),
696 Some(live) => live.without(&missed),
697 },
698 })
699 }
700
701 /// What each operand of a connective costs to run over a chunk, for the ordering to divide by.
702 ///
703 /// An operand costs what its whole subtree costs, which is the steps from where the operand
704 /// before it ended up to the operand itself.
705 fn weights(&self, operands: &[usize], begin: usize) -> Vec<f64> {
706 let mut costs = Vec::with_capacity(operands.len());
707 let mut from = begin;
708 for &operand in operands {
709 costs.push((from..=operand).map(|step| self.weight(step)).sum());
710 from = operand + 1;
711 }
712 costs
713 }
714
715 /// Roughly what one step costs to run over a chunk, against a comparison of two fixed width
716 /// columns as the unit.
717 ///
718 /// A ranking rather than a prediction. Nothing downstream reads the number itself, only which
719 /// of two of them is larger, and the differences that decide an order are the big ones: a
720 /// column reference costs nothing because it is read in place, a string function costs many
721 /// times what an integer comparison costs, and a comparison over a variable length type costs
722 /// several times what the same comparison over a fixed width one costs. Everything finer than
723 /// that is below the noise of what the window is measuring anyway.
724 fn weight(&self, index: usize) -> f64 {
725 match &self.steps[index] {
726 // Read straight out of the chunk at the point an operand is wanted, so there is no step
727 // to run and nothing to charge for.
728 Step::Column(_) => 0.0,
729 // One vector built per chunk, however many rows the chunk has.
730 Step::Constant(_) => 0.25,
731 // The operands carry the cost of a connective, and they are steps of their own.
732 Step::Conjunction { .. } => 0.0,
733 Step::Cast { input, .. } => 2.0 * touching(&self.types[*input]),
734 Step::Compare { left, .. } => touching(&self.types[*left]),
735 // One hash and one probe a row, whatever the list holds, which is the point of it. It
736 // is dearer than a comparison and much cheaper than the chain of them it replaced.
737 Step::InSet { input, .. } => 2.0 * touching(&self.types[*input]),
738 Step::Function { start, len, .. } => {
739 let widest = self.operands[*start..*start + *len]
740 .iter()
741 .map(|&argument| touching(&self.types[argument]))
742 .fold(1.0, f64::max);
743 4.0 * widest
744 }
745 // A branch per arm, each of which is a prepared expression of its own that this does
746 // not look inside. Charging for the arms alone understates it and says the right thing
747 // about the order, which is that a `CASE` is not what you want in front.
748 Step::Case { arms, .. } => 4.0 * arms.len() as f64,
749 // A run of the body per element, which is several a row, and a list to take apart and
750 // put back together around it.
751 Step::Lambda { .. } => 16.0,
752 // An integer operation a row per node and no check, which is a quarter of what the
753 // function steps it replaced cost each.
754 Step::Fused { fused, .. } => fused.len() as f64,
755 }
756 }
757
758 /// One operand of a connective, over the rows it is still worth asking about.
759 ///
760 /// `begin` is the first step of the operand's subtree, which the caller knows because the steps
761 /// are in post order.
762 fn thread(
763 &self,
764 index: usize,
765 begin: usize,
766 chunk: &Chunk,
767 scratch: &mut Scratch,
768 live: Option<&Selection>,
769 ) -> Result<Selection> {
770 if matches!(self.steps[index], Step::Conjunction { .. }) {
771 return self.branches(index, begin, chunk, scratch, live);
772 }
773 for step in begin..index {
774 self.run_step(step, chunk, scratch)?;
775 }
776 if let Step::Compare { op, left, right, held } = &self.steps[index] {
777 let one = self.operand(*left, chunk, &scratch.slots)?;
778 let other = self.operand(*right, chunk, &scratch.slots)?;
779 let held = held.as_ref();
780 return match live {
781 // The first operand has every row in play, and asking the threaded kernel for that
782 // would be a pass over an identity selection the unthreaded one does not need.
783 None => select_prepared(*op, one, other, held),
784 Some(live) => refine_prepared(*op, one, other, live, held),
785 };
786 }
787 // A later LIKE in a threaded filter often sees only a handful of survivors.
788 // Gather its arguments, not the whole chunk, while preserving the stable
789 // dictionary behind a gathered string column. The ordinary full-vector
790 // path remains cheaper when most rows are still live.
791 if let (Some(live), Step::Function { recipe, written, start, len }) =
792 (live, &self.steps[index])
793 {
794 if matches!(recipe.name(), "~~" | "!~~" | "~~*" | "!~~*")
795 && live.len().saturating_mul(4) <= chunk.len()
796 {
797 let flags = self
798 .with_operands(*start, *len, chunk, &scratch.slots, |args| {
799 let gathered = args
800 .iter()
801 .map(|arg| arg.gather(live.indices()))
802 .collect::<Result<Vec<_>>>()?;
803 let narrowed = gathered.iter().collect::<Vec<_>>();
804 rudb_kernels::call_prepared(
805 recipe,
806 &narrowed,
807 &self.types[index],
808 Some(&|| written.clone()),
809 )
810 })
811 .map_err(|error| error.with_fallback_span(self.spans[index]))?;
812 return Ok(selection(&flags, live.len()).compose(live));
813 }
814 }
815 self.run_step(index, chunk, scratch)?;
816 let flags = self.operand(index, chunk, &scratch.slots)?;
817 match live {
818 None => Ok(selection(flags, chunk.len())),
819 Some(live) => refine_flags(flags, live),
820 }
821 }
822
823 /// Runs every step in order, filling the slots.
824 fn run(&self, chunk: &Chunk, scratch: &mut Scratch) -> Result<()> {
825 scratch.slots.clear();
826 scratch.slots.resize_with(self.steps.len(), || None);
827 for index in 0..self.steps.len() {
828 self.run_step(index, chunk, scratch)?;
829 }
830 Ok(())
831 }
832
833 /// Runs one step and empties the slot of every operand this was the last step to read.
834 fn run_step(&self, index: usize, chunk: &Chunk, scratch: &mut Scratch) -> Result<()> {
835 let produced = self
836 .step(index, chunk, &scratch.slots)
837 .map_err(|error| error.with_fallback_span(self.spans[index]))?;
838 scratch.slots[index] = produced;
839 let slots = &mut scratch.slots;
840 self.for_each_operand(index, |operand| {
841 if self.last_use[operand] == index {
842 slots[operand] = None;
843 }
844 });
845 Ok(())
846 }
847
848 /// Runs one step, given what the steps before it produced.
849 fn step(
850 &self,
851 index: usize,
852 chunk: &Chunk,
853 slots: &[Option<Vector>],
854 ) -> Result<Option<Vector>> {
855 let ty = &self.types[index];
856 let produced = match &self.steps[index] {
857 Step::Column(_) => None,
858 Step::Constant(value) => Some(Vector::constant(ty.clone(), value.clone(), chunk.len())),
859 Step::Cast { input, try_cast } => Some(cast_in_time_zone(
860 self.operand(*input, chunk, slots)?,
861 ty,
862 *try_cast,
863 Some(self.time_zone),
864 )?),
865 Step::Compare { op, left, right, held } => Some(compare_prepared(
866 *op,
867 self.operand(*left, chunk, slots)?,
868 self.operand(*right, chunk, slots)?,
869 held.as_ref(),
870 )?),
871 Step::Conjunction { op, start, len } => {
872 Some(
873 self.with_operands(*start, *len, chunk, slots, |children| {
874 combine(*op, children)
875 })?,
876 )
877 }
878 Step::Function { recipe, written, start, len } => {
879 Some(self.with_operands(*start, *len, chunk, slots, |args| {
880 rudb_kernels::call_prepared(recipe, args, ty, Some(&|| written.clone()))
881 })?)
882 }
883 Step::InSet { input, members } => {
884 Some(in_set(self.operand(*input, chunk, slots)?, members, ty)?)
885 }
886 Step::Case { arms, otherwise, blend } => {
887 Some(self.case(chunk, arms, otherwise.as_ref(), blend.as_ref(), ty)?)
888 }
889 Step::Fused { fused, fallback } => Some(match fused.run(chunk) {
890 Some(answer) => answer,
891 None => fallback.evaluate_one(chunk, &mut fallback.scratch())?.clone(),
892 }),
893 Step::Lambda { inputs, runner, body } => {
894 let mut operands = Vec::with_capacity(inputs.len());
895 for &input in inputs {
896 operands.push(self.operand(input, chunk, slots)?);
897 }
898 let mut scratch = body.scratch();
899 Some(runner.run(&operands, chunk, &mut |inner| {
900 body.evaluate_one(inner, &mut scratch).cloned()
901 })?)
902 }
903 };
904 Ok(produced)
905 }
906
907 /// The vector a step produced, or the chunk's column if the step is a column reference.
908 fn operand<'v>(
909 &self,
910 index: usize,
911 chunk: &'v Chunk,
912 slots: &'v [Option<Vector>],
913 ) -> Result<&'v Vector> {
914 if let Step::Column(position) = self.steps[index] {
915 return chunk.column(position);
916 }
917 slots[index].as_ref().ok_or_else(|| missing(index))
918 }
919
920 /// Hands a kernel the references to an operand list, without allocating for the usual widths.
921 ///
922 /// One, two and three because those are what a bound tree is made of: every scalar function in
923 /// the catalog is unary or binary, a comparison is binary, and a conjunction is two or three
924 /// often enough to be worth a line. A stack array for those means a chain of eight additions
925 /// makes zero allocations for its operand lists over a chunk instead of eight, and eight
926 /// allocations a chunk at the rate a pipeline produces chunks is a real number rather than a
927 /// tidiness argument. Anything wider falls back to [`gather`](Self::gather), which is a `Vec`
928 /// of pointers and still moves no data.
929 fn with_operands<'v, T>(
930 &self,
931 start: usize,
932 len: usize,
933 chunk: &'v Chunk,
934 slots: &'v [Option<Vector>],
935 run: impl FnOnce(&[&'v Vector]) -> Result<T>,
936 ) -> Result<T> {
937 match self.operands[start..start + len] {
938 [a] => run(&[self.operand(a, chunk, slots)?]),
939 [a, b] => run(&[self.operand(a, chunk, slots)?, self.operand(b, chunk, slots)?]),
940 [a, b, c] => run(&[
941 self.operand(a, chunk, slots)?,
942 self.operand(b, chunk, slots)?,
943 self.operand(c, chunk, slots)?,
944 ]),
945 _ => {
946 let gathered = self.gather(start, len, chunk, slots)?;
947 run(&gathered)
948 }
949 }
950 }
951
952 /// References to an operand list, for a kernel that takes a slice of them.
953 ///
954 /// The `Vec` here is the allocation the module documentation names: it holds pointers rather
955 /// than vectors, so it is a dozen bytes an operand and no data moves.
956 fn gather<'v>(
957 &self,
958 start: usize,
959 len: usize,
960 chunk: &'v Chunk,
961 slots: &'v [Option<Vector>],
962 ) -> Result<Vec<&'v Vector>> {
963 let mut gathered = Vec::with_capacity(len);
964 for &operand in &self.operands[start..start + len] {
965 gathered.push(self.operand(operand, chunk, slots)?);
966 }
967 Ok(gathered)
968 }
969
970 /// A searched `CASE` over the rows no earlier arm claimed.
971 ///
972 /// The same shape [`evaluate`](crate::evaluate) has, because the thing that makes it that shape
973 /// is a correctness rule rather than a performance one: `CASE WHEN x <> 0 THEN 1 / x ELSE 0 END`
974 /// divides by zero on the rows the arm excludes if the arm is evaluated for them.
975 ///
976 /// Each arm answers the rows no earlier arm claimed, so the answers come back short and out of
977 /// order and have to be put back in the order the rows arrived in. That is what [`Assembly`] is:
978 /// the arms are laid end to end into one run of data and the interleave is a single typed copy
979 /// over it. It used to be a `Vec<Value>` filled a row at a time and handed to
980 /// `Vector::from_values`, which is a heap allocation and a drop for every string in the answer.
981 /// On the ClickBench query that groups by a `CASE` over `Referer` that was about a quarter of
982 /// the whole query.
983 ///
984 /// What is left of #57 here is the narrowing. An arm still narrows the whole chunk rather than
985 /// the columns it reads, and the selection threading that replaces the narrowing entirely is
986 /// the item this one was carved out of.
987 fn case(
988 &self,
989 chunk: &Chunk,
990 arms: &[PreparedArm],
991 otherwise: Option<&Prepared>,
992 blend: Option<&Blend>,
993 ty: &LogicalType,
994 ) -> Result<Vector> {
995 let claimed = self.claims(chunk, arms)?;
996 if let Some(blend) = blend {
997 if let Some(blended) = blended(chunk, &claimed, blend)? {
998 return Ok(blended);
999 }
1000 }
1001 let mut built = Assembly::new(ty.clone(), chunk.len())?;
1002 let branches = arms.iter().map(|arm| &arm.then).map(Some).chain([otherwise]);
1003 for (branch, rows) in branches.zip(&claimed) {
1004 let (Some(branch), false) = (branch, rows.is_empty()) else { continue };
1005 // The same cut the conditions skip above, skipped here for the same reason: a branch
1006 // that claimed every row claimed them in order, so narrowing to them is a copy of every
1007 // column in the chunk to arrive back at the chunk.
1008 let cut;
1009 let matched = if rows.len() == chunk.len() {
1010 chunk
1011 } else {
1012 cut = narrow(chunk, rows)?;
1013 &cut
1014 };
1015 let mut scratch = branch.scratch();
1016 let results = branch.evaluate_one(matched, &mut scratch)?;
1017 built.place(&placed(rows)?, results)?;
1018 }
1019 built.finish()
1020 }
1021
1022 /// The rows each branch of a `CASE` answers, one list per arm in order and the `ELSE` last.
1023 ///
1024 /// Only the conditions are run here, which is what keeps the rule the doc above states: an arm's
1025 /// condition is evaluated over the rows no earlier arm claimed, so a condition that would raise
1026 /// on a row an earlier arm took is never asked about it. The results are worked out afterwards,
1027 /// once, from these lists, and both ways of working them out want the same thing, which is the
1028 /// rows of one branch in the order they arrived in.
1029 fn claims(&self, chunk: &Chunk, arms: &[PreparedArm]) -> Result<Vec<Vec<usize>>> {
1030 let mut claimed = Vec::with_capacity(arms.len() + 1);
1031 let mut pending: Vec<usize> = (0..chunk.len()).collect();
1032 for arm in arms {
1033 if pending.is_empty() {
1034 claimed.push(Vec::new());
1035 continue;
1036 }
1037 // `pending` starts as every row in order and only ever shrinks, so the same length is
1038 // the same rows in the same order and there is nothing to cut. That is the whole of the
1039 // first arm of a one armed `CASE`, which is the shape of the ClickBench query this was
1040 // measured on, and cutting it was a copy of every column in the chunk for nothing.
1041 let cut;
1042 let narrowed = if pending.len() == chunk.len() {
1043 chunk
1044 } else {
1045 cut = narrow(chunk, &pending)?;
1046 &cut
1047 };
1048 let mut scratch = arm.when.scratch();
1049 let flags = arm.when.evaluate_one(narrowed, &mut scratch)?;
1050 let mut taken = Vec::new();
1051 let mut still = Vec::new();
1052 // row at a time: splitting the rows an arm claims from the ones it leaves is a test per
1053 // row, and what replaces it is the selection threading the rest of #57 asks for rather
1054 // than anything that can be done here.
1055 for (at, &row) in pending.iter().enumerate() {
1056 if is_true(&flags.value_at(at)) {
1057 taken.push(row);
1058 } else {
1059 still.push(row);
1060 }
1061 }
1062 claimed.push(taken);
1063 pending = still;
1064 }
1065 claimed.push(pending);
1066 Ok(claimed)
1067 }
1068
1069 /// Flattens one expression, appending its steps and returning the index of its last one.
1070 fn push(&mut self, plan: &Plan, expr: ExprRef, schema: &Schema) -> Result<usize> {
1071 if self.share {
1072 if let Some(&step) = self.shared.get(&expr) {
1073 return Ok(step);
1074 }
1075 }
1076 let ty = plan.expr_type(expr).clone();
1077 if self.fuse {
1078 if let Some(fused) = Fused::compile(plan, expr, schema) {
1079 let fallback = Self::built(plan, &[expr], schema, false, false)?;
1080 let step = Step::Fused { fused: Box::new(fused), fallback: Box::new(fallback) };
1081 return Ok(self.place(plan, expr, step, ty));
1082 }
1083 }
1084 let step = match *plan.expr(expr) {
1085 Expr::Column(binding) => {
1086 let position = schema.position_of(binding).ok_or_else(|| {
1087 Error::internal(format!(
1088 "column #{}.{} is not in the schema this operator was given",
1089 binding.table, binding.column
1090 ))
1091 })?;
1092 Step::Column(position)
1093 }
1094 Expr::Constant(reference) => Step::Constant(plan.value(reference).clone()),
1095 Expr::Cast { input, try_cast } => {
1096 Step::Cast { input: self.push(plan, input, schema)?, try_cast }
1097 }
1098 Expr::Compare { op, left, right } => {
1099 let left = self.push(plan, left, schema)?;
1100 let right = self.push(plan, right, schema)?;
1101 Step::Compare { op: comparison(op), left, right, held: self.held(left, right) }
1102 }
1103 Expr::Conjunction { op, children } => {
1104 let list = plan.expr_list(children).to_vec();
1105 match self.membership(plan, connective(op), &list, schema)? {
1106 Some(step) => step,
1107 None => {
1108 let (start, len) = self.push_list(plan, &list, schema)?;
1109 Step::Conjunction { op: connective(op), start, len }
1110 }
1111 }
1112 }
1113 Expr::Function { name, args } if lambda_call(plan, args).is_some() => {
1114 let Some((lambda, inputs)) = lambda_call(plan, args) else {
1115 return Err(Error::internal("a lambda call without a lambda"));
1116 };
1117 let Expr::Lambda { body, .. } = *plan.expr(lambda) else {
1118 return Err(Error::internal("a lambda call without a lambda"));
1119 };
1120 let runner = Lambda::new(plan, plan.string(name), lambda, &inputs, schema)?;
1121 let body = Self::one(plan, body, runner.schema())?;
1122 let mut steps = Vec::with_capacity(inputs.len());
1123 for &input in &inputs {
1124 steps.push(self.push(plan, input, schema)?);
1125 }
1126 Step::Lambda { inputs: steps, runner: Box::new(runner), body: Box::new(body) }
1127 }
1128 Expr::LambdaParam(binding) => {
1129 let position = schema.position_of(binding).ok_or_else(|| {
1130 Error::internal(format!(
1131 "lambda parameter @{}.{} is not in the schema its body was given",
1132 binding.table, binding.column
1133 ))
1134 })?;
1135 Step::Column(position)
1136 }
1137 Expr::Lambda { .. } => {
1138 return Err(Error::internal(
1139 "a lambda was evaluated outside the function that takes it",
1140 ));
1141 }
1142 Expr::Function { name, args } => {
1143 let (start, len) = self.push_list(plan, plan.expr_list(args), schema)?;
1144 Step::Function {
1145 recipe: Recipe::new(plan.string(name), &self.literals(start, len)),
1146 written: written(plan, expr, schema),
1147 start,
1148 len,
1149 }
1150 }
1151 Expr::Aggregate { name, .. } => {
1152 return Err(Error::internal(format!(
1153 "the {} aggregate was evaluated as an ordinary expression",
1154 plan.string(name)
1155 )));
1156 }
1157 Expr::Window { name, .. } => {
1158 return Err(Error::internal(format!(
1159 "the {} window function was evaluated as an ordinary expression",
1160 plan.string(name)
1161 )));
1162 }
1163 Expr::Case { arms, otherwise } => {
1164 let mut prepared = Vec::new();
1165 for &arm in plan.arm_list(arms) {
1166 prepared.push(PreparedArm {
1167 when: Self::one(plan, arm.when, schema)?,
1168 then: Self::one(plan, arm.then, schema)?,
1169 });
1170 }
1171 let otherwise = match otherwise {
1172 Some(otherwise) => Some(Self::one(plan, otherwise, schema)?),
1173 None => None,
1174 };
1175 let blend = blending(&ty, &prepared, otherwise.as_ref());
1176 Step::Case { arms: prepared, otherwise, blend }
1177 }
1178 };
1179 Ok(self.place(plan, expr, step, ty))
1180 }
1181
1182 /// Appends a built step and answers its index.
1183 fn place(&mut self, plan: &Plan, expr: ExprRef, step: Step, ty: LogicalType) -> usize {
1184 self.steps.push(step);
1185 self.types.push(ty);
1186 self.spans.push(plan.expr_span(expr));
1187 let step = self.steps.len() - 1;
1188 if self.share {
1189 self.shared.insert(expr, step);
1190 }
1191 step
1192 }
1193
1194 /// Flattens a list of expressions and records where its operand run starts and how long it is.
1195 ///
1196 /// The operand run is written after every child has been flattened rather than as they go,
1197 /// because a child that is itself a list would otherwise interleave its run with this one.
1198 fn push_list(
1199 &mut self,
1200 plan: &Plan,
1201 exprs: &[ExprRef],
1202 schema: &Schema,
1203 ) -> Result<(usize, usize)> {
1204 let mut indices = Vec::with_capacity(exprs.len());
1205 for &expr in exprs {
1206 indices.push(self.push(plan, expr, schema)?);
1207 }
1208 let start = self.operands.len();
1209 let len = indices.len();
1210 self.operands.extend(indices);
1211 Ok((start, len))
1212 }
1213
1214 /// This connective folded back into the `IN` the user wrote, or `None` when it is not one.
1215 ///
1216 /// What the binder writes for `x IN (1, 2, 3)` is `x = 1 OR x = 2 OR x = 3`, and for
1217 /// `x NOT IN (1, 2, 3)` it is `x <> 1 AND x <> 2 AND x <> 3`. So the shape looked for is every
1218 /// child a comparison of the one direction, every left the same expression, and every right a
1219 /// literal. Anything else is left alone, which covers the `OR` that was written as an `OR` and
1220 /// the one where an `IN` has been flattened together with another branch. The second is a fold
1221 /// this could make and does not, and it is worth having later out of a query that wants it
1222 /// rather than now out of a guess.
1223 ///
1224 /// This runs before the children are pushed, and that is the whole reason it is here rather than
1225 /// as a pass over the finished array. A step that nothing reads is still a step the walk runs,
1226 /// because the walk over a subtree is a range and not a graph, so folding after the fact would
1227 /// leave every equality in place and running.
1228 fn membership(
1229 &mut self,
1230 plan: &Plan,
1231 op: Connective,
1232 children: &[ExprRef],
1233 schema: &Schema,
1234 ) -> Result<Option<Step>> {
1235 let wanted = match op {
1236 Connective::Or => CompareOp::Equal,
1237 Connective::And => CompareOp::NotEqual,
1238 };
1239 let mut subject: Option<ExprRef> = None;
1240 let mut values = Vec::with_capacity(children.len());
1241 for &child in children {
1242 let Expr::Compare { op: found, left, right } = *plan.expr(child) else {
1243 return Ok(None);
1244 };
1245 if found != wanted || !same(plan, *subject.get_or_insert(left), left) {
1246 return Ok(None);
1247 }
1248 let Expr::Constant(reference) = *plan.expr(right) else {
1249 return Ok(None);
1250 };
1251 values.push(plan.value(reference).clone());
1252 }
1253 let (Some(subject), Some(members)) = (subject, Members::of(&values, op == Connective::And))
1254 else {
1255 return Ok(None);
1256 };
1257 Ok(Some(Step::InSet { input: self.push(plan, subject, schema)?, members }))
1258 }
1259
1260 /// The literal side of a comparison, in the one row column the comparison reads it through.
1261 ///
1262 /// The right side first, because that is the side the binder puts a literal on and the side the
1263 /// loops are written for. Two literals is a comparison the optimizer folded, and if it did not
1264 /// then the kernel answers it once for the whole vector and never reads either column, so
1265 /// neither side is built here.
1266 fn held(&self, left: usize, right: usize) -> Option<Held> {
1267 let (at, other) = match (&self.steps[left], &self.steps[right]) {
1268 (Step::Constant(_), Step::Constant(_)) => return None,
1269 (_, Step::Constant(value)) => (right, value),
1270 (Step::Constant(value), _) => (left, value),
1271 _ => return None,
1272 };
1273 Held::of(&self.types[at], other)
1274 }
1275
1276 /// The literal behind each argument in a run of the operand list, and `None` for an argument
1277 /// that is anything else.
1278 ///
1279 /// This is what a [`Recipe`] hoists from. An argument that is a literal in the plan arrives as a
1280 /// constant vector holding exactly this value on every chunk, so what a kernel reads here is
1281 /// what it would have read per chunk. An argument that is a cast of a literal reads as `None`,
1282 /// which is a call the kernel decides per chunk as it always did, and the optimizer folds most
1283 /// of those before the plan gets here anyway.
1284 fn literals(&self, start: usize, len: usize) -> Vec<Option<Value>> {
1285 self.operands[start..start + len]
1286 .iter()
1287 .map(|&operand| match &self.steps[operand] {
1288 Step::Constant(value) => Some(value.clone()),
1289 _ => None,
1290 })
1291 .collect()
1292 }
1293}
1294
1295/// Whether two expressions of one plan are the same expression, written once or written twice.
1296///
1297/// The binder binds the subject of an `IN` once and points every comparison it writes at that one
1298/// reference, so the answer is almost always the first line. A plan that has been through a rewrite,
1299/// and a plan read back from its own text, hold two copies of the same tree instead, and for the
1300/// fold in [`Prepared::membership`] those are the same expression.
1301///
1302/// The four shapes handled are what an `IN` is written over: a column, a literal, a cast of either,
1303/// and a call, which is TPC-H query 22 asking whether the first two digits of a phone number are in
1304/// a list. Anything else answers no, which costs a fold that could have happened rather than a wrong
1305/// one. The walk is bounded by the size of the subject and a subject is small.
1306fn same(plan: &Plan, left: ExprRef, right: ExprRef) -> bool {
1307 if left == right {
1308 return true;
1309 }
1310 if plan.expr_type(left) != plan.expr_type(right) {
1311 return false;
1312 }
1313 match (plan.expr(left), plan.expr(right)) {
1314 (Expr::Column(one), Expr::Column(other)) => one == other,
1315 (Expr::Constant(one), Expr::Constant(other)) => plan.value(*one) == plan.value(*other),
1316 (
1317 Expr::Cast { input: one, try_cast: first },
1318 Expr::Cast { input: other, try_cast: second },
1319 ) => first == second && same(plan, *one, *other),
1320 (
1321 Expr::Function { name: one, args: first },
1322 Expr::Function { name: other, args: second },
1323 ) => {
1324 let (first, second) = (plan.expr_list(*first), plan.expr_list(*second));
1325 plan.string(*one) == plan.string(*other)
1326 && first.len() == second.len()
1327 && first.iter().zip(second).all(|(&one, &other)| same(plan, one, other))
1328 }
1329 _ => false,
1330 }
1331}
1332
1333/// What touching a value of this type costs, against a fixed width one as the unit.
1334///
1335/// A variable length value is a pointer to follow and a length that is not the same twice, and a
1336/// nested one is that per element. Four is not measured, and what it has to be is large enough that
1337/// the ordering puts a fixed width comparison in front of a string one and small enough that it does
1338/// not put one in front of a string comparison that rejects every row.
1339fn touching(ty: &LogicalType) -> f64 {
1340 match ty.physical() {
1341 PhysicalType::Varlen => 4.0,
1342 PhysicalType::List | PhysicalType::Array | PhysicalType::Struct => 8.0,
1343 _ => 1.0,
1344 }
1345}
1346
1347/// The error for a slot that should have held something and did not.
1348///
1349/// This cannot happen while the array is in post order, since every operand's index is smaller than
1350/// the index of the step using it and every step runs in order. It is an error rather than a panic
1351/// because the property it depends on is a property of [`Prepared::push`], and the day somebody
1352/// writes a pass that reorders the array is the day it stops holding.
1353fn missing(index: usize) -> Error {
1354 Error::internal(format!("step {index} was used as an operand before it produced anything"))
1355}
1356
1357/// Chunk rows as the positions an [`Assembly`] places a piece at.
1358///
1359/// A chunk is at most [`VECTOR_SIZE`](rudb_vector::VECTOR_SIZE) rows, so the conversion cannot fail
1360/// in practice. It is checked rather than cast because a silent truncation here would put a value in
1361/// the wrong row, and a wrong row is the one kind of bug nothing downstream can notice.
1362fn placed(rows: &[usize]) -> Result<Vec<u32>> {
1363 rows.iter()
1364 .map(|&row| {
1365 u32::try_from(row).map_err(|_| Error::internal("a chunk of more than u32 rows"))
1366 })
1367 .collect()
1368}
1369
1370/// A `CASE` answered as codes over the dictionary its branches share, or `None` for a chunk that
1371/// cannot be.
1372///
1373/// Declined per chunk rather than once, because whether a column arrives coded is a fact about the
1374/// chunk and not about the expression. The same query reads codes out of a native file and plain
1375/// strings out of rows held in memory, and one file can hand a column over as a dictionary in one
1376/// part and as plain data in the next. Everything that declines does so before a code is written, so
1377/// the caller starts the general path from nothing rather than from a half filled answer.
1378fn blended(chunk: &Chunk, claimed: &[Vec<usize>], blend: &Blend) -> Result<Option<Vector>> {
1379 let Some((dictionary, literals)) = agreed(chunk, blend)? else { return Ok(None) };
1380 let mut codes = vec![0; chunk.len()];
1381 for (branch, rows) in blend.branches.iter().zip(claimed) {
1382 match *branch {
1383 Branch::Column(position) => {
1384 let Some((from, _)) = chunk.column(position)?.stable_dictionary_parts() else {
1385 return Ok(None);
1386 };
1387 for &row in rows {
1388 codes[row] = from[row];
1389 }
1390 }
1391 Branch::Literal(at) => {
1392 for &row in rows {
1393 codes[row] = literals[at];
1394 }
1395 }
1396 }
1397 }
1398 Vector::stable_dictionary(codes, dictionary).map(Some)
1399}
1400
1401/// The one dictionary every branch of a blend names values in, and the code each literal sits at.
1402///
1403/// Three things say no. A column that did not arrive as a stable dictionary has no codes to copy. A
1404/// second column over a different dictionary would have codes that mean something else, and a code
1405/// is a position in one dictionary and nothing anywhere else. And a literal the dictionary does not
1406/// hold has no code at all, which for `ELSE ''` over a column where no row is empty is the honest
1407/// answer rather than a missing one.
1408///
1409/// The null check is the fourth. A dictionary keeps its nulls in the values it points at rather than
1410/// beside its codes, so a column carrying its own validity is one whose codes do not say everything
1411/// the column says, and copying them would turn its nulls into whatever their codes happen to name.
1412fn agreed(chunk: &Chunk, blend: &Blend) -> Result<Option<(Arc<Vector>, Vec<u32>)>> {
1413 let mut held: Option<(&Vector, &Arc<Vector>)> = None;
1414 for branch in &blend.branches {
1415 let Branch::Column(position) = *branch else { continue };
1416 let column = chunk.column(position)?;
1417 let Some((_, dictionary)) = column.stable_dictionary_parts() else { return Ok(None) };
1418 if column.validity().has_nulls(chunk.len()) {
1419 return Ok(None);
1420 }
1421 match held {
1422 Some((_, first)) if !Arc::ptr_eq(first, dictionary) => return Ok(None),
1423 Some(_) => {}
1424 None => held = Some((column, dictionary)),
1425 }
1426 }
1427 let Some((column, dictionary)) = held else { return Ok(None) };
1428 let mut codes = Vec::with_capacity(blend.literals.len());
1429 for (text, lookup) in &blend.literals {
1430 match lookup.find(column, text.as_bytes()) {
1431 Some(Ok(Found::At(code))) => codes.push(code),
1432 Some(Err(error)) => return Err(error),
1433 Some(Ok(Found::Absent)) | None => return Ok(None),
1434 }
1435 }
1436 Ok(Some((Arc::clone(dictionary), codes)))
1437}
1438
1439/// The blend a `CASE` can be answered by, or `None` for one that has to read its branches' values.
1440fn blending(ty: &LogicalType, arms: &[PreparedArm], otherwise: Option<&Prepared>) -> Option<Blend> {
1441 if !matches!(ty, LogicalType::Varchar) {
1442 return None;
1443 }
1444 let otherwise = otherwise?;
1445 let mut branches = Vec::with_capacity(arms.len() + 1);
1446 let mut literals = Vec::new();
1447 for branch in arms.iter().map(|arm| &arm.then).chain([otherwise]) {
1448 branches.push(named(branch, &mut literals)?);
1449 }
1450 // All of them literals means there is no dictionary to name any of them in, and a `CASE` whose
1451 // every branch is a constant is not a thing anybody writes.
1452 let any = branches.iter().any(|branch| matches!(branch, Branch::Column(_)));
1453 any.then_some(Blend { branches, literals })
1454}
1455
1456/// The branch a prepared expression stands for, when it names a value rather than computing one.
1457fn named(prepared: &Prepared, literals: &mut Vec<(String, Lookup)>) -> Option<Branch> {
1458 match prepared.steps.as_slice() {
1459 [Step::Column(position)] => Some(Branch::Column(*position)),
1460 [Step::Constant(Value::Varchar(text))] => {
1461 literals.push((text.clone(), Lookup::default()));
1462 Some(Branch::Literal(literals.len() - 1))
1463 }
1464 _ => None,
1465 }
1466}
1467
1468/// The chunk cut down to the given rows.
1469///
1470/// The reason `CASE` is written with this rather than by evaluating every arm over the whole chunk
1471/// and picking afterwards. `CASE WHEN x <> 0 THEN 1 // x ELSE 0 END` divides by zero on the rows the
1472/// arm does not apply to if the arm is evaluated for them, and a `CASE` that raises on a row it was
1473/// written to exclude is the classic wrong answer this shape prevents.
1474pub(crate) fn narrow(chunk: &Chunk, rows: &[usize]) -> Result<Chunk> {
1475 let mut selection = Selection::with_capacity(rows.len());
1476 for &row in rows {
1477 selection.push(row);
1478 }
1479 chunk.clone().select(&selection)
1480}
1481
1482/// The kernels' comparison for the plan's.
1483///
1484/// A translation rather than one shared enum, because the kernels are rank 3 and the plan is rank
1485/// 9. This function is the whole of what that separation costs.
1486pub(crate) fn comparison(op: CompareOp) -> Comparison {
1487 match op {
1488 CompareOp::Equal => Comparison::Equal,
1489 CompareOp::NotEqual => Comparison::NotEqual,
1490 CompareOp::Less => Comparison::Less,
1491 CompareOp::LessOrEqual => Comparison::LessOrEqual,
1492 CompareOp::Greater => Comparison::Greater,
1493 CompareOp::GreaterOrEqual => Comparison::GreaterOrEqual,
1494 CompareOp::DistinctFrom => Comparison::DistinctFrom,
1495 CompareOp::NotDistinctFrom => Comparison::NotDistinctFrom,
1496 }
1497}
1498
1499/// The kernels' connective for the plan's.
1500pub(crate) fn connective(op: ConjunctionOp) -> Connective {
1501 match op {
1502 ConjunctionOp::And => Connective::And,
1503 ConjunctionOp::Or => Connective::Or,
1504 }
1505}
1506
1507#[cfg(test)]
1508mod tests {
1509 use rudb_common::{Field, LogicalType, Value};
1510 use rudb_kernels::is_true;
1511 use rudb_plan::{ExprRef, Node, Plan};
1512 use rudb_vector::{Chunk, Selection, Vector};
1513
1514 use super::{Prepared, narrow};
1515 use crate::expr::evaluate;
1516 use crate::schema::Schema;
1517
1518 /// Two columns with a null in each, because every disagreement between these two evaluators
1519 /// that is worth finding is a disagreement about which rows are null.
1520 fn input() -> (Schema, Chunk) {
1521 let schema = Schema::numbered(
1522 vec![Field::new("x", LogicalType::Integer), Field::new("s", LogicalType::Varchar)],
1523 0,
1524 );
1525 let x = Vector::from_values(
1526 LogicalType::Integer,
1527 &[Value::Integer(3), Value::Integer(1), Value::Null, Value::Integer(2)],
1528 )
1529 .expect("four integers");
1530 let s = Vector::from_values(
1531 LogicalType::Varchar,
1532 &[
1533 Value::Varchar("a".to_string()),
1534 Value::Null,
1535 Value::Varchar("c".to_string()),
1536 Value::Varchar("a".to_string()),
1537 ],
1538 )
1539 .expect("four strings");
1540 (schema, Chunk::new(vec![x, s]).expect("two columns of four rows"))
1541 }
1542
1543 /// The expressions of a projection written in the plan's textual form, over the two columns
1544 /// [`input`] produces.
1545 ///
1546 /// Going through the text rather than the arena builders for the reason the other test module
1547 /// gives: a test that says what it evaluates in the notation a plan dump uses is a test whose
1548 /// failure can be pasted into a plan and vice versa.
1549 fn projection(exprs: &str) -> (Plan, Vec<ExprRef>) {
1550 let text =
1551 format!("Project #1 [{exprs}]\n Get memory.main.t AS t #0 [x::INTEGER, s::VARCHAR]");
1552 let plan = Plan::parse(&text).expect("a well formed plan");
1553 let Node::Project { exprs, .. } = *plan.node(plan.root()) else {
1554 panic!("the root of that text is a projection");
1555 };
1556 let list = plan.expr_list(exprs).to_vec();
1557 (plan, list)
1558 }
1559
1560 /// Every expression shape, evaluated both ways over the same chunk.
1561 ///
1562 /// This is the agreement the module documentation claims and it is the only thing that makes
1563 /// the prepared form safe to put in front of the tree walk. The generated well typed trees the
1564 /// test gate of #57 asks for are a wider version of this and are worth building once the
1565 /// selection threaded shapes exist to disagree about.
1566 fn agrees(exprs: &str) {
1567 let (schema, chunk) = input();
1568 let (plan, list) = projection(exprs);
1569 let prepared = Prepared::new(&plan, &list, &schema).expect("the expressions resolve");
1570 let mut scratch = prepared.scratch();
1571 let mut fast = Vec::new();
1572 prepared.evaluate(&chunk, &mut scratch, &mut fast).expect("the prepared form runs");
1573 for (at, &expr) in list.iter().enumerate() {
1574 let slow = evaluate(&plan, expr, &schema, &chunk).expect("the tree walk runs");
1575 for row in 0..chunk.len() {
1576 assert_eq!(
1577 fast[at].value_at(row),
1578 slow.value_at(row),
1579 "expression {at} of `{exprs}` at row {row}"
1580 );
1581 }
1582 }
1583 }
1584
1585 /// Three decimal columns of TPC-H's shape, in the form `form` puts them in.
1586 fn decimals(prices: &[i128], form: fn(Vector) -> Vector) -> (Schema, Chunk) {
1587 let ty = LogicalType::Decimal { width: 15, scale: 2 };
1588 let schema = Schema::numbered(
1589 vec![
1590 Field::new("p", ty.clone()),
1591 Field::new("d", ty.clone()),
1592 Field::new("t", ty.clone()),
1593 ],
1594 0,
1595 );
1596 let column =
1597 |values: Vec<Value>| form(Vector::from_values(ty.clone(), &values).expect("decimals"));
1598 let decimal = |unscaled| Value::Decimal { unscaled, width: 15, scale: 2 };
1599 let p = column(prices.iter().map(|&v| decimal(v)).collect());
1600 let d = column((0..prices.len() as i128).map(|v| decimal(v % 11)).collect());
1601 let t = column((0..prices.len() as i128).map(|v| decimal(v % 9)).collect());
1602 (schema, Chunk::new(vec![p, d, t]).expect("three columns"))
1603 }
1604
1605 /// q01's charge, as the binder writes it.
1606 const CHARGE: &str = "\"*\"(\"*\"(CAST(#0.0::DECIMAL(15,2))::DECIMAL(18,2), \
1607 CAST(\"-\"(1.00::DECIMAL(16,2), CAST(#0.1::DECIMAL(15,2))::DECIMAL(16,2))::DECIMAL(16,2))\
1608 ::DECIMAL(18,2))::DECIMAL(18,4), CAST(\"+\"(1.00::DECIMAL(16,2), \
1609 CAST(#0.2::DECIMAL(15,2))::DECIMAL(16,2))::DECIMAL(16,2))::DECIMAL(18,2))::DECIMAL(18,6) AS a";
1610
1611 /// The fused answer, the unfused one and the tree walk's, over one chunk.
1612 fn three_ways(chunk: &Chunk, schema: &Schema) -> [rudb_common::Result<Vec<Value>>; 3] {
1613 let text = format!(
1614 "Project #1 [{CHARGE}]\n Get memory.main.t AS t #0 \
1615 [p::DECIMAL(15,2), d::DECIMAL(15,2), t::DECIMAL(15,2)]"
1616 );
1617 let plan = Plan::parse(&text).expect("a well formed plan");
1618 let Node::Project { exprs, .. } = *plan.node(plan.root()) else {
1619 panic!("the root of that text is a projection");
1620 };
1621 let expr = plan.expr_list(exprs)[0];
1622 let values = |vector: &Vector| (0..chunk.len()).map(|row| vector.value_at(row)).collect();
1623 let fused = Prepared::one(&plan, expr, schema).expect("resolves");
1624 assert_eq!(fused.fused(), 1, "the whole tree is one step");
1625 let unfused = Prepared::built(&plan, &[expr], schema, false, false).expect("resolves");
1626 assert_eq!(unfused.fused(), 0);
1627 let run = |prepared: &Prepared| {
1628 prepared.evaluate_one(chunk, &mut prepared.scratch()).map(&values)
1629 };
1630 [run(&fused), run(&unfused), evaluate(&plan, expr, schema, chunk).map(|v| values(&v))]
1631 }
1632
1633 fn all_agree(chunk: &Chunk, schema: &Schema) {
1634 let [fused, unfused, walked] = three_ways(chunk, schema);
1635 let fused = fused.expect("fits");
1636 assert_eq!(fused, unfused.expect("fits"));
1637 assert_eq!(fused, walked.expect("fits"));
1638 }
1639
1640 #[test]
1641 fn decimal_arithmetic_run_as_one_loop_agrees_in_every_form() {
1642 let prices: Vec<i128> = (0..2500).map(|v| 90_000 + v * 37).collect();
1643 let packed = |vector: Vector| vector.bit_packed().expect("packs");
1644 let coded = |vector: Vector| {
1645 let rows = vector.len();
1646 let codes = (0..rows as u32).rev().collect();
1647 Vector::dictionary(codes, vector.bit_packed().expect("packs")).expect("in range")
1648 };
1649 // Codes too far apart for a block to unpack the run they cover.
1650 let scattered = |vector: Vector| {
1651 let rows = vector.len() as u32;
1652 let codes = (0..rows).map(|row| row * 997 % rows).collect();
1653 Vector::dictionary(codes, vector.bit_packed().expect("packs")).expect("in range")
1654 };
1655 for form in [std::convert::identity, packed, coded, scattered] {
1656 let (schema, chunk) = decimals(&prices, form);
1657 all_agree(&chunk, &schema);
1658 }
1659 }
1660
1661 #[test]
1662 fn a_chunk_the_ranges_cannot_prove_raises_what_the_steps_raise() {
1663 // The large price in the second block, so a flat column gets as far as running the first.
1664 let mut prices = vec![5; 300];
1665 prices.push(999_999_999_999_999);
1666 let packed = |vector: Vector| vector.bit_packed().expect("packs");
1667 for form in [std::convert::identity, packed] {
1668 let (schema, chunk) = decimals(&prices, form);
1669 let [fused, unfused, _] = three_ways(&chunk, &schema);
1670 let (fused, unfused) = (fused.expect_err("overflows"), unfused.expect_err("overflows"));
1671 assert_eq!(fused.message(), unfused.message());
1672 }
1673 }
1674
1675 #[test]
1676 fn a_chunk_with_a_null_goes_through_the_steps() {
1677 let ty = LogicalType::Decimal { width: 15, scale: 2 };
1678 let (schema, mut chunk) = decimals(&[100, 200, 300], std::convert::identity);
1679 let with_null = Vector::from_values(
1680 ty,
1681 &[Value::Decimal { unscaled: 5, width: 15, scale: 2 }, Value::Null, Value::Null],
1682 )
1683 .expect("decimals");
1684 chunk = Chunk::new(vec![
1685 chunk.column(0).expect("p").clone(),
1686 with_null,
1687 chunk.column(2).expect("t").clone(),
1688 ])
1689 .expect("three columns");
1690 all_agree(&chunk, &schema);
1691 }
1692
1693 #[test]
1694 fn a_column_reference_agrees() {
1695 agrees("#0.0::INTEGER AS a, #0.1::VARCHAR AS b");
1696 }
1697
1698 #[test]
1699 fn a_constant_agrees() {
1700 agrees("7::INTEGER AS a, NULL::INTEGER AS b");
1701 }
1702
1703 #[test]
1704 fn a_cast_agrees() {
1705 agrees("CAST(#0.0::INTEGER)::BIGINT AS a, CAST(#0.0::INTEGER)::VARCHAR AS b");
1706 }
1707
1708 #[test]
1709 fn a_comparison_agrees() {
1710 agrees("(#0.0::INTEGER > 1::INTEGER)::BOOLEAN AS a");
1711 }
1712
1713 #[test]
1714 fn a_conjunction_agrees() {
1715 agrees(
1716 "((#0.0::INTEGER > 1::INTEGER)::BOOLEAN AND (#0.0::INTEGER < 3::INTEGER)::BOOLEAN)\
1717 ::BOOLEAN AS a",
1718 );
1719 }
1720
1721 #[test]
1722 fn a_function_agrees() {
1723 agrees("\"+\"(#0.0::INTEGER, 1::INTEGER)::INTEGER AS a");
1724 }
1725
1726 /// The two evaluators quote the same expression when a divisor is zero. Per #262.
1727 ///
1728 /// This is the one message in the engine that depends on how an expression is written rather
1729 /// than on what it computes, and the two evaluators render it at different times: the prepared
1730 /// form when the pipeline is built, the tree walk on the row that fails. Same renderer, so the
1731 /// same sentence, and this is what says so.
1732 #[test]
1733 fn both_evaluators_quote_the_same_expression_when_a_divisor_is_zero() {
1734 let (schema, chunk) = input();
1735 let (plan, list) = projection("\"//\"(#0.0::INTEGER, 0::INTEGER)::INTEGER AS a");
1736 let prepared = Prepared::new(&plan, &list, &schema).expect("the expression resolves");
1737 let mut scratch = prepared.scratch();
1738 let mut out = Vec::new();
1739 let fast = prepared.evaluate(&chunk, &mut scratch, &mut out).expect_err("divides by zero");
1740 let slow = evaluate(&plan, list[0], &schema, &chunk).expect_err("divides by zero");
1741 assert_eq!(fast.message(), slow.message());
1742 assert!(fast.message().starts_with("Division by zero in expression (x // 0)."), "{fast}");
1743 }
1744
1745 #[test]
1746 fn a_case_agrees() {
1747 agrees(
1748 "CASE WHEN (#0.0::INTEGER > 1::INTEGER)::BOOLEAN THEN 10::INTEGER \
1749 ELSE 20::INTEGER END::INTEGER AS a",
1750 );
1751 }
1752
1753 /// A second arm, which is the first one that sees a cut chunk rather than the whole one.
1754 ///
1755 /// The first arm of any `CASE` runs over every row, so it takes the path that does not cut at
1756 /// all, and a `CASE` of one arm never exercises the other one. Two arms and an `ELSE` puts a
1757 /// different set of rows in front of each of the three.
1758 ///
1759 /// That this is the only test here reaching the cut was checked rather than assumed, by gating a
1760 /// panic on it and rerunning the seven. This one failed and the other six did not.
1761 #[test]
1762 fn a_case_of_two_arms_agrees() {
1763 agrees(
1764 "CASE WHEN (#0.0::INTEGER > 2::INTEGER)::BOOLEAN THEN 10::INTEGER \
1765 WHEN (#0.0::INTEGER > 1::INTEGER)::BOOLEAN THEN 20::INTEGER \
1766 ELSE 30::INTEGER END::INTEGER AS a",
1767 );
1768 }
1769
1770 /// No `ELSE`, so the rows no arm claims are null rather than anything.
1771 ///
1772 /// The case a run of data with a hole in it gets wrong: a null still occupies a position, and an
1773 /// assembly that skipped it would put every value after it one row early.
1774 #[test]
1775 fn a_case_with_no_else_agrees() {
1776 agrees(
1777 "CASE WHEN (#0.0::INTEGER > 2::INTEGER)::BOOLEAN THEN 10::INTEGER \
1778 END::INTEGER AS a",
1779 );
1780 }
1781
1782 /// An arm no row takes, so it contributes nothing to the answer and must not shift it.
1783 #[test]
1784 fn a_case_whose_arm_claims_nothing_agrees() {
1785 agrees(
1786 "CASE WHEN (#0.0::INTEGER > 99::INTEGER)::BOOLEAN THEN 10::INTEGER \
1787 ELSE 20::INTEGER END::INTEGER AS a",
1788 );
1789 }
1790
1791 /// Strings, which is the case that used to allocate one of them per row and drop it afterwards.
1792 ///
1793 /// The arm reads a column and the `ELSE` is a constant, which is the shape of the ClickBench
1794 /// query this path was rewritten for: the arm arrives as views over an arena and the `ELSE` as
1795 /// one value repeated, and the two have to be laid end to end into a single arena.
1796 #[test]
1797 fn a_case_over_strings_agrees() {
1798 agrees(
1799 "CASE WHEN (#0.0::INTEGER > 1::INTEGER)::BOOLEAN THEN #0.1::VARCHAR \
1800 ELSE ''::VARCHAR END::VARCHAR AS a",
1801 );
1802 }
1803
1804 /// A null inside an arm, which is a different thing from a row no arm claimed.
1805 ///
1806 /// Both come out null and they reach the validity mask by different routes, so a mask built for
1807 /// one of them and not the other reads correct on whichever test only has the other in it.
1808 #[test]
1809 fn a_case_whose_arm_answers_null_agrees() {
1810 agrees(
1811 "CASE WHEN (#0.0::INTEGER > 1::INTEGER)::BOOLEAN THEN #0.1::VARCHAR \
1812 ELSE NULL::VARCHAR END::VARCHAR AS a",
1813 );
1814 }
1815
1816 /// A `WHEN` over a column that is null on some rows, which is neither true nor false there.
1817 ///
1818 /// A three valued `WHEN` is what decides whether a row goes to the arm or falls through, and
1819 /// treating unknown as true would claim a row the `ELSE` should have had.
1820 #[test]
1821 fn a_case_whose_test_is_null_on_some_rows_agrees() {
1822 agrees(
1823 "CASE WHEN (#0.1::VARCHAR = 'a'::VARCHAR)::BOOLEAN THEN 10::INTEGER \
1824 ELSE 20::INTEGER END::INTEGER AS a",
1825 );
1826 }
1827
1828 /// The same expression twice, which is where the tree walk copies the column twice and this
1829 /// does not, and the answers still have to be identical.
1830 #[test]
1831 fn a_column_mentioned_three_times_agrees() {
1832 agrees("\"+\"(\"+\"(#0.0::INTEGER, #0.0::INTEGER)::INTEGER, #0.0::INTEGER)::INTEGER AS a");
1833 }
1834
1835 /// The intermediates of a chain are not all held to the end of it.
1836 ///
1837 /// This is the whole difference between the prepared form being faster than the tree walk on a
1838 /// deep chain and being slower than it, and it is a property of the slot array rather than of
1839 /// any answer, so it is asserted here rather than left to the benchmark to catch.
1840 #[test]
1841 fn a_chain_holds_one_intermediate_at_a_time() {
1842 let (schema, chunk) = input();
1843 let mut expr = "#0.0::INTEGER".to_string();
1844 for _ in 0..8 {
1845 expr = format!("\"+\"({expr}, 1::INTEGER)::INTEGER");
1846 }
1847 let (plan, list) = projection(&format!("{expr} AS a"));
1848 let prepared = Prepared::new(&plan, &list, &schema).expect("the chain resolves");
1849 let mut scratch = prepared.scratch();
1850 prepared.run(&chunk, &mut scratch).expect("the chain runs");
1851 let live = scratch.slots.iter().filter(|slot| slot.is_some()).count();
1852 assert_eq!(live, 1, "a chain that has run should be holding its answer and nothing else");
1853 }
1854
1855 /// The rows a threaded filter keeps are the rows the tree walk says the predicate is true for.
1856 ///
1857 /// Every threaded conjunct is a chance to disagree with the unthreaded answer about a null,
1858 /// about a row an earlier conjunct had already dropped, or about a chunk nothing survives, and
1859 /// the answer is a set of row numbers rather than a vector, so this is checked against the tree
1860 /// walk read a row at a time rather than against the prepared form it is part of.
1861 fn filters(predicate: &str) {
1862 let (schema, chunk) = input();
1863 let (plan, list) = projection(&format!("{predicate} AS p"));
1864 let prepared = Prepared::new(&plan, &list, &schema).expect("the predicate resolves");
1865 let mut scratch = prepared.scratch();
1866 let threaded = prepared.evaluate_filter(&chunk, &mut scratch).expect("the filter runs");
1867 let flags = evaluate(&plan, list[0], &schema, &chunk).expect("the tree walk runs");
1868 let expected = Selection::from_predicate(chunk.len(), |row| is_true(&flags.value_at(row)));
1869 assert_eq!(threaded, expected, "`{predicate}`");
1870 // And running it again over the same scratch is the same answer, because a pipeline calls
1871 // this once a chunk and a slot left behind by the conjunct before would show up here.
1872 let again = prepared.evaluate_filter(&chunk, &mut scratch).expect("the filter runs again");
1873 assert_eq!(again, expected, "`{predicate}` a second time");
1874 }
1875
1876 /// A predicate with no `AND` in it is not threaded and has to keep saying the same thing.
1877 #[test]
1878 fn a_single_comparison_filters_the_same_rows() {
1879 filters("(#0.0::INTEGER > 1::INTEGER)::BOOLEAN");
1880 filters("(#0.1::VARCHAR = 'a'::VARCHAR)::BOOLEAN");
1881 filters("(#0.0::INTEGER IS NOT DISTINCT FROM NULL::INTEGER)::BOOLEAN");
1882 }
1883
1884 #[test]
1885 fn a_chain_of_conjuncts_keeps_what_all_of_them_keep() {
1886 filters(
1887 "((#0.0::INTEGER > 1::INTEGER)::BOOLEAN AND (#0.0::INTEGER < 3::INTEGER)::BOOLEAN)\
1888 ::BOOLEAN",
1889 );
1890 filters(
1891 "((#0.0::INTEGER >= 1::INTEGER)::BOOLEAN AND (#0.0::INTEGER <= 3::INTEGER)::BOOLEAN \
1892 AND (#0.1::VARCHAR = 'a'::VARCHAR)::BOOLEAN AND (#0.0::INTEGER <> 2::INTEGER)\
1893 ::BOOLEAN)::BOOLEAN",
1894 );
1895 }
1896
1897 /// A conjunct that rejects every row, in front of one that would have kept some. The rows are
1898 /// the same either way and the point of the shape is that the second conjunct never runs.
1899 #[test]
1900 fn a_conjunct_that_keeps_nothing_ends_the_predicate() {
1901 filters(
1902 "((#0.0::INTEGER > 9::INTEGER)::BOOLEAN AND (#0.0::INTEGER < 9::INTEGER)::BOOLEAN)\
1903 ::BOOLEAN",
1904 );
1905 }
1906
1907 /// A conjunct whose operands are computed rather than read, which is the shape where the
1908 /// comparison is threaded and the arithmetic under it is not.
1909 #[test]
1910 fn a_conjunct_over_a_computed_operand_keeps_the_same_rows() {
1911 filters(
1912 "((#0.0::INTEGER > 1::INTEGER)::BOOLEAN AND \
1913 (\"+\"(#0.0::INTEGER, 1::INTEGER)::INTEGER < 4::INTEGER)::BOOLEAN)::BOOLEAN",
1914 );
1915 }
1916
1917 /// A conjunct that is not a comparison at all, which is the one that goes through the flag
1918 /// kernel rather than the comparison kernel.
1919 #[test]
1920 fn a_conjunct_that_is_not_a_comparison_is_threaded_too() {
1921 filters(
1922 "((#0.0::INTEGER > 1::INTEGER)::BOOLEAN AND ((#0.1::VARCHAR = 'a'::VARCHAR)::BOOLEAN \
1923 OR (#0.0::INTEGER = 1::INTEGER)::BOOLEAN)::BOOLEAN)::BOOLEAN",
1924 );
1925 filters(
1926 "(((#0.1::VARCHAR = 'c'::VARCHAR)::BOOLEAN OR (#0.0::INTEGER = 3::INTEGER)::BOOLEAN)\
1927 ::BOOLEAN AND (#0.0::INTEGER <> 1::INTEGER)::BOOLEAN)::BOOLEAN",
1928 );
1929 }
1930
1931 #[test]
1932 fn a_selective_conjunct_evaluates_later_like_on_its_survivors() {
1933 filters(
1934 "((#0.0::INTEGER > 2::INTEGER)::BOOLEAN AND \
1935 \"~~\"(#0.1::VARCHAR, '%a%'::VARCHAR)::BOOLEAN)::BOOLEAN",
1936 );
1937 filters(
1938 "((#0.0::INTEGER > 2::INTEGER)::BOOLEAN AND \
1939 \"!~~\"(#0.1::VARCHAR, '%a%'::VARCHAR)::BOOLEAN)::BOOLEAN",
1940 );
1941 }
1942
1943 /// An `OR` at the top threads the complement: the second branch only sees the rows the first
1944 /// one did not accept, and the rows it accepts are added to them rather than replacing them.
1945 ///
1946 /// The input has a row where the first branch is true, one where the second is, one where both
1947 /// are false and one where the first is null and the second is true, which is the row that says
1948 /// whether the complement was taken over "not true" or over "false".
1949 #[test]
1950 fn an_or_at_the_top_threads_the_complement() {
1951 filters(
1952 "((#0.0::INTEGER > 2::INTEGER)::BOOLEAN OR (#0.1::VARCHAR = 'c'::VARCHAR)::BOOLEAN)\
1953 ::BOOLEAN",
1954 );
1955 filters(
1956 "((#0.0::INTEGER = 1::INTEGER)::BOOLEAN OR (#0.1::VARCHAR = 'a'::VARCHAR)::BOOLEAN \
1957 OR (#0.0::INTEGER > 2::INTEGER)::BOOLEAN)::BOOLEAN",
1958 );
1959 }
1960
1961 /// A branch that accepts every row, in front of one that would have accepted none. The rows are
1962 /// the same either way and the point of the shape is that the second branch never runs.
1963 #[test]
1964 fn a_branch_that_keeps_everything_ends_the_predicate() {
1965 filters(
1966 "((#0.0::INTEGER IS NOT DISTINCT FROM #0.0::INTEGER)::BOOLEAN OR \
1967 (#0.0::INTEGER > 9::INTEGER)::BOOLEAN)::BOOLEAN",
1968 );
1969 }
1970
1971 /// The branches after one that has accepted every row really are skipped.
1972 ///
1973 /// Every other test here says the threaded answer matches the unthreaded one, which it would
1974 /// even if nothing were threaded at all. This one puts a division by zero behind a branch that
1975 /// accepts everything, so the predicate raises if the second branch runs and does not if the
1976 /// walk stopped where it was supposed to.
1977 #[test]
1978 fn a_branch_behind_one_that_accepted_every_row_does_not_run() {
1979 let (schema, chunk) = input();
1980 let predicate = "((#0.0::INTEGER IS NOT DISTINCT FROM #0.0::INTEGER)::BOOLEAN OR \
1981 (\"//\"(#0.0::INTEGER, 0::INTEGER)::INTEGER > 0::INTEGER)::BOOLEAN)\
1982 ::BOOLEAN";
1983 let (plan, list) = projection(&format!("{predicate} AS p"));
1984 let prepared = Prepared::new(&plan, &list, &schema).expect("the predicate resolves");
1985 let mut scratch = prepared.scratch();
1986 let kept =
1987 prepared.evaluate_filter(&chunk, &mut scratch).expect("the second branch never runs");
1988 assert_eq!(kept, Selection::identity(chunk.len()));
1989 // And the same predicate evaluated as an expression does divide by zero, which is what says
1990 // the test is testing the threading rather than a predicate that happens not to raise.
1991 evaluate(&plan, list[0], &schema, &chunk).expect_err("the tree walk divides by zero");
1992 }
1993
1994 /// The conjunct that rejects the most rows ends up in front of the one that rejects none.
1995 ///
1996 /// The predicate is written the wrong way round on purpose. The plan order costs two passes a
1997 /// chunk where one would do, and after a chunk of watching it the filter runs the selective one
1998 /// first and the other one stops running at all.
1999 #[test]
2000 fn a_filter_learns_which_conjunct_to_run_first() {
2001 let (schema, chunk) = input();
2002 let predicate = "((#0.0::INTEGER > 0::INTEGER)::BOOLEAN AND (#0.0::INTEGER > 9::INTEGER)\
2003 ::BOOLEAN)::BOOLEAN";
2004 let (plan, list) = projection(&format!("{predicate} AS p"));
2005 let prepared = Prepared::new(&plan, &list, &schema).expect("the predicate resolves");
2006 let mut scratch = prepared.scratch();
2007 let root = prepared.roots[0];
2008 assert_eq!(scratch.order(root), None, "nothing has run yet");
2009 let kept = prepared.evaluate_filter(&chunk, &mut scratch).expect("the filter runs");
2010 assert!(kept.is_empty());
2011 assert_eq!(scratch.order(root), Some(&[1, 0][..]), "the second conjunct rejects the most");
2012 // And it stays there, because the conjunct that now runs first empties the selection and
2013 // the one behind it keeps the history it already had rather than losing it.
2014 let kept = prepared.evaluate_filter(&chunk, &mut scratch).expect("the filter runs again");
2015 assert!(kept.is_empty());
2016 assert_eq!(scratch.order(root), Some(&[1, 0][..]));
2017 }
2018
2019 /// Whatever order it settles on, the rows are the rows.
2020 ///
2021 /// Run for longer than the window is wide, because an order that changes halfway through a scan
2022 /// is the shape where a walk that got the subtree bookkeeping wrong would start reading the
2023 /// wrong steps, and the first chunk would not show it.
2024 #[test]
2025 fn reordering_never_changes_which_rows_survive() {
2026 let (schema, chunk) = input();
2027 let predicate = "((#0.0::INTEGER >= 1::INTEGER)::BOOLEAN AND \
2028 (\"+\"(#0.0::INTEGER, 1::INTEGER)::INTEGER < 4::INTEGER)::BOOLEAN AND \
2029 (#0.1::VARCHAR = 'a'::VARCHAR)::BOOLEAN)::BOOLEAN";
2030 let (plan, list) = projection(&format!("{predicate} AS p"));
2031 let prepared = Prepared::new(&plan, &list, &schema).expect("the predicate resolves");
2032 let mut scratch = prepared.scratch();
2033 let flags = evaluate(&plan, list[0], &schema, &chunk).expect("the tree walk runs");
2034 let expected = Selection::from_predicate(chunk.len(), |row| is_true(&flags.value_at(row)));
2035 for round in 0..40 {
2036 let kept = prepared.evaluate_filter(&chunk, &mut scratch).expect("the filter runs");
2037 assert_eq!(kept, expected, "round {round}");
2038 }
2039 }
2040
2041 /// A nested connective is threaded rather than evaluated into flags.
2042 ///
2043 /// The inner `AND` keeps nothing, so its second conjunct is never reached and the division by
2044 /// zero in it never happens. Evaluating the branch as an expression and narrowing the flags
2045 /// afterwards, which is what an operand that is not a connective still does, would have run it.
2046 #[test]
2047 fn a_nested_connective_stops_where_the_outer_one_would() {
2048 let (schema, chunk) = input();
2049 let predicate = "((#0.0::INTEGER > 9::INTEGER)::BOOLEAN OR ((#0.0::INTEGER > 9::INTEGER)\
2050 ::BOOLEAN AND (\"//\"(#0.0::INTEGER, 0::INTEGER)::INTEGER > 0::INTEGER)\
2051 ::BOOLEAN)::BOOLEAN)::BOOLEAN";
2052 let (plan, list) = projection(&format!("{predicate} AS p"));
2053 let prepared = Prepared::new(&plan, &list, &schema).expect("the predicate resolves");
2054 let mut scratch = prepared.scratch();
2055 let kept =
2056 prepared.evaluate_filter(&chunk, &mut scratch).expect("the division never happens");
2057 assert!(kept.is_empty());
2058 evaluate(&plan, list[0], &schema, &chunk).expect_err("the tree walk divides by zero");
2059 }
2060
2061 /// A branch that is not a comparison, which is the one that goes through the flag kernel.
2062 #[test]
2063 fn an_or_branch_that_is_not_a_comparison_is_threaded_too() {
2064 filters(
2065 "((#0.0::INTEGER > 2::INTEGER)::BOOLEAN OR \
2066 \"~~\"(#0.1::VARCHAR, 'a%'::VARCHAR)::BOOLEAN)::BOOLEAN",
2067 );
2068 filters(
2069 "(\"~~\"(#0.1::VARCHAR, 'c%'::VARCHAR)::BOOLEAN OR (#0.0::INTEGER = 1::INTEGER)\
2070 ::BOOLEAN)::BOOLEAN",
2071 );
2072 }
2073
2074 /// A connective inside a connective, which recurses rather than falling back to flags.
2075 ///
2076 /// Both nestings, because the two carry opposite things: an `AND` under an `OR` starts from the
2077 /// rows no branch has accepted, and an `OR` under an `AND` starts from the rows every conjunct
2078 /// has kept, and getting either one backwards is a wrong set of rows.
2079 #[test]
2080 fn a_connective_inside_a_connective_threads_both_ways() {
2081 filters(
2082 "(((#0.0::INTEGER >= 2::INTEGER)::BOOLEAN AND (#0.1::VARCHAR = 'a'::VARCHAR)::BOOLEAN)\
2083 ::BOOLEAN OR ((#0.0::INTEGER < 2::INTEGER)::BOOLEAN AND (#0.1::VARCHAR <> 'c'\
2084 ::VARCHAR)::BOOLEAN)::BOOLEAN)::BOOLEAN",
2085 );
2086 filters(
2087 "(((#0.1::VARCHAR = 'c'::VARCHAR)::BOOLEAN OR (#0.0::INTEGER = 3::INTEGER)::BOOLEAN)\
2088 ::BOOLEAN AND ((#0.0::INTEGER <> 1::INTEGER)::BOOLEAN OR (#0.1::VARCHAR = 'a'\
2089 ::VARCHAR)::BOOLEAN)::BOOLEAN)::BOOLEAN",
2090 );
2091 // Three deep, since two levels is where an off by one in the subtree bookkeeping can still
2092 // be hidden by the ranges lining up.
2093 filters(
2094 "((#0.0::INTEGER > 9::INTEGER)::BOOLEAN OR ((#0.0::INTEGER >= 1::INTEGER)::BOOLEAN \
2095 AND ((#0.1::VARCHAR = 'a'::VARCHAR)::BOOLEAN OR (#0.0::INTEGER = 1::INTEGER)\
2096 ::BOOLEAN)::BOOLEAN)::BOOLEAN)::BOOLEAN",
2097 );
2098 }
2099
2100 /// A predicate where one side is null and the other is true, in both orders. `OR` is true there
2101 /// and a complement taken over the rows a branch rejected rather than the rows it accepted
2102 /// would drop the row, which is the one way this can be wrong and is not a wrong vector but a
2103 /// missing row.
2104 #[test]
2105 fn a_null_branch_beside_a_true_one_keeps_the_row() {
2106 filters(
2107 "((#0.0::INTEGER > 2::INTEGER)::BOOLEAN OR (#0.1::VARCHAR = 'c'::VARCHAR)::BOOLEAN \
2108 OR (#0.0::INTEGER IS NOT DISTINCT FROM NULL::INTEGER)::BOOLEAN)::BOOLEAN",
2109 );
2110 filters(
2111 "((#0.1::VARCHAR > 'b'::VARCHAR)::BOOLEAN OR (#0.0::INTEGER = 1::INTEGER)::BOOLEAN)\
2112 ::BOOLEAN",
2113 );
2114 }
2115
2116 /// A filter over a chunk that has already been narrowed, which is what a second filter in a
2117 /// pipeline sees and is the form pair the threaded kernels have to handle rather than fall
2118 /// through on.
2119 #[test]
2120 fn a_filter_over_a_selected_chunk_keeps_the_same_rows() {
2121 let (schema, chunk) = input();
2122 let predicate = "((#0.0::INTEGER >= 1::INTEGER)::BOOLEAN AND \
2123 (#0.1::VARCHAR = 'a'::VARCHAR)::BOOLEAN)::BOOLEAN";
2124 let (plan, list) = projection(&format!("{predicate} AS p"));
2125 let prepared = Prepared::new(&plan, &list, &schema).expect("the predicate resolves");
2126 let mut scratch = prepared.scratch();
2127 let narrowed = narrow(&chunk, &[0, 3]).expect("two of the four rows");
2128 let threaded = prepared.evaluate_filter(&narrowed, &mut scratch).expect("the filter runs");
2129 let flags = evaluate(&plan, list[0], &schema, &narrowed).expect("the tree walk runs");
2130 let expected =
2131 Selection::from_predicate(narrowed.len(), |row| is_true(&flags.value_at(row)));
2132 assert_eq!(threaded, expected);
2133 }
2134
2135 /// Preparing is per pipeline and evaluating is per chunk, so the scratch has to survive being
2136 /// used again and give the same answer the second time.
2137 #[test]
2138 fn a_scratch_used_twice_gives_the_same_answer_twice() {
2139 let (schema, chunk) = input();
2140 let (plan, list) = projection("\"+\"(#0.0::INTEGER, 1::INTEGER)::INTEGER AS a");
2141 let prepared = Prepared::new(&plan, &list, &schema).expect("the expressions resolve");
2142 let mut scratch = prepared.scratch();
2143 let mut once = Vec::new();
2144 prepared.evaluate(&chunk, &mut scratch, &mut once).expect("the first chunk runs");
2145 let mut twice = Vec::new();
2146 prepared.evaluate(&chunk, &mut scratch, &mut twice).expect("the second chunk runs");
2147 assert_eq!(once, twice);
2148 }
2149
2150 #[test]
2151 fn a_shared_computed_root_is_compiled_once() {
2152 let (schema, chunk) = input();
2153 let (plan, list) = projection("\"+\"(#0.0::INTEGER, 1::INTEGER)::INTEGER AS a");
2154 let prepared = Prepared::shared(&plan, &[list[0], list[0]], &schema)
2155 .expect("the shared expression resolves");
2156 assert_eq!(prepared.steps.len(), 3);
2157 let mut scratch = prepared.scratch();
2158 let mut answers = Vec::new();
2159 prepared.evaluate(&chunk, &mut scratch, &mut answers).expect("both roots are returned");
2160 assert_eq!(answers[0], answers[1]);
2161 }
2162
2163 /// A chunk shorter than the last one, because a scan's final chunk is that and a constant
2164 /// materialized to the wrong length would be an out of range read rather than a wrong answer.
2165 #[test]
2166 fn a_shorter_chunk_after_a_longer_one_is_evaluated_at_its_own_length() {
2167 let (schema, chunk) = input();
2168 let (plan, list) = projection("7::INTEGER AS a");
2169 let prepared = Prepared::new(&plan, &list, &schema).expect("the expressions resolve");
2170 let mut scratch = prepared.scratch();
2171 let mut full = Vec::new();
2172 prepared.evaluate(&chunk, &mut scratch, &mut full).expect("the full chunk runs");
2173 assert_eq!(full[0].len(), 4);
2174 let short = chunk
2175 .clone()
2176 .select(&{
2177 let mut selection = Selection::with_capacity(2);
2178 selection.push(0);
2179 selection.push(2);
2180 selection
2181 })
2182 .expect("two of the four rows");
2183 let mut cut = Vec::new();
2184 prepared.evaluate(&short, &mut scratch, &mut cut).expect("the short chunk runs");
2185 assert_eq!(cut[0].len(), 2);
2186 }
2187
2188 /// An aggregate is not an expression and saying so when the pipeline is built is better than
2189 /// saying it on the first chunk.
2190 #[test]
2191 fn an_aggregate_is_refused_when_it_is_prepared() {
2192 let (schema, _) = input();
2193 let text = "Aggregate #1 groups=[] aggregates=[sum(#0.0::INTEGER)::HUGEINT]\n \
2194 Get memory.main.t AS t #0 [x::INTEGER, s::VARCHAR]";
2195 let plan = Plan::parse(text).expect("a well formed plan");
2196 let Node::Aggregate { aggregates, .. } = *plan.node(plan.root()) else {
2197 panic!("the root of that text is an aggregate");
2198 };
2199 let list = plan.expr_list(aggregates).to_vec();
2200 let error = Prepared::new(&plan, &list, &schema).expect_err("sum is not a scalar");
2201 assert!(error.message().contains("sum"), "{error}");
2202 }
2203
2204 /// How many of an expression's function steps worked something out when it was prepared, and
2205 /// whether the answer it gives is still the tree walk's answer.
2206 ///
2207 /// The count is the point of the assertion, because an answer that moved would be a bug. The
2208 /// agreement is what says the answer did not move.
2209 fn prepares(expr: &str, lifted: usize) {
2210 let (schema, _) = input();
2211 let projected = format!("{expr} AS a");
2212 let (plan, list) = projection(&projected);
2213 let prepared = Prepared::new(&plan, &list, &schema).expect("the expression resolves");
2214 assert_eq!(prepared.hoisted(), lifted, "`{expr}`");
2215 agrees(&projected);
2216 }
2217
2218 /// A pattern the user wrote is compiled where the plan is, which is once.
2219 #[test]
2220 fn a_literal_pattern_is_compiled_when_the_pipeline_is_built() {
2221 prepares("\"~~\"(#0.1::VARCHAR, 'a%'::VARCHAR)::BOOLEAN", 1);
2222 prepares("\"~~*\"(#0.1::VARCHAR, '%A%'::VARCHAR)::BOOLEAN", 1);
2223 }
2224
2225 /// A regular expression, which is the one where the compiling is worth real time.
2226 ///
2227 /// ClickBench query 29 runs one pattern over a hundred million rows, which is a hundred thousand
2228 /// chunks, and before this each of those hundred thousand compiled the pattern again.
2229 #[test]
2230 fn a_regular_expression_is_compiled_when_the_pipeline_is_built() {
2231 prepares("\"regexp_matches\"(#0.1::VARCHAR, '^a'::VARCHAR)::BOOLEAN", 1);
2232 prepares("\"regexp_replace\"(#0.1::VARCHAR, 'a'::VARCHAR, 'b'::VARCHAR)::VARCHAR", 1);
2233 }
2234
2235 /// A pattern that is not a literal, which is legal SQL and is decided per chunk as it was.
2236 #[test]
2237 fn a_pattern_that_is_not_a_literal_is_left_to_the_chunk() {
2238 prepares("\"~~\"(#0.1::VARCHAR, #0.1::VARCHAR)::BOOLEAN", 0);
2239 }
2240
2241 /// A function with nothing to work out, which is almost all of them.
2242 #[test]
2243 fn a_function_with_no_prepare_step_prepares_nothing() {
2244 prepares("\"upper\"(#0.1::VARCHAR)::VARCHAR", 0);
2245 }
2246
2247 /// How many of an expression's steps are a folded `IN`, and whether the answer still agrees.
2248 fn folds(expr: &str, sets: usize) {
2249 let (schema, _) = input();
2250 let projected = format!("{expr} AS a");
2251 let (plan, list) = projection(&projected);
2252 let prepared = Prepared::new(&plan, &list, &schema).expect("the expression resolves");
2253 assert_eq!(prepared.sets(), sets, "`{expr}`");
2254 agrees(&projected);
2255 }
2256
2257 /// What the binder writes for `x IN (1, 3)`, folded back into one lookup.
2258 ///
2259 /// The test goes through the plan's text, where the three mentions of the column are three
2260 /// expressions rather than one, which is the case `same` exists for. A plan the binder built has
2261 /// one mention and takes the first line of it.
2262 #[test]
2263 fn an_in_list_becomes_one_lookup() {
2264 folds(
2265 "((#0.0::INTEGER = 1::INTEGER)::BOOLEAN OR (#0.0::INTEGER = 3::INTEGER)::BOOLEAN)\
2266 ::BOOLEAN",
2267 1,
2268 );
2269 folds(
2270 "((#0.1::VARCHAR = 'a'::VARCHAR)::BOOLEAN OR (#0.1::VARCHAR = 'z'::VARCHAR)::BOOLEAN)\
2271 ::BOOLEAN",
2272 1,
2273 );
2274 }
2275
2276 /// `NOT IN`, which the binder writes as an `AND` of inequalities and which reads the same
2277 /// lookup the other way round.
2278 #[test]
2279 fn a_not_in_list_becomes_the_same_lookup() {
2280 folds(
2281 "((#0.0::INTEGER <> 1::INTEGER)::BOOLEAN AND (#0.0::INTEGER <> 3::INTEGER)::BOOLEAN)\
2282 ::BOOLEAN",
2283 1,
2284 );
2285 }
2286
2287 /// A list with a null in it, which is the rule that makes an `IN` not a set lookup.
2288 ///
2289 /// A row that is not in the list is null rather than false, because it might have equalled the
2290 /// value the null stands for. `agrees` is what says the fold kept that, since the `OR` of
2291 /// comparisons it is checked against gets it from three valued logic for free.
2292 #[test]
2293 fn a_list_with_a_null_in_it_folds_and_keeps_the_null_rule() {
2294 folds(
2295 "((#0.0::INTEGER = 1::INTEGER)::BOOLEAN OR (#0.0::INTEGER = NULL::INTEGER)::BOOLEAN \
2296 OR (#0.0::INTEGER = 3::INTEGER)::BOOLEAN)::BOOLEAN",
2297 1,
2298 );
2299 folds(
2300 "((#0.0::INTEGER <> 1::INTEGER)::BOOLEAN AND (#0.0::INTEGER <> NULL::INTEGER)\
2301 ::BOOLEAN AND (#0.0::INTEGER <> 3::INTEGER)::BOOLEAN)::BOOLEAN",
2302 1,
2303 );
2304 }
2305
2306 /// The connectives that are not an `IN`, each for its own reason.
2307 #[test]
2308 fn a_connective_that_is_not_an_in_list_is_left_alone() {
2309 // Two different columns.
2310 folds(
2311 "((#0.0::INTEGER = 1::INTEGER)::BOOLEAN OR (#0.1::VARCHAR = 'a'::VARCHAR)::BOOLEAN)\
2312 ::BOOLEAN",
2313 0,
2314 );
2315 // One equality and one of something else.
2316 folds(
2317 "((#0.0::INTEGER = 1::INTEGER)::BOOLEAN OR (#0.0::INTEGER > 3::INTEGER)::BOOLEAN)\
2318 ::BOOLEAN",
2319 0,
2320 );
2321 // The right hand side is a column rather than a literal.
2322 folds(
2323 "((#0.0::INTEGER = 1::INTEGER)::BOOLEAN OR (#0.0::INTEGER = #0.0::INTEGER)::BOOLEAN)\
2324 ::BOOLEAN",
2325 0,
2326 );
2327 // An `AND` of equalities is not a `NOT IN`, it is a predicate that is false unless the two
2328 // literals are the same. Folding it as one would answer true where it answers false.
2329 folds(
2330 "((#0.0::INTEGER = 1::INTEGER)::BOOLEAN AND (#0.0::INTEGER = 3::INTEGER)::BOOLEAN)\
2331 ::BOOLEAN",
2332 0,
2333 );
2334 }
2335
2336 /// The same thing in a filter, which is the shape it is written in.
2337 #[test]
2338 fn an_in_list_filters_the_same_rows() {
2339 filters(
2340 "((#0.0::INTEGER = 1::INTEGER)::BOOLEAN OR (#0.0::INTEGER = 3::INTEGER)::BOOLEAN)\
2341 ::BOOLEAN",
2342 );
2343 filters(
2344 "((#0.0::INTEGER <> 1::INTEGER)::BOOLEAN AND (#0.0::INTEGER <> 3::INTEGER)::BOOLEAN)\
2345 ::BOOLEAN",
2346 );
2347 // Inside a larger predicate, where the fold is one operand of the connective above it.
2348 filters(
2349 "(((#0.0::INTEGER = 1::INTEGER)::BOOLEAN OR (#0.0::INTEGER = 3::INTEGER)::BOOLEAN)\
2350 ::BOOLEAN AND (#0.1::VARCHAR = 'a'::VARCHAR)::BOOLEAN)::BOOLEAN",
2351 );
2352 }
2353
2354 /// The literal side of a comparison is turned into a column when the pipeline is built.
2355 #[test]
2356 fn a_comparison_against_a_literal_builds_it_once() {
2357 let (schema, _) = input();
2358 for (expr, built) in [
2359 ("(#0.1::VARCHAR = 'a'::VARCHAR)::BOOLEAN AS p", 1),
2360 ("(#0.0::INTEGER > 1::INTEGER)::BOOLEAN AS p", 1),
2361 // The literal on the left, which is the same comparison written the other way round.
2362 ("(1::INTEGER < #0.0::INTEGER)::BOOLEAN AS p", 1),
2363 // Two columns, which has no literal side to build.
2364 ("(#0.0::INTEGER = #0.0::INTEGER)::BOOLEAN AS p", 0),
2365 // Two literals, which the kernel answers once for the whole vector without reading a
2366 // column, so building one would be work that nothing reads.
2367 ("(1::INTEGER = 2::INTEGER)::BOOLEAN AS p", 0),
2368 ] {
2369 let (plan, list) = projection(expr);
2370 let prepared = Prepared::new(&plan, &list, &schema).expect("the expression resolves");
2371 assert_eq!(prepared.literals_built(), built, "`{expr}`");
2372 agrees(expr);
2373 }
2374 }
2375
2376 /// A pattern that does not compile still fails where the query said it does.
2377 ///
2378 /// Preparing is not allowed to move an error earlier. Compiling at build time and reporting
2379 /// there would raise before a row had been read, and under a `CASE` arm it would raise on a
2380 /// query whose rows never reach the call at all.
2381 #[test]
2382 fn a_pattern_that_does_not_compile_fails_on_the_chunk_and_not_before() {
2383 let (schema, chunk) = input();
2384 let (plan, list) =
2385 projection("\"regexp_matches\"(#0.1::VARCHAR, 'a('::VARCHAR)::BOOLEAN AS a");
2386 let prepared = Prepared::new(&plan, &list, &schema).expect("preparing does not compile it");
2387 assert_eq!(prepared.hoisted(), 0);
2388 let mut scratch = prepared.scratch();
2389 let mut out = Vec::new();
2390 prepared.evaluate(&chunk, &mut scratch, &mut out).expect_err("the chunk raises");
2391 }
2392}