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