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