Skip to main content

rudb_opt/
lib.rs

1//! The rewrite passes, cardinality estimation, join ordering, predicate transfer and layout adaptation.
2//!
3//! Rank 11 in the layer rule. See `xtask/layers.toml` and `spec/18-package-layout.md`.
4//!
5//! Six passes so far. `spec/09-optimizer.md` section 9.1 describes a sequence and [`PASSES`] is
6//! the start of it. Column pruning came first, because it is the pass whose absence is measured in
7//! gigabytes: a scan that reads 105 columns to answer a question about three is the whole of the
8//! difference on ClickBench, and the Parquet reader has been able to read a subset since M1 with
9//! nothing able to tell it which subset.
10
11#![forbid(unsafe_code)]
12
13pub mod columns;
14pub mod distinct;
15pub mod empty;
16pub mod estimate;
17pub mod explain;
18pub mod filter;
19pub mod fold;
20pub mod late;
21pub mod limit;
22pub mod nulls;
23pub mod pass;
24pub mod tables;
25pub mod topn;
26mod transitive;
27mod walk;
28
29use rudb_common::{Error, Result};
30use rudb_plan::{Node, NodeRef, Plan};
31
32use crate::pass::{Context, Pass};
33
34/// The crate this rank belongs to, so that the layer check has something to read.
35pub const RANK: u8 = 11;
36
37/// The passes, in the order they run.
38///
39/// A fixed sequence rather than a loop to a fixed point, which is what `spec/09-optimizer.md`
40/// section 9.1 asks for and what DuckDB does. A fixed point is easy to write and hard to bound: a
41/// pair of passes that undo each other runs forever, and the version that stops after a few rounds
42/// has a plan that depends on how many rounds it was given.
43///
44/// Folding is before pruning because folding removes column references and pruning drops the columns
45/// nothing refers to, so a `CASE WHEN false THEN t.a ELSE 1 END` costs a column read when the two run
46/// the other way around. Nothing in the other direction is given up: pruning drops columns and
47/// renumbers bindings, and neither of those makes anything foldable.
48///
49/// Filter pushdown goes between them. After folding, because a predicate that folds to a constant is
50/// a predicate with nothing to push and the pass that moves it should not be the one that finds out.
51/// Before pruning, because moving a filter below a projection rewrites it in terms of columns the
52/// projection reads, and pruning has to see the plan after the move or it drops a column that
53/// something now refers to.
54///
55/// Empty result pullup is after filter pushdown, because pushdown is what moves an unsatisfiable
56/// predicate down to the scan it should stop and what drops the conjuncts that were always true, so
57/// the pass that looks for a predicate nothing can satisfy should look after that has happened. It
58/// is before pruning for the same reason folding is: the subtrees it removes are subtrees pruning
59/// would otherwise walk and work out column lists for.
60///
61/// Limit pushdown is second to last, which is to say it is immediately before top N. A limit that
62/// has moved below the projections above it is a limit that may now be sitting directly on a sort,
63/// and that pair is what top N fuses, so running the two the other way around would leave the fusion
64/// with a plan it cannot see the shape of.
65///
66/// The distinct aggregate rewrite is second, ahead of everything that moves an operator around,
67/// because it is the one pass that changes what an aggregate is rather than where it sits. Every
68/// other pass here is written against a single aggregate node, and running this one ahead of them
69/// means none of them has to know that `COUNT(DISTINCT x)` has a second spelling. In particular the
70/// limit that fuses into an aggregate has to fuse into the outer one, and after this pass the outer
71/// one is the only one it can see.
72///
73/// What it is not ahead of is folding, and that order is the other way round for a reason the AST
74/// fuzz target found. The rewrite fires only when every `DISTINCT` call in a node has the same
75/// argument, and whether two arguments are the same is a question folding answers: `max(DISTINCT
76/// 1 + 1)` and `min(DISTINCT 2)` are two arguments before it and one after it. With the rewrite
77/// first the pass sees the unfolded pair, refuses, and a second run of the sequence over its own
78/// output fires, which is the idempotence assertion below failing. Folding has no opinion about
79/// either spelling of an aggregate, so nothing is given up by putting it in front.
80///
81/// Top N is last, because it is the one pass that fuses two operators into one rather than moving
82/// something around. Everything before it is written against a sort and a limit, and a pass that had
83/// to know about both spellings of the same plan is a pass with two of every rule in it.
84pub static PASSES: [&(dyn Pass + Sync); 8] = [
85    &fold::ExpressionRewriter,
86    &distinct::DistinctAggregateRewrite,
87    &filter::FilterPushdown,
88    &empty::EmptyResultPullup,
89    &columns::UnusedColumns,
90    &limit::LimitPushdown,
91    &topn::TopN,
92    &late::LateMaterialization,
93];
94
95/// Every name `SET disabled_optimizers` accepts, which is every name DuckDB accepts.
96///
97/// `SELECT name FROM duckdb_optimizers()` on the pinned binary, sorted, all forty four of them.
98/// [`PASSES`] is the seven rudb has built and every name here is one rudb takes without complaint,
99/// because turning off a pass that does not exist is a thing that has already happened.
100///
101/// Accepting the other thirty seven is the whole point. Forty five files in the upstream corpus run
102/// a `SET disabled_optimizers`, and most of them name a pass rudb has not written, `join_order` and
103/// `build_side_probe_side` and `statistics_propagation` and the rest. Refusing those makes the
104/// `SET` fail, and a failed `SET` in a sqllogictest file ends the file, so every record after it
105/// goes unasked over a pass whose absence changes no answer.
106///
107/// The list is written down rather than discovered, because there is nothing to discover it from:
108/// DuckDB is a binary that may not be on the machine and this has to answer the same way when it is
109/// not. It is pinned to the same commit the rest of the compatibility work is pinned to, and a
110/// release that adds a pass adds a name here.
111pub static UPSTREAM: [&str; 44] = [
112    "aggregate_function_rewriter",
113    "aggregate_reuse",
114    "build_side_probe_side",
115    "column_lifetime",
116    "common_aggregate",
117    "common_subexpressions",
118    "common_subplan",
119    "compressed_materialization",
120    "cte_filter_pusher",
121    "cte_inlining",
122    "deliminator",
123    "distinct_aggregate_rewrite",
124    "duplicate_groups",
125    "empty_result_pullup",
126    "expression_rewriter",
127    "extension",
128    "filter_pullup",
129    "filter_pushdown",
130    "grouping_sets",
131    "in_clause",
132    "join_elimination",
133    "join_filter_pushdown",
134    "join_order",
135    "late_materialization",
136    "limit_pushdown",
137    "materialized_cte",
138    "outer_join_simplification",
139    "partial_aggregate_pushdown",
140    "partitioned_execution",
141    "projection_pullup",
142    "regex_range",
143    "remote_pushdown",
144    "reorder_filter",
145    "row_group_pruner",
146    "sampling_pushdown",
147    "scalar_fn_pushdown",
148    "statistics_propagation",
149    "top_n",
150    "top_n_window_elimination",
151    "type_pushdown",
152    "unnest_rewriter",
153    "unused_columns",
154    "window_rewriter",
155    "window_self_join",
156];
157
158/// Rewrites a bound plan into the plan that runs, with every pass on.
159///
160/// # Errors
161///
162/// If a pass left the plan malformed or narrowed what it returns, which is a bug in the pass and
163/// not in the query.
164pub fn optimize(plan: &mut Plan) -> Result<()> {
165    optimize_with(plan, &Context::new())
166}
167
168/// Rewrites a bound plan into the plan that runs, skipping the passes the context turned off.
169///
170/// Every pass preserves the plan invariant, which is what [`Plan::validate`] checks, so this checks
171/// it once at the end rather than each pass checking itself. In a release build it does not, because
172/// a pass that breaks the invariant breaks it the same way in both builds and the debug build is
173/// where that gets found.
174///
175/// It also checks that the plan still returns as many columns as it did on the way in. A malformed
176/// plan is found by whatever runs next, but a rewrite that quietly changes what a query returns is
177/// the one failure that running the query afterwards would not notice, and column pruning in
178/// particular is a pass whose only way of being wrong is exactly that.
179///
180/// It also checks, in a debug build, that running the whole sequence a second time changes nothing.
181/// That is the property that makes a fixed sequence the right shape: a pass that keeps finding work
182/// on a plan it has already rewritten is a pass whose output depends on how many times it happened
183/// to run, and in a fixed sequence it runs once, so the plan that reaches the executor is whatever
184/// the first pass left behind. Each pass has its own test for this and the assertion is here anyway,
185/// because the pair that is not idempotent together is usually a pair that is idempotent apart.
186///
187/// # Errors
188///
189/// Whatever a pass reported, and then, in a debug build, if a pass left the plan malformed, narrowed
190/// what it returns or did not settle, all three of which are a bug in the pass and not in the query.
191pub fn optimize_with(plan: &mut Plan, context: &Context) -> Result<()> {
192    run(plan, context, &PASSES)
193}
194
195/// The sequence, over a list of passes the tests can choose.
196fn run(plan: &mut Plan, context: &Context, passes: &[&(dyn Pass + Sync)]) -> Result<()> {
197    let before = output_columns(plan, plan.root());
198    once(plan, context, passes)?;
199    if cfg!(debug_assertions) {
200        plan.validate()?;
201        let after = output_columns(plan, plan.root());
202        if after != before {
203            return Err(Error::internal(format!(
204                "a pass turned a query of {before} columns into one of {after}"
205            )));
206        }
207        let settled = plan.to_string();
208        once(plan, context, passes)?;
209        let again = plan.to_string();
210        if again != settled {
211            return Err(Error::internal(format!(
212                "the passes did not settle, since running them again gave a different plan\n\n{settled}\n{again}"
213            )));
214        }
215    }
216    Ok(())
217}
218
219/// One run of every pass that is turned on.
220fn once(plan: &mut Plan, context: &Context, passes: &[&(dyn Pass + Sync)]) -> Result<()> {
221    for pass in passes {
222        if context.is_disabled(pass.name()) {
223            continue;
224        }
225        pass.run(plan, context)?;
226    }
227    Ok(())
228}
229
230/// How many columns a node produces, which no pass is allowed to change at the root.
231///
232/// The count rather than the names and types, because the root of a plan the binder builds is a
233/// projection and what has to hold is that a pass did not add or drop one of its expressions. The
234/// recursion is over the operators that pass their input's width through, so its depth is the
235/// nesting the binder already walked to build the plan.
236fn output_columns(plan: &Plan, reference: NodeRef) -> usize {
237    match *plan.node(reference) {
238        Node::Get { columns, .. }
239        | Node::Values { columns, .. }
240        | Node::TableFunction { columns, .. }
241        | Node::Fetch { columns, .. } => plan.field_list(columns).len(),
242        Node::Project { exprs, .. } => plan.expr_list(exprs).len(),
243        Node::Aggregate { groups, aggregates, .. } => {
244            plan.expr_list(groups).len() + plan.expr_list(aggregates).len()
245        }
246        Node::Dummy => 0,
247        Node::Filter { input, .. }
248        | Node::Sort { input, .. }
249        | Node::Limit { input, .. }
250        | Node::TopN { input, .. }
251        | Node::Distinct { input, .. } => output_columns(plan, input),
252        // A set operation is as wide as either side, since the binder already required the two to
253        // agree. A join and a cross product are as wide as the two together.
254        Node::SetOp { left, .. } => output_columns(plan, left),
255        Node::Join { left, right, .. } | Node::CrossProduct { left, right } => {
256            output_columns(plan, left) + output_columns(plan, right)
257        }
258    }
259}
260
261#[cfg(test)]
262mod tests {
263    use super::*;
264
265    /// How wide the plan a text prints is, before anything has run over it.
266    fn width(text: &str) -> usize {
267        let plan =
268            Plan::parse(text).unwrap_or_else(|error| panic!("{text} did not parse: {error}"));
269        output_columns(&plan, plan.root())
270    }
271
272    /// Optimize the plan a text prints and hand back what it printed afterwards.
273    fn optimized(text: &str) -> String {
274        let mut plan =
275            Plan::parse(text).unwrap_or_else(|error| panic!("{text} did not parse: {error}"));
276        optimize(&mut plan).unwrap_or_else(|error| panic!("{text} did not optimize: {error}"));
277        plan.to_string()
278    }
279
280    #[test]
281    fn the_width_of_a_plan_is_the_width_of_whatever_produces_its_columns() {
282        assert_eq!(
283            width(
284                "Project #1 [#0.0::INTEGER AS a]\n  Get memory.main.t AS t #0 [a::INTEGER, b::VARCHAR]\n"
285            ),
286            1
287        );
288        assert_eq!(width("Get memory.main.t AS t #0 [a::INTEGER, b::VARCHAR]\n"), 2);
289        assert_eq!(width("Dummy\n"), 0);
290        assert_eq!(
291            width(
292                "Aggregate #1 groups=[#0.0::INTEGER] aggregates=[count_star()::BIGINT]\n  Get memory.main.t AS t #0 [a::INTEGER]\n"
293            ),
294            2
295        );
296    }
297
298    /// A `LIMIT` or a `SORT` is as wide as what is under it, which is the recursion this function
299    /// exists for and the part a single level check would get wrong.
300    #[test]
301    fn an_operator_that_passes_its_input_through_is_as_wide_as_its_input() {
302        assert_eq!(
303            width("Limit 1 offset 0\n  Get memory.main.t AS t #0 [a::INTEGER, b::VARCHAR]\n"),
304            2
305        );
306    }
307
308    /// A join is both sides and a set operation is either one, since the binder already required
309    /// the two sides of a set operation to agree.
310    #[test]
311    fn a_join_is_both_sides_together_and_a_set_operation_is_one_of_them() {
312        assert_eq!(
313            width(
314                "Join INNER on=[]\n  Get memory.main.t AS t #0 [a::INTEGER, b::VARCHAR]\n  Get memory.main.u AS u #1 [x::INTEGER]\n"
315            ),
316            3
317        );
318        assert_eq!(
319            width(
320                "SetOp UNION ALL #2\n  Get memory.main.t AS t #0 [a::INTEGER]\n  Get memory.main.u AS u #1 [x::INTEGER]\n"
321            ),
322            1
323        );
324    }
325
326    /// The check is on the whole of `optimize` and not on one pass, so it keeps holding as passes
327    /// are added. This is the shape it runs over today.
328    #[test]
329    fn optimizing_keeps_a_query_as_wide_as_it_was() {
330        let before = "Project #1 [#0.1::VARCHAR AS b]\n  Get memory.main.t AS t #0 [a::INTEGER, b::VARCHAR]\n";
331        let after = "Project #1 [#0.0::VARCHAR AS b]\n  Get memory.main.t AS t #0 [b::VARCHAR]\n";
332        assert_eq!(optimized(before), after);
333        assert_eq!(width(before), width(after));
334    }
335
336    #[test]
337    fn no_two_passes_answer_to_the_same_name() {
338        // The name is the address, so two passes sharing one would make the toggle turn off
339        // whichever came first in the list and silently leave the other on.
340        let mut names: Vec<&str> = PASSES.iter().map(|pass| pass.name()).collect();
341        names.sort_unstable();
342        let held = names.len();
343        names.dedup();
344        assert_eq!(names.len(), held, "{names:?}");
345    }
346
347    #[test]
348    fn a_pass_that_is_turned_off_does_not_run() {
349        let text = "Project #1 [\"+\"(1::INTEGER, 1::INTEGER)::INTEGER AS n]\n  Get memory.main.t AS t #0 [a::INTEGER]\n";
350        let mut plan = Plan::parse(text).expect("a well formed plan");
351        let context = Context::without("expression_rewriter").expect("a name that is a pass");
352        optimize_with(&mut plan, &context).expect("the other pass still runs");
353        assert_eq!(
354            plan.to_string(),
355            "Project #1 [\"+\"(1::INTEGER, 1::INTEGER)::INTEGER AS n]\n  Get memory.main.t AS t #0 []\n"
356        );
357    }
358
359    /// A pass that finds the same work every time it looks, which is what the assertion is for.
360    #[derive(Debug)]
361    #[cfg(debug_assertions)]
362    struct Restless;
363
364    #[cfg(debug_assertions)]
365    impl Pass for Restless {
366        fn name(&self) -> &'static str {
367            "restless"
368        }
369
370        fn run(&self, plan: &mut Plan, _context: &Context) -> Result<()> {
371            let root = plan.root();
372            if !matches!(*plan.node(root), Node::Limit { .. }) {
373                return Ok(());
374            }
375            let stacked = plan.add_node(Node::Limit { input: root, count: Some(1), offset: 0 });
376            plan.set_root(stacked);
377            Ok(())
378        }
379    }
380
381    /// The settle check is a debug build check, so the test for it is a debug build test. Without
382    /// this the release profile job runs a test that asserts an error nothing was going to report,
383    /// which is what it had been doing since #196, because the per commit gate runs the tests once
384    /// and runs them in debug.
385    #[test]
386    #[cfg(debug_assertions)]
387    fn a_pass_that_never_settles_is_a_reported_error_and_not_a_plan() {
388        let text = "Limit 1 offset 0\n  Get memory.main.t AS t #0 [a::INTEGER]\n";
389        let mut plan = Plan::parse(text).expect("a well formed plan");
390        let error = run(&mut plan, &Context::new(), &[&Restless]).expect_err("it never settles");
391        assert!(error.message().starts_with("the passes did not settle"), "{}", error.message());
392    }
393
394    /// Folding before pruning, which is the reason the order in [`PASSES`] is the order it is. The
395    /// column is read only by a branch that cannot be taken, so one pass has to remove the branch
396    /// before the other can see that nothing reads the column.
397    #[test]
398    fn folding_runs_first_so_that_pruning_sees_the_columns_it_freed() {
399        let text = "Project #1 [CASE WHEN FALSE::BOOLEAN THEN #0.1::INTEGER ELSE #0.0::INTEGER END::INTEGER AS n]\n  Get memory.main.t AS t #0 [a::INTEGER, b::INTEGER]\n";
400        assert_eq!(
401            optimized(text),
402            "Project #1 [#0.0::INTEGER AS n]\n  Get memory.main.t AS t #0 [a::INTEGER]\n"
403        );
404    }
405
406    /// Folding before the distinct aggregate rewrite, which is the other half of that order. The
407    /// rewrite wants every `DISTINCT` call in a node to have the same argument, and these two have
408    /// the same argument only once folding has run, so with the passes the other way around the
409    /// rewrite refuses here and fires on a second run over its own output.
410    #[test]
411    fn folding_runs_first_so_that_the_distinct_rewrite_sees_one_argument_rather_than_two() {
412        let text = concat!(
413            "Aggregate #1 groups=[] aggregates=[max(DISTINCT \"+\"(1::INTEGER, 1::INTEGER)::INTEGER)::INTEGER, min(DISTINCT 2::INTEGER)::INTEGER]\n",
414            "  Dummy\n",
415        );
416        assert_eq!(
417            optimized(text),
418            concat!(
419                "Aggregate #1 groups=[] aggregates=[max(#2.0::INTEGER)::INTEGER, min(#2.0::INTEGER)::INTEGER]\n",
420                "  Aggregate #2 groups=[2::INTEGER] aggregates=[]\n",
421                "    Dummy\n",
422            )
423        );
424    }
425}