1use std::str::FromStr;
16
17use crate::rule::{apply_rule_batch, AppliedRule, OptimizerRule};
18use crate::search::{RuleEvent, RuleOutcome};
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
21pub enum ApplyOrder {
22 Once,
23 TopDown,
24 BottomUp,
25 FixedPoint,
26}
27
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub struct OptimizationStage {
30 name: &'static str,
31 apply_order: ApplyOrder,
32}
33
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
35pub struct StageStats {
36 pub input_count: usize,
37 pub output_count: usize,
38 pub applied_rules: usize,
39 pub skipped_rules: usize,
40}
41
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub struct StageTrace {
44 name: String,
45 apply_order: ApplyOrder,
46 stats: StageStats,
47}
48
49#[derive(Debug, Clone, PartialEq, Eq)]
50pub struct StageRuleBatch<E> {
51 expressions: Vec<AppliedRule<E>>,
52 events: Vec<RuleEvent>,
53 trace: StageTrace,
54}
55
56pub struct RuleStage<'a, E> {
57 stage: OptimizationStage,
58 rules: Vec<&'a dyn OptimizerRule<E>>,
59}
60
61pub struct OptimizationPipeline<'a, E> {
62 stages: Vec<RuleStage<'a, E>>,
63}
64
65#[derive(Debug, Clone, PartialEq, Eq)]
66pub struct PipelineExecution<E> {
67 expression: E,
68 events: Vec<RuleEvent>,
69 traces: Vec<StageTrace>,
70}
71
72impl ApplyOrder {
73 pub fn all() -> &'static [Self] {
74 const ALL: &[ApplyOrder] = &[
75 ApplyOrder::Once,
76 ApplyOrder::TopDown,
77 ApplyOrder::BottomUp,
78 ApplyOrder::FixedPoint,
79 ];
80 ALL
81 }
82
83 pub fn as_str(self) -> &'static str {
84 match self {
85 ApplyOrder::Once => "once",
86 ApplyOrder::TopDown => "top_down",
87 ApplyOrder::BottomUp => "bottom_up",
88 ApplyOrder::FixedPoint => "fixed_point",
89 }
90 }
91}
92
93impl FromStr for ApplyOrder {
94 type Err = &'static str;
95
96 fn from_str(value: &str) -> Result<Self, Self::Err> {
97 Self::all()
98 .iter()
99 .copied()
100 .find(|order| order.as_str() == value)
101 .ok_or("unknown optimizer stage apply order")
102 }
103}
104
105impl OptimizationStage {
106 pub const fn new(name: &'static str, apply_order: ApplyOrder) -> Self {
107 Self { name, apply_order }
108 }
109
110 pub fn name(&self) -> &'static str {
111 self.name
112 }
113
114 pub fn apply_order(&self) -> ApplyOrder {
115 self.apply_order
116 }
117
118 pub fn trace(&self, stats: StageStats) -> StageTrace {
119 StageTrace {
120 name: self.name.to_string(),
121 apply_order: self.apply_order,
122 stats,
123 }
124 }
125
126 pub fn execute_rule_batch<E>(
127 &self,
128 expression: &E,
129 rules: &[&dyn OptimizerRule<E>],
130 ) -> StageRuleBatch<E> {
131 let batch = apply_rule_batch(expression, rules);
132 let (expressions, events) = batch.into_parts();
133 let applied_rules = events
134 .iter()
135 .filter(|event| event.outcome() == RuleOutcome::Applied)
136 .count();
137 let skipped_rules = events
138 .iter()
139 .filter(|event| event.outcome() == RuleOutcome::Skipped)
140 .count();
141 let stats =
142 StageStats::new(1, expressions.len()).with_rule_counts(applied_rules, skipped_rules);
143
144 StageRuleBatch {
145 expressions,
146 events,
147 trace: self.trace(stats),
148 }
149 }
150}
151
152impl StageStats {
153 pub const fn new(input_count: usize, output_count: usize) -> Self {
154 Self {
155 input_count,
156 output_count,
157 applied_rules: 0,
158 skipped_rules: 0,
159 }
160 }
161
162 pub const fn with_rule_counts(mut self, applied_rules: usize, skipped_rules: usize) -> Self {
163 self.applied_rules = applied_rules;
164 self.skipped_rules = skipped_rules;
165 self
166 }
167}
168
169impl StageTrace {
170 #[doc(hidden)]
172 pub fn retained_heap_bytes(&self) -> Option<usize> {
173 let Self {
174 name,
175 apply_order,
176 stats,
177 } = self;
178 fn leaf<T: Copy>(_: &T) {}
179 leaf(apply_order);
180 leaf(stats);
181 Some(name.capacity())
182 }
183
184 pub fn name(&self) -> &str {
185 &self.name
186 }
187
188 pub fn apply_order(&self) -> ApplyOrder {
189 self.apply_order
190 }
191
192 pub fn stats(&self) -> StageStats {
193 self.stats
194 }
195}
196
197impl<E> StageRuleBatch<E> {
198 pub fn expressions(&self) -> &[AppliedRule<E>] {
199 &self.expressions
200 }
201
202 pub fn events(&self) -> &[RuleEvent] {
203 &self.events
204 }
205
206 pub fn trace(&self) -> &StageTrace {
207 &self.trace
208 }
209
210 pub fn into_parts(self) -> (Vec<AppliedRule<E>>, Vec<RuleEvent>, StageTrace) {
211 (self.expressions, self.events, self.trace)
212 }
213}
214
215impl<'a, E> RuleStage<'a, E> {
216 pub fn new(stage: OptimizationStage, rules: Vec<&'a dyn OptimizerRule<E>>) -> Self {
217 Self { stage, rules }
218 }
219
220 pub fn stage(&self) -> &OptimizationStage {
221 &self.stage
222 }
223
224 pub fn rules(&self) -> &[&'a dyn OptimizerRule<E>] {
225 &self.rules
226 }
227}
228
229impl<'a, E> OptimizationPipeline<'a, E> {
230 pub fn new(stages: Vec<RuleStage<'a, E>>) -> Self {
231 Self { stages }
232 }
233
234 pub fn stages(&self) -> &[RuleStage<'a, E>] {
235 &self.stages
236 }
237}
238
239impl<E: Clone> OptimizationPipeline<'_, E> {
240 pub fn execute(&self, expression: E) -> PipelineExecution<E> {
241 let mut expression = expression;
242 let mut events = Vec::new();
243 let mut traces = Vec::new();
244
245 for stage in &self.stages {
246 let batch = stage.stage.execute_rule_batch(&expression, &stage.rules);
247 let (expressions, stage_events, trace) = batch.into_parts();
248 events.extend(stage_events);
249 traces.push(trace);
250 if let Some(applied) = expressions.into_iter().next() {
251 expression = applied.into_application().into_expression();
252 }
253 }
254
255 PipelineExecution {
256 expression,
257 events,
258 traces,
259 }
260 }
261}
262
263impl<E> PipelineExecution<E> {
264 pub fn expression(&self) -> &E {
265 &self.expression
266 }
267
268 pub fn into_expression(self) -> E {
269 self.expression
270 }
271
272 pub fn events(&self) -> &[RuleEvent] {
273 &self.events
274 }
275
276 pub fn traces(&self) -> &[StageTrace] {
277 &self.traces
278 }
279
280 pub fn into_parts(self) -> (E, Vec<RuleEvent>, Vec<StageTrace>) {
281 (self.expression, self.events, self.traces)
282 }
283}
284
285#[cfg(test)]
286mod tests {
287 use super::{ApplyOrder, OptimizationPipeline, OptimizationStage, RuleStage, StageStats};
288 use crate::{OptimizerRule, RuleApplication, RuleId, RuleKind, RuleOutcome, RulePromise};
289
290 #[derive(Debug, Clone, PartialEq, Eq)]
291 struct TestExpr(&'static str);
292
293 struct RenameRule {
294 id: RuleId,
295 priority: u16,
296 input: &'static str,
297 output: Option<&'static str>,
298 }
299
300 impl OptimizerRule<TestExpr> for RenameRule {
301 fn id(&self) -> RuleId {
302 self.id
303 }
304
305 fn promise(&self, expression: &TestExpr) -> RulePromise {
306 if expression.0 == self.input {
307 RulePromise::new(self.priority)
308 } else {
309 RulePromise::NEVER
310 }
311 }
312
313 fn apply(&self, _expression: &TestExpr) -> Option<RuleApplication<TestExpr>> {
314 self.output
315 .map(|output| RuleApplication::new(TestExpr(output), format!("to={output}")))
316 }
317 }
318
319 #[test]
320 fn apply_order_strings_round_trip() {
321 for order in ApplyOrder::all() {
322 assert_eq!(order.as_str().parse::<ApplyOrder>(), Ok(*order));
323 }
324 assert!("sideways".parse::<ApplyOrder>().is_err());
325 }
326
327 #[test]
328 fn stage_trace_records_stable_stage_metadata() {
329 let stage = OptimizationStage::new("predicate_pushdown", ApplyOrder::BottomUp);
330 let trace = stage.trace(StageStats::new(3, 2).with_rule_counts(1, 4));
331
332 assert_eq!(trace.name(), "predicate_pushdown");
333 assert_eq!(trace.apply_order(), ApplyOrder::BottomUp);
334 assert_eq!(trace.stats().input_count, 3);
335 assert_eq!(trace.stats().output_count, 2);
336 assert_eq!(trace.stats().applied_rules, 1);
337 assert_eq!(trace.stats().skipped_rules, 4);
338 }
339
340 #[test]
341 fn stage_executes_rules_and_records_structured_trace() {
342 let stage = OptimizationStage::new("access_path_selection", ApplyOrder::BottomUp);
343 let high = RenameRule {
344 id: RuleId::new("node_equality_index_seek", RuleKind::Implementation),
345 priority: 100,
346 input: "filter",
347 output: Some("seek"),
348 };
349 let skipped = RenameRule {
350 id: RuleId::new("node_text_index_seek", RuleKind::Implementation),
351 priority: 10,
352 input: "filter",
353 output: None,
354 };
355
356 let batch = stage.execute_rule_batch(&TestExpr("filter"), &[&skipped, &high]);
357
358 assert_eq!(batch.expressions().len(), 1);
359 assert_eq!(
360 batch.expressions()[0].id().stable_name(),
361 "implementation:node_equality_index_seek"
362 );
363 assert_eq!(batch.events().len(), 2);
364 assert_eq!(batch.events()[0].outcome(), RuleOutcome::Applied);
365 assert_eq!(batch.events()[1].outcome(), RuleOutcome::Skipped);
366 assert_eq!(batch.trace().name(), "access_path_selection");
367 assert_eq!(batch.trace().stats().input_count, 1);
368 assert_eq!(batch.trace().stats().output_count, 1);
369 assert_eq!(batch.trace().stats().applied_rules, 1);
370 assert_eq!(batch.trace().stats().skipped_rules, 1);
371 }
372
373 #[test]
374 fn pipeline_executes_named_stages_in_order() {
375 let scan_to_filter = RenameRule {
376 id: RuleId::new("scan_to_filter", RuleKind::Transformation),
377 priority: 50,
378 input: "scan",
379 output: Some("filter"),
380 };
381 let filter_to_seek = RenameRule {
382 id: RuleId::new("filter_to_seek", RuleKind::Implementation),
383 priority: 100,
384 input: "filter",
385 output: Some("seek"),
386 };
387 let pipeline = OptimizationPipeline::new(vec![
388 RuleStage::new(
389 OptimizationStage::new("logical_rewrite", ApplyOrder::TopDown),
390 vec![&scan_to_filter],
391 ),
392 RuleStage::new(
393 OptimizationStage::new("access_path_selection", ApplyOrder::BottomUp),
394 vec![&filter_to_seek],
395 ),
396 ]);
397
398 let execution = pipeline.execute(TestExpr("scan"));
399
400 assert_eq!(execution.expression(), &TestExpr("seek"));
401 assert_eq!(execution.events().len(), 2);
402 assert_eq!(execution.traces().len(), 2);
403 assert_eq!(execution.traces()[0].name(), "logical_rewrite");
404 assert_eq!(execution.traces()[1].name(), "access_path_selection");
405 assert_eq!(execution.traces()[0].stats().applied_rules, 1);
406 assert_eq!(execution.traces()[1].stats().applied_rules, 1);
407 }
408}