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 empty;
15pub mod filter;
16pub mod fold;
17pub mod limit;
18pub mod nulls;
19pub mod pass;
20pub mod tables;
21pub mod topn;
22mod transitive;
23mod walk;
24
25use rudb_common::{Error, Result};
26use rudb_plan::{Node, NodeRef, Plan};
27
28use crate::pass::{Context, Pass};
29
30/// The crate this rank belongs to, so that the layer check has something to read.
31pub const RANK: u8 = 11;
32
33/// The passes, in the order they run.
34///
35/// A fixed sequence rather than a loop to a fixed point, which is what `spec/09-optimizer.md`
36/// section 9.1 asks for and what DuckDB does. A fixed point is easy to write and hard to bound: a
37/// pair of passes that undo each other runs forever, and the version that stops after a few rounds
38/// has a plan that depends on how many rounds it was given.
39///
40/// Folding is before pruning because folding removes column references and pruning drops the columns
41/// nothing refers to, so a `CASE WHEN false THEN t.a ELSE 1 END` costs a column read when the two run
42/// the other way around. Nothing in the other direction is given up: pruning drops columns and
43/// renumbers bindings, and neither of those makes anything foldable.
44///
45/// Filter pushdown goes between them. After folding, because a predicate that folds to a constant is
46/// a predicate with nothing to push and the pass that moves it should not be the one that finds out.
47/// Before pruning, because moving a filter below a projection rewrites it in terms of columns the
48/// projection reads, and pruning has to see the plan after the move or it drops a column that
49/// something now refers to.
50///
51/// Empty result pullup is after filter pushdown, because pushdown is what moves an unsatisfiable
52/// predicate down to the scan it should stop and what drops the conjuncts that were always true, so
53/// the pass that looks for a predicate nothing can satisfy should look after that has happened. It
54/// is before pruning for the same reason folding is: the subtrees it removes are subtrees pruning
55/// would otherwise walk and work out column lists for.
56///
57/// Limit pushdown is second to last, which is to say it is immediately before top N. A limit that
58/// has moved below the projections above it is a limit that may now be sitting directly on a sort,
59/// and that pair is what top N fuses, so running the two the other way around would leave the fusion
60/// with a plan it cannot see the shape of.
61///
62/// Top N is last, because it is the one pass that fuses two operators into one rather than moving
63/// something around. Everything before it is written against a sort and a limit, and a pass that had
64/// to know about both spellings of the same plan is a pass with two of every rule in it.
65pub static PASSES: [&(dyn Pass + Sync); 6] = [
66 &fold::ExpressionRewriter,
67 &filter::FilterPushdown,
68 &empty::EmptyResultPullup,
69 &columns::UnusedColumns,
70 &limit::LimitPushdown,
71 &topn::TopN,
72];
73
74/// Rewrites a bound plan into the plan that runs, with every pass on.
75///
76/// # Errors
77///
78/// If a pass left the plan malformed or narrowed what it returns, which is a bug in the pass and
79/// not in the query.
80pub fn optimize(plan: &mut Plan) -> Result<()> {
81 optimize_with(plan, &Context::new())
82}
83
84/// Rewrites a bound plan into the plan that runs, skipping the passes the context turned off.
85///
86/// Every pass preserves the plan invariant, which is what [`Plan::validate`] checks, so this checks
87/// it once at the end rather than each pass checking itself. In a release build it does not, because
88/// a pass that breaks the invariant breaks it the same way in both builds and the debug build is
89/// where that gets found.
90///
91/// It also checks that the plan still returns as many columns as it did on the way in. A malformed
92/// plan is found by whatever runs next, but a rewrite that quietly changes what a query returns is
93/// the one failure that running the query afterwards would not notice, and column pruning in
94/// particular is a pass whose only way of being wrong is exactly that.
95///
96/// It also checks, in a debug build, that running the whole sequence a second time changes nothing.
97/// That is the property that makes a fixed sequence the right shape: a pass that keeps finding work
98/// on a plan it has already rewritten is a pass whose output depends on how many times it happened
99/// to run, and in a fixed sequence it runs once, so the plan that reaches the executor is whatever
100/// the first pass left behind. Each pass has its own test for this and the assertion is here anyway,
101/// because the pair that is not idempotent together is usually a pair that is idempotent apart.
102///
103/// # Errors
104///
105/// Whatever a pass reported, and then, in a debug build, if a pass left the plan malformed, narrowed
106/// what it returns or did not settle, all three of which are a bug in the pass and not in the query.
107pub fn optimize_with(plan: &mut Plan, context: &Context) -> Result<()> {
108 run(plan, context, &PASSES)
109}
110
111/// The sequence, over a list of passes the tests can choose.
112fn run(plan: &mut Plan, context: &Context, passes: &[&(dyn Pass + Sync)]) -> Result<()> {
113 let before = output_columns(plan, plan.root());
114 once(plan, context, passes)?;
115 if cfg!(debug_assertions) {
116 plan.validate()?;
117 let after = output_columns(plan, plan.root());
118 if after != before {
119 return Err(Error::internal(format!(
120 "a pass turned a query of {before} columns into one of {after}"
121 )));
122 }
123 let settled = plan.to_string();
124 once(plan, context, passes)?;
125 let again = plan.to_string();
126 if again != settled {
127 return Err(Error::internal(format!(
128 "the passes did not settle, since running them again gave a different plan\n\n{settled}\n{again}"
129 )));
130 }
131 }
132 Ok(())
133}
134
135/// One run of every pass that is turned on.
136fn once(plan: &mut Plan, context: &Context, passes: &[&(dyn Pass + Sync)]) -> Result<()> {
137 for pass in passes {
138 if context.is_disabled(pass.name()) {
139 continue;
140 }
141 pass.run(plan, context)?;
142 }
143 Ok(())
144}
145
146/// How many columns a node produces, which no pass is allowed to change at the root.
147///
148/// The count rather than the names and types, because the root of a plan the binder builds is a
149/// projection and what has to hold is that a pass did not add or drop one of its expressions. The
150/// recursion is over the operators that pass their input's width through, so its depth is the
151/// nesting the binder already walked to build the plan.
152fn output_columns(plan: &Plan, reference: NodeRef) -> usize {
153 match *plan.node(reference) {
154 Node::Get { columns, .. }
155 | Node::Values { columns, .. }
156 | Node::TableFunction { columns, .. } => plan.field_list(columns).len(),
157 Node::Project { exprs, .. } => plan.expr_list(exprs).len(),
158 Node::Aggregate { groups, aggregates, .. } => {
159 plan.expr_list(groups).len() + plan.expr_list(aggregates).len()
160 }
161 Node::Dummy => 0,
162 Node::Filter { input, .. }
163 | Node::Sort { input, .. }
164 | Node::Limit { input, .. }
165 | Node::TopN { input, .. }
166 | Node::Distinct { input, .. } => output_columns(plan, input),
167 // A set operation is as wide as either side, since the binder already required the two to
168 // agree. A join and a cross product are as wide as the two together.
169 Node::SetOp { left, .. } => output_columns(plan, left),
170 Node::Join { left, right, .. } | Node::CrossProduct { left, right } => {
171 output_columns(plan, left) + output_columns(plan, right)
172 }
173 }
174}
175
176#[cfg(test)]
177mod tests {
178 use super::*;
179
180 /// How wide the plan a text prints is, before anything has run over it.
181 fn width(text: &str) -> usize {
182 let plan =
183 Plan::parse(text).unwrap_or_else(|error| panic!("{text} did not parse: {error}"));
184 output_columns(&plan, plan.root())
185 }
186
187 /// Optimize the plan a text prints and hand back what it printed afterwards.
188 fn optimized(text: &str) -> String {
189 let mut plan =
190 Plan::parse(text).unwrap_or_else(|error| panic!("{text} did not parse: {error}"));
191 optimize(&mut plan).unwrap_or_else(|error| panic!("{text} did not optimize: {error}"));
192 plan.to_string()
193 }
194
195 #[test]
196 fn the_width_of_a_plan_is_the_width_of_whatever_produces_its_columns() {
197 assert_eq!(
198 width(
199 "Project #1 [#0.0::INTEGER AS a]\n Get memory.main.t AS t #0 [a::INTEGER, b::VARCHAR]\n"
200 ),
201 1
202 );
203 assert_eq!(width("Get memory.main.t AS t #0 [a::INTEGER, b::VARCHAR]\n"), 2);
204 assert_eq!(width("Dummy\n"), 0);
205 assert_eq!(
206 width(
207 "Aggregate #1 groups=[#0.0::INTEGER] aggregates=[count_star()::BIGINT]\n Get memory.main.t AS t #0 [a::INTEGER]\n"
208 ),
209 2
210 );
211 }
212
213 /// A `LIMIT` or a `SORT` is as wide as what is under it, which is the recursion this function
214 /// exists for and the part a single level check would get wrong.
215 #[test]
216 fn an_operator_that_passes_its_input_through_is_as_wide_as_its_input() {
217 assert_eq!(
218 width("Limit 1 offset 0\n Get memory.main.t AS t #0 [a::INTEGER, b::VARCHAR]\n"),
219 2
220 );
221 }
222
223 /// A join is both sides and a set operation is either one, since the binder already required
224 /// the two sides of a set operation to agree.
225 #[test]
226 fn a_join_is_both_sides_together_and_a_set_operation_is_one_of_them() {
227 assert_eq!(
228 width(
229 "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"
230 ),
231 3
232 );
233 assert_eq!(
234 width(
235 "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"
236 ),
237 1
238 );
239 }
240
241 /// The check is on the whole of `optimize` and not on one pass, so it keeps holding as passes
242 /// are added. This is the shape it runs over today.
243 #[test]
244 fn optimizing_keeps_a_query_as_wide_as_it_was() {
245 let before = "Project #1 [#0.1::VARCHAR AS b]\n Get memory.main.t AS t #0 [a::INTEGER, b::VARCHAR]\n";
246 let after = "Project #1 [#0.0::VARCHAR AS b]\n Get memory.main.t AS t #0 [b::VARCHAR]\n";
247 assert_eq!(optimized(before), after);
248 assert_eq!(width(before), width(after));
249 }
250
251 #[test]
252 fn no_two_passes_answer_to_the_same_name() {
253 // The name is the address, so two passes sharing one would make the toggle turn off
254 // whichever came first in the list and silently leave the other on.
255 let mut names: Vec<&str> = PASSES.iter().map(|pass| pass.name()).collect();
256 names.sort_unstable();
257 let held = names.len();
258 names.dedup();
259 assert_eq!(names.len(), held, "{names:?}");
260 }
261
262 #[test]
263 fn a_pass_that_is_turned_off_does_not_run() {
264 let text = "Project #1 [\"+\"(1::INTEGER, 1::INTEGER)::INTEGER AS n]\n Get memory.main.t AS t #0 [a::INTEGER]\n";
265 let mut plan = Plan::parse(text).expect("a well formed plan");
266 let context = Context::without("expression_rewriter").expect("a name that is a pass");
267 optimize_with(&mut plan, &context).expect("the other pass still runs");
268 assert_eq!(
269 plan.to_string(),
270 "Project #1 [\"+\"(1::INTEGER, 1::INTEGER)::INTEGER AS n]\n Get memory.main.t AS t #0 []\n"
271 );
272 }
273
274 /// A pass that finds the same work every time it looks, which is what the assertion is for.
275 #[derive(Debug)]
276 #[cfg(debug_assertions)]
277 struct Restless;
278
279 #[cfg(debug_assertions)]
280 impl Pass for Restless {
281 fn name(&self) -> &'static str {
282 "restless"
283 }
284
285 fn run(&self, plan: &mut Plan, _context: &Context) -> Result<()> {
286 let root = plan.root();
287 if !matches!(*plan.node(root), Node::Limit { .. }) {
288 return Ok(());
289 }
290 let stacked = plan.add_node(Node::Limit { input: root, count: Some(1), offset: 0 });
291 plan.set_root(stacked);
292 Ok(())
293 }
294 }
295
296 /// The settle check is a debug build check, so the test for it is a debug build test. Without
297 /// this the release profile job runs a test that asserts an error nothing was going to report,
298 /// which is what it had been doing since #196, because the per commit gate runs the tests once
299 /// and runs them in debug.
300 #[test]
301 #[cfg(debug_assertions)]
302 fn a_pass_that_never_settles_is_a_reported_error_and_not_a_plan() {
303 let text = "Limit 1 offset 0\n Get memory.main.t AS t #0 [a::INTEGER]\n";
304 let mut plan = Plan::parse(text).expect("a well formed plan");
305 let error = run(&mut plan, &Context::new(), &[&Restless]).expect_err("it never settles");
306 assert!(error.message().starts_with("the passes did not settle"), "{}", error.message());
307 }
308
309 /// Folding before pruning, which is the reason the order in [`PASSES`] is the order it is. The
310 /// column is read only by a branch that cannot be taken, so one pass has to remove the branch
311 /// before the other can see that nothing reads the column.
312 #[test]
313 fn folding_runs_first_so_that_pruning_sees_the_columns_it_freed() {
314 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";
315 assert_eq!(
316 optimized(text),
317 "Project #1 [#0.0::INTEGER AS n]\n Get memory.main.t AS t #0 [a::INTEGER]\n"
318 );
319 }
320}