Skip to main content

datafusion_optimizer/
optimizer.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! [`Optimizer`] and [`OptimizerRule`]
6
7use std::fmt::Debug;
8use std::sync::Arc;
9
10use chrono::{DateTime, Utc};
11use datafusion_expr::registry::FunctionRegistry;
12use datafusion_expr::{InvariantLevel, assert_expected_schema};
13use log::{debug, warn};
14
15use datafusion_common::alias::AliasGenerator;
16use datafusion_common::config::ConfigOptions;
17use datafusion_common::instant::Instant;
18use datafusion_common::tree_node::{
19    Transformed, TreeNode, TreeNodeRecursion, TreeNodeRewriter,
20};
21use datafusion_common::{DFSchema, DataFusionError, HashSet, Result, internal_err};
22use datafusion_expr::dml::CopyTo;
23use datafusion_expr::logical_plan::LogicalPlan;
24use datafusion_expr::{
25    Aggregate, Analyze, CreateMemoryTable, CreateView, DdlStatement, Distinct,
26    DistinctOn, DmlStatement, Explain, Expr, Extension, Filter, Join, Limit,
27    MaterializedCte, MaterializedCtePlan, Projection, RecursiveQuery, Repartition, Sort,
28    Statement, Subquery, SubqueryAlias, Union, Unnest, Window,
29};
30
31use crate::common_subexpr_eliminate::CommonSubexprEliminate;
32use crate::decorrelate_lateral_join::DecorrelateLateralJoin;
33use crate::decorrelate_predicate_subquery::DecorrelatePredicateSubquery;
34use crate::eliminate_aggregate_distinct::EliminateAggregateDistinct;
35use crate::eliminate_cross_join::EliminateCrossJoin;
36use crate::eliminate_duplicated_expr::EliminateDuplicatedExpr;
37use crate::eliminate_filter::EliminateFilter;
38use crate::eliminate_group_by_constant::EliminateGroupByConstant;
39use crate::eliminate_join::EliminateJoin;
40use crate::eliminate_limit::EliminateLimit;
41use crate::eliminate_outer_join::EliminateOuterJoin;
42use crate::extract_equijoin_predicate::ExtractEquijoinPredicate;
43use crate::extract_leaf_expressions::{ExtractLeafExpressions, PushDownLeafProjections};
44use crate::filter_null_join_keys::FilterNullJoinKeys;
45use crate::optimize_projections::OptimizeProjections;
46use crate::optimize_unions::OptimizeUnions;
47use crate::plan_signature::LogicalPlanSignature;
48use crate::propagate_empty_relation::PropagateEmptyRelation;
49use crate::push_down_filter::PushDownFilter;
50use crate::push_down_limit::PushDownLimit;
51use crate::replace_distinct_aggregate::ReplaceDistinctWithAggregate;
52use crate::rewrite_set_comparison::RewriteSetComparison;
53use crate::scalar_subquery_to_join::ScalarSubqueryToJoin;
54use crate::simplify_expressions::SimplifyExpressions;
55use crate::single_distinct_to_groupby::SingleDistinctToGroupBy;
56use crate::unions_to_filter::UnionsToFilter;
57use crate::utils::log_plan;
58
59/// Transforms one [`LogicalPlan`] into another which computes the same results,
60/// but in a potentially more efficient way.
61///
62/// See notes on [`Self::rewrite`] for details on how to implement an `OptimizerRule`.
63///
64/// To change the semantics of a `LogicalPlan`, see [`AnalyzerRule`].
65///
66/// Use [`SessionState::add_optimizer_rule`] to register additional
67/// `OptimizerRule`s.
68///
69/// [`AnalyzerRule`]: crate::analyzer::AnalyzerRule
70/// [`SessionState::add_optimizer_rule`]: https://docs.rs/datafusion/latest/datafusion/execution/session_state/struct.SessionState.html#method.add_optimizer_rule
71pub trait OptimizerRule: Debug {
72    /// A human readable name for this optimizer rule
73    fn name(&self) -> &str;
74
75    /// How should the rule be applied by the optimizer? See comments on
76    /// [`ApplyOrder`] for details.
77    ///
78    /// If returns `None`, the default, the rule must handle recursion itself
79    fn apply_order(&self) -> Option<ApplyOrder> {
80        None
81    }
82
83    /// Try to rewrite `plan` to an optimized form, returning [`Transformed::yes`]
84    /// if the plan was rewritten and [`Transformed::no`] if it was not.
85    ///
86    /// # Notes for implementations:
87    ///
88    /// ## Return the same plan if no changes were made
89    ///
90    /// If there are no suitable transformations for the input plan,
91    /// the optimizer should simply return it unmodified.
92    ///
93    /// The optimizer will call `rewrite` several times until a fixed point is
94    /// reached, so it is important that `rewrite` return [`Transformed::no`] if
95    /// the output is the same.
96    ///
97    /// ## Matching on functions
98    ///
99    /// The rule should avoid function-specific transformations, and instead use
100    /// methods on [`ScalarUDFImpl`] and [`AggregateUDFImpl`]. Specifically, the
101    /// rule should not check function names as functions can be overridden, and
102    /// may not have the same semantics as the functions provided with
103    /// DataFusion.
104    ///
105    /// For example, if a rule rewrites a function based on the check
106    /// `func.name() == "sum"`, it may rewrite the plan incorrectly if the
107    /// registered `sum` function has different semantics (for example, the
108    /// `sum` function from the `datafusion-spark` crate).
109    ///
110    /// There are still several cases that rely on function name checking in
111    /// the rules included with DataFusion. Please see [#18643] for more details
112    /// and to help remove these cases.
113    ///
114    /// [`ScalarUDFImpl`]: datafusion_expr::ScalarUDFImpl
115    /// [`AggregateUDFImpl`]: datafusion_expr::ScalarUDFImpl
116    /// [#18643]: https://github.com/apache/datafusion/issues/18643
117    fn rewrite(
118        &self,
119        _plan: LogicalPlan,
120        _config: &dyn OptimizerConfig,
121    ) -> Result<Transformed<LogicalPlan>, DataFusionError> {
122        internal_err!("rewrite is not implemented for {}", self.name())
123    }
124}
125
126/// Options to control the DataFusion Optimizer.
127pub trait OptimizerConfig {
128    /// Return the time at which the query execution started. This
129    /// time is used as the value for `now()`. If `None`, time-dependent
130    /// functions like `now()` will not be simplified during optimization.
131    fn query_execution_start_time(&self) -> Option<DateTime<Utc>>;
132
133    /// Return alias generator used to generate unique aliases for subqueries
134    fn alias_generator(&self) -> &Arc<AliasGenerator>;
135
136    fn options(&self) -> Arc<ConfigOptions>;
137
138    fn function_registry(&self) -> Option<&dyn FunctionRegistry> {
139        None
140    }
141}
142
143/// A standalone [`OptimizerConfig`] that can be used independently
144/// of DataFusion's config management
145#[derive(Debug)]
146pub struct OptimizerContext {
147    /// Query execution start time that can be used to rewrite
148    /// expressions such as `now()` to use a literal value instead.
149    /// If `None`, time-dependent functions will not be simplified.
150    query_execution_start_time: Option<DateTime<Utc>>,
151
152    /// Alias generator used to generate unique aliases for subqueries
153    alias_generator: Arc<AliasGenerator>,
154
155    options: Arc<ConfigOptions>,
156}
157
158impl OptimizerContext {
159    /// Create optimizer config
160    pub fn new() -> Self {
161        let mut options = ConfigOptions::default();
162        options.optimizer.filter_null_join_keys = true;
163
164        Self::new_with_config_options(Arc::new(options))
165    }
166
167    /// Create a optimizer config with provided [ConfigOptions].
168    pub fn new_with_config_options(options: Arc<ConfigOptions>) -> Self {
169        Self {
170            query_execution_start_time: Some(Utc::now()),
171            alias_generator: Arc::new(AliasGenerator::new()),
172            options,
173        }
174    }
175
176    /// Specify whether to enable the filter_null_keys rule
177    pub fn filter_null_keys(mut self, filter_null_keys: bool) -> Self {
178        Arc::make_mut(&mut self.options)
179            .optimizer
180            .filter_null_join_keys = filter_null_keys;
181        self
182    }
183
184    /// Set the query execution start time
185    pub fn with_query_execution_start_time(
186        mut self,
187        query_execution_start_time: DateTime<Utc>,
188    ) -> Self {
189        self.query_execution_start_time = Some(query_execution_start_time);
190        self
191    }
192
193    /// Clear the query execution start time. When `None`, time-dependent
194    /// functions like `now()` will not be simplified during optimization.
195    pub fn without_query_execution_start_time(mut self) -> Self {
196        self.query_execution_start_time = None;
197        self
198    }
199
200    /// Specify whether the optimizer should skip rules that produce
201    /// errors, or fail the query
202    pub fn with_skip_failing_rules(mut self, b: bool) -> Self {
203        Arc::make_mut(&mut self.options).optimizer.skip_failed_rules = b;
204        self
205    }
206
207    /// Specify how many times to attempt to optimize the plan
208    pub fn with_max_passes(mut self, v: u8) -> Self {
209        Arc::make_mut(&mut self.options).optimizer.max_passes = v as usize;
210        self
211    }
212}
213
214impl Default for OptimizerContext {
215    /// Create optimizer config
216    fn default() -> Self {
217        Self::new()
218    }
219}
220
221impl OptimizerConfig for OptimizerContext {
222    fn query_execution_start_time(&self) -> Option<DateTime<Utc>> {
223        self.query_execution_start_time
224    }
225
226    fn alias_generator(&self) -> &Arc<AliasGenerator> {
227        &self.alias_generator
228    }
229
230    fn options(&self) -> Arc<ConfigOptions> {
231        Arc::clone(&self.options)
232    }
233}
234
235/// A rule-based logical optimizer.
236///
237/// Applies rules in order for up to `datafusion.optimizer.max_passes` passes,
238/// stopping early if the plan repeats.
239#[derive(Clone, Debug)]
240pub struct Optimizer {
241    /// All optimizer rules to apply
242    pub rules: Vec<Arc<dyn OptimizerRule + Send + Sync>>,
243}
244
245/// Specifies how recursion for an `OptimizerRule` should be handled.
246///
247/// * `Some(apply_order)`: The Optimizer will recursively apply the rule to the plan.
248/// * `None`: the rule must handle any required recursion itself.
249#[derive(Debug, Clone, Copy, PartialEq)]
250pub enum ApplyOrder {
251    /// Apply the rule to the node before its inputs
252    TopDown,
253    /// Apply the rule to the node after its inputs
254    BottomUp,
255}
256
257impl Default for Optimizer {
258    fn default() -> Self {
259        Self::new()
260    }
261}
262
263impl Optimizer {
264    /// Create a new optimizer using the recommended list of rules
265    pub fn new() -> Self {
266        // NOTEs:
267        // - The order of rules in this list is important, as it determines the
268        //   order in which they are applied.
269        // - Adding a new rule here is expensive as it will be applied to all
270        //   queries, and will likely increase the optimization time. Please extend
271        //   existing rules when possible, rather than adding a new rule.
272        //   If you do add a new rule considering having aggressive no-op paths
273        //   (e.g. if the plan doesn't contain any of the nodes you are looking for
274        //    return `Transformed::no`; only works if you control the traversal).
275        let rules: Vec<Arc<dyn OptimizerRule + Sync + Send>> = vec![
276            Arc::new(RewriteSetComparison::new()),
277            Arc::new(OptimizeUnions::new()),
278            Arc::new(UnionsToFilter::new()),
279            Arc::new(SimplifyExpressions::new()),
280            Arc::new(ReplaceDistinctWithAggregate::new()),
281            Arc::new(EliminateJoin::new()),
282            Arc::new(DecorrelatePredicateSubquery::new()),
283            Arc::new(ScalarSubqueryToJoin::new()),
284            Arc::new(DecorrelateLateralJoin::new()),
285            Arc::new(ExtractEquijoinPredicate::new()),
286            Arc::new(EliminateDuplicatedExpr::new()),
287            Arc::new(EliminateFilter::new()),
288            Arc::new(EliminateCrossJoin::new()),
289            Arc::new(EliminateLimit::new()),
290            Arc::new(PropagateEmptyRelation::new()),
291            Arc::new(FilterNullJoinKeys::default()),
292            Arc::new(EliminateOuterJoin::new()),
293            // Filters can't be pushed down past Limits, we should do PushDownFilter after PushDownLimit
294            Arc::new(PushDownLimit::new()),
295            Arc::new(PushDownFilter::new()),
296            Arc::new(EliminateAggregateDistinct::new()),
297            Arc::new(SingleDistinctToGroupBy::new()),
298            // The previous optimizations added expressions and projections,
299            // that might benefit from the following rules
300            Arc::new(EliminateGroupByConstant::new()),
301            Arc::new(CommonSubexprEliminate::new()),
302            Arc::new(ExtractLeafExpressions::new()),
303            Arc::new(PushDownLeafProjections::new()),
304            Arc::new(OptimizeProjections::new()),
305        ];
306
307        Self::with_rules(rules)
308    }
309
310    /// Create a new optimizer with the given rules
311    pub fn with_rules(rules: Vec<Arc<dyn OptimizerRule + Send + Sync>>) -> Self {
312        Self { rules }
313    }
314}
315
316/// Recursively rewrites LogicalPlans
317struct Rewriter<'a> {
318    apply_order: ApplyOrder,
319    rule: &'a dyn OptimizerRule,
320    config: &'a dyn OptimizerConfig,
321}
322
323impl<'a> Rewriter<'a> {
324    fn new(
325        apply_order: ApplyOrder,
326        rule: &'a dyn OptimizerRule,
327        config: &'a dyn OptimizerConfig,
328    ) -> Self {
329        Self {
330            apply_order,
331            rule,
332            config,
333        }
334    }
335}
336
337impl TreeNodeRewriter for Rewriter<'_> {
338    type Node = LogicalPlan;
339
340    fn f_down(&mut self, node: LogicalPlan) -> Result<Transformed<LogicalPlan>> {
341        if self.apply_order == ApplyOrder::TopDown {
342            self.rule.rewrite(node, self.config)
343        } else {
344            Ok(Transformed::no(node))
345        }
346    }
347
348    fn f_up(&mut self, node: LogicalPlan) -> Result<Transformed<LogicalPlan>> {
349        if self.apply_order == ApplyOrder::BottomUp {
350            self.rule.rewrite(node, self.config)
351        } else {
352            Ok(Transformed::no(node))
353        }
354    }
355}
356
357/// Applies `f` to each child (input) of `plan` in place, using
358/// [`Arc::make_mut`] for copy-on-write semantics on `Arc<LogicalPlan>`
359/// children. When the `Arc` refcount is 1 (the common case here)
360/// `Arc::make_mut` hands out a `&mut` without cloning; when it is >1 the
361/// inner value is cloned first.
362///
363/// Returns `Ok(true)` if any child was modified by `f`.
364///
365/// This is deliberately private to the optimizer rather than a method on
366/// [`LogicalPlan`]: it is an implementation detail of in-place rewriting, and
367/// the `Arc::make_mut` approach does not generalize to the other tree types
368/// (`Expr` children are `Box`ed; `PhysicalExpr`/`ExecutionPlan` children are
369/// `Arc<dyn _>`, which `Arc::make_mut` cannot handle). If `TreeNode` ever
370/// grows an in-place traversal this logic can move there.
371///
372/// # Error semantics
373///
374/// If `f` returns `Err` for a child, that error is returned immediately;
375/// children visited earlier keep whatever modifications `f` already applied
376/// to them — they are **not** rolled back.
377fn map_children_mut<F: FnMut(&mut LogicalPlan) -> Result<bool>>(
378    plan: &mut LogicalPlan,
379    mut f: F,
380) -> Result<bool> {
381    Ok(match plan {
382        LogicalPlan::Projection(Projection { input, .. })
383        | LogicalPlan::Filter(Filter { input, .. })
384        | LogicalPlan::Repartition(Repartition { input, .. })
385        | LogicalPlan::Window(Window { input, .. })
386        | LogicalPlan::Aggregate(Aggregate { input, .. })
387        | LogicalPlan::Sort(Sort { input, .. })
388        | LogicalPlan::Limit(Limit { input, .. })
389        | LogicalPlan::SubqueryAlias(SubqueryAlias { input, .. })
390        | LogicalPlan::Analyze(Analyze { input, .. })
391        | LogicalPlan::Dml(DmlStatement { input, .. })
392        | LogicalPlan::Copy(CopyTo { input, .. })
393        | LogicalPlan::Unnest(Unnest { input, .. }) => f(Arc::make_mut(input))?,
394        LogicalPlan::Subquery(Subquery { subquery, .. }) => f(Arc::make_mut(subquery))?,
395        LogicalPlan::Join(Join { left, right, .. }) => {
396            let l = f(Arc::make_mut(left))?;
397            let r = f(Arc::make_mut(right))?;
398            l || r
399        }
400        LogicalPlan::AsOfJoin(join) => {
401            let l = f(Arc::make_mut(&mut join.left))?;
402            let r = f(Arc::make_mut(&mut join.right))?;
403            l || r
404        }
405        LogicalPlan::Union(Union { inputs, .. }) => {
406            let mut changed = false;
407            for input in inputs {
408                changed |= f(Arc::make_mut(input))?;
409            }
410            changed
411        }
412        LogicalPlan::Distinct(Distinct::All(input)) => f(Arc::make_mut(input))?,
413        LogicalPlan::Distinct(Distinct::On(DistinctOn { input, .. })) => {
414            f(Arc::make_mut(input))?
415        }
416        LogicalPlan::Explain(Explain { plan, .. }) => f(Arc::make_mut(plan))?,
417        LogicalPlan::Ddl(DdlStatement::CreateMemoryTable(CreateMemoryTable {
418            input,
419            ..
420        }))
421        | LogicalPlan::Ddl(DdlStatement::CreateView(CreateView { input, .. })) => {
422            f(Arc::make_mut(input))?
423        }
424        LogicalPlan::RecursiveQuery(RecursiveQuery {
425            static_term,
426            recursive_term,
427            ..
428        }) => {
429            let s = f(Arc::make_mut(static_term))?;
430            let r = f(Arc::make_mut(recursive_term))?;
431            s || r
432        }
433        LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(MaterializedCte {
434            cte,
435            continuation,
436            ..
437        })) => {
438            let b = f(Arc::make_mut(cte))?;
439            let c = f(Arc::make_mut(continuation))?;
440            b || c
441        }
442        LogicalPlan::Statement(Statement::Prepare(p)) => f(Arc::make_mut(&mut p.input))?,
443        LogicalPlan::Extension(Extension { node }) => {
444            let inputs = node.inputs();
445            if inputs.is_empty() {
446                false
447            } else {
448                // Extension nodes don't expose mutable children,
449                // fall back to the ownership-based API
450                let mut changed = false;
451                let exprs = node.expressions();
452                let new_inputs: Vec<LogicalPlan> = inputs
453                    .into_iter()
454                    .map(|input| {
455                        let mut plan = input.clone();
456                        if f(&mut plan)? {
457                            changed = true;
458                        }
459                        Ok(plan)
460                    })
461                    .collect::<Result<Vec<_>>>()?;
462                *node = node.with_exprs_and_inputs(exprs, new_inputs)?;
463                changed
464            }
465        }
466        // plans without inputs
467        LogicalPlan::TableScan { .. }
468        | LogicalPlan::EmptyRelation { .. }
469        | LogicalPlan::Values { .. }
470        | LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(_))
471        | LogicalPlan::Show(_)
472        | LogicalPlan::Ddl(DdlStatement::CreateExternalTable(_))
473        | LogicalPlan::Ddl(DdlStatement::CreateCatalogSchema(_))
474        | LogicalPlan::Ddl(DdlStatement::CreateCatalog(_))
475        | LogicalPlan::Ddl(DdlStatement::CreateExternalCatalog(_))
476        | LogicalPlan::Ddl(DdlStatement::CreateIndex(_))
477        | LogicalPlan::Ddl(DdlStatement::DropTable(_))
478        | LogicalPlan::Ddl(DdlStatement::DropView(_))
479        | LogicalPlan::Ddl(DdlStatement::DropCatalogSchema(_))
480        | LogicalPlan::Ddl(DdlStatement::DropCatalog(_))
481        | LogicalPlan::Ddl(DdlStatement::CreateFunction(_))
482        | LogicalPlan::Ddl(DdlStatement::DropFunction(_))
483        | LogicalPlan::Statement(_) => false,
484    })
485}
486
487/// Rewrites a plan tree in place using `Arc::make_mut` for
488/// copy-on-write semantics on `Arc<LogicalPlan>` children.
489///
490/// This avoids the `Arc::unwrap_or_clone` + `Arc::new` cycle that the
491/// ownership-based `TreeNode::rewrite` performs at every child node.
492///
493/// # Error semantics
494///
495/// On `Err`, `*plan` is left in an **unspecified** state and must not be used.
496/// Note this is different than consuming APIs such as [`TreeNode::rewrite`]
497/// where the original plan is freed and no longer available on error
498#[cfg_attr(feature = "recursive_protection", recursive::recursive)]
499fn rewrite_plan_in_place(
500    plan: &mut LogicalPlan,
501    apply_order: ApplyOrder,
502    rule: &dyn OptimizerRule,
503    config: &dyn OptimizerConfig,
504) -> Result<bool> {
505    // f_down phase
506    let mut changed = false;
507    if apply_order == ApplyOrder::TopDown {
508        // `rule.rewrite()` takes the plan by value, so bridge the `&mut` to an
509        // owned value with `std::mem::take`. `LogicalPlan::default()` is a cheap
510        // empty placeholder (shared empty schema, no allocation) and is
511        // overwritten with the rule's output on the next line.
512        let owned = std::mem::take(plan);
513        let result = rule.rewrite(owned, config)?;
514        *plan = result.data;
515        changed |= result.transformed;
516        // Respect TreeNodeRecursion::Stop/Jump from the rule
517        if result.tnr == TreeNodeRecursion::Stop {
518            return Ok(changed);
519        }
520    }
521
522    let mut child_schema_changed = false;
523    let children_changed = map_children_mut(plan, |child| {
524        let old_schema = Arc::clone(child.schema());
525        let child_changed = rewrite_plan_in_place(child, apply_order, rule, config)?;
526        if child_changed && old_schema.as_ref() != child.schema().as_ref() {
527            child_schema_changed = true;
528        }
529        Ok(child_changed)
530    })?;
531    changed |= children_changed;
532
533    if child_schema_changed {
534        // Child rewrites can change their output schemas. Recompute the current
535        // node before later rules use positional requirements from that schema.
536        let owned = std::mem::take(plan);
537        *plan = owned.recompute_schema()?;
538    }
539
540    // f_up phase
541    if apply_order == ApplyOrder::BottomUp {
542        let owned = std::mem::take(plan);
543        let result = rule.rewrite(owned, config)?;
544        *plan = result.data;
545        changed |= result.transformed;
546    }
547
548    Ok(changed)
549}
550
551/// Returns true if the plan contains any subquery expressions
552/// (EXISTS, IN subquery, scalar subquery, set comparison).
553///
554/// Used to determine whether the more expensive `rewrite_with_subqueries`
555/// traversal is needed. When the plan has no subqueries, the cheaper
556/// `rewrite` traversal is sufficient since all plan nodes are reachable
557/// via direct children.
558fn plan_has_subqueries(plan: &LogicalPlan) -> bool {
559    let mut found = false;
560    let _ = plan.apply(|node| {
561        if found {
562            return Ok(TreeNodeRecursion::Stop);
563        }
564        node.apply_expressions(|expr| {
565            if found {
566                return Ok(TreeNodeRecursion::Stop);
567            }
568            expr.apply(|e| {
569                if matches!(
570                    e,
571                    Expr::Exists(_)
572                        | Expr::InSubquery(_)
573                        | Expr::SetComparison(_)
574                        | Expr::ScalarSubquery(_)
575                ) {
576                    found = true;
577                    Ok(TreeNodeRecursion::Stop)
578                } else {
579                    Ok(TreeNodeRecursion::Continue)
580                }
581            })
582        })?;
583        Ok(if found {
584            TreeNodeRecursion::Stop
585        } else {
586            TreeNodeRecursion::Continue
587        })
588    });
589    found
590}
591
592impl Optimizer {
593    /// Optimizes the logical plan by applying optimizer rules, and
594    /// invoking observer function after each call
595    pub fn optimize<F>(
596        &self,
597        plan: LogicalPlan,
598        config: &dyn OptimizerConfig,
599        mut observer: F,
600    ) -> Result<LogicalPlan>
601    where
602        F: FnMut(&LogicalPlan, &dyn OptimizerRule),
603    {
604        // verify LP is valid, before the first LP optimizer pass.
605        plan.check_invariants(InvariantLevel::Executable)
606            .map_err(|e| e.context("Invalid input plan before LP Optimizers"))?;
607
608        let start_time = Instant::now();
609        let options = config.options();
610        let mut new_plan = plan;
611
612        let mut previous_plans = HashSet::with_capacity(16);
613        previous_plans.insert(LogicalPlanSignature::new(&new_plan));
614
615        let starting_schema = Arc::clone(new_plan.schema());
616
617        let mut i = 0;
618        while i < options.optimizer.max_passes {
619            log_plan(&format!("Optimizer input (pass {i})"), &new_plan);
620
621            // Track subquery presence across the pass. Refresh after changed
622            // rules so decorrelation can move later rules onto the in-place
623            // path; that path refreshes parent schemas after child schemas
624            // change.
625            let mut has_subqueries = plan_has_subqueries(&new_plan);
626
627            for rule in &self.rules {
628                // If skipping failed rules, copy plan before attempting to rewrite
629                // as rewriting is destructive
630                let prev_plan = options
631                    .optimizer
632                    .skip_failed_rules
633                    .then(|| new_plan.clone());
634
635                let starting_schema = Arc::clone(new_plan.schema());
636
637                let result = match rule.apply_order() {
638                    // optimizer handles recursion
639                    Some(apply_order) => {
640                        if has_subqueries {
641                            // Plans with subqueries need the full
642                            // rewrite_with_subqueries traversal to
643                            // recurse into subquery plans.
644                            new_plan.rewrite_with_subqueries(
645                                &mut Rewriter::new(
646                                    apply_order,
647                                    rule.as_ref(),
648                                    config,
649                                ),
650                            )
651                        } else {
652                            // No subqueries: use in-place rewriting
653                            // with Arc::make_mut for zero-cost CoW on
654                            // children, avoiding Arc unwrap/rewrap.
655                            //
656                            // On error `new_plan` is left in an unspecified
657                            // state (see `rewrite_plan_in_place`); the result
658                            // handling below discards it, restoring `prev_plan`
659                            // when `skip_failed_rules` is set or propagating
660                            // the error otherwise.
661                            rewrite_plan_in_place(
662                                &mut new_plan,
663                                apply_order,
664                                rule.as_ref(),
665                                config,
666                            )
667                            .map(|transformed| {
668                                Transformed::new_transformed(
669                                    std::mem::take(&mut new_plan),
670                                    transformed,
671                                )
672                            })
673                        }
674                    }
675                    // rule handles recursion itself
676                    None => {
677                        rule.rewrite(new_plan, config)
678                    },
679                }
680                .and_then(|tnr| {
681                    // run checks optimizer invariant checks, per optimizer rule applied
682                    assert_valid_optimization(&tnr.data, &starting_schema)
683                        .map_err(|e| e.context(format!("Check optimizer-specific invariants after optimizer rule: {}", rule.name())))?;
684
685                    // run LP invariant checks only in debug mode for performance reasons
686                    #[cfg(debug_assertions)]
687                    tnr.data.check_invariants(InvariantLevel::Executable)
688                        .map_err(|e| e.context(format!("Invalid (non-executable) plan after Optimizer rule: {}", rule.name())))?;
689
690                    Ok(tnr)
691                });
692
693                // Handle results
694                match (result, prev_plan) {
695                    // OptimizerRule was successful
696                    (
697                        Ok(Transformed {
698                            data, transformed, ..
699                        }),
700                        _,
701                    ) => {
702                        new_plan = data;
703                        observer(&new_plan, rule.as_ref());
704                        if transformed {
705                            has_subqueries = plan_has_subqueries(&new_plan);
706                            log_plan(rule.name(), &new_plan);
707                        } else {
708                            debug!(
709                                "Plan unchanged by optimizer rule '{}' (pass {})",
710                                rule.name(),
711                                i
712                            );
713                        }
714                    }
715                    // OptimizerRule was unsuccessful, but skipped failed rules is on
716                    // so use the previous plan
717                    (Err(e), Some(orig_plan)) => {
718                        // Note to future readers: if you see this warning it signals a
719                        // bug in the DataFusion optimizer. Please consider filing a ticket
720                        // https://github.com/apache/datafusion
721                        warn!(
722                            "Skipping optimizer rule '{}' due to unexpected error: {}",
723                            rule.name(),
724                            e
725                        );
726                        new_plan = orig_plan;
727                    }
728                    // OptimizerRule was unsuccessful, but skipped failed rules is off, return error
729                    (Err(e), None) => {
730                        return Err(e.context(format!(
731                            "Optimizer rule '{}' failed",
732                            rule.name()
733                        )));
734                    }
735                }
736            }
737            log_plan(&format!("Optimized plan (pass {i})"), &new_plan);
738
739            // HashSet::insert returns, whether the value was newly inserted.
740            let plan_is_fresh =
741                previous_plans.insert(LogicalPlanSignature::new(&new_plan));
742            if !plan_is_fresh {
743                // plan did not change, so no need to continue trying to optimize
744                debug!("optimizer pass {i} did not make changes");
745                break;
746            }
747            i += 1;
748        }
749
750        // verify that the optimizer passes only mutated what was permitted.
751        assert_valid_optimization(&new_plan, &starting_schema).map_err(|e| {
752            e.context("Check optimizer-specific invariants after all passes")
753        })?;
754
755        // verify LP is valid, after the last optimizer pass.
756        new_plan
757            .check_invariants(InvariantLevel::Executable)
758            .map_err(|e| {
759                e.context("Invalid (non-executable) plan after LP Optimizers")
760            })?;
761
762        log_plan("Final optimized plan", &new_plan);
763        debug!("Optimizer took {} ms", start_time.elapsed().as_millis());
764        Ok(new_plan)
765    }
766}
767
768/// These are invariants which should hold true before and after [`LogicalPlan`] optimization.
769///
770/// This differs from [`LogicalPlan::check_invariants`], which addresses if a singular
771/// LogicalPlan is valid. Instead, this address if the optimization was valid based upon permitted changes.
772fn assert_valid_optimization(
773    plan: &LogicalPlan,
774    prev_schema: &Arc<DFSchema>,
775) -> Result<()> {
776    // verify invariant: optimizer passes should not change the schema if the schema can't be cast from the previous schema.
777    // Refer to <https://datafusion.apache.org/contributor-guide/specification/invariants.html#logical-schema-is-invariant-under-logical-optimization>
778    assert_expected_schema(prev_schema, plan)?;
779
780    Ok(())
781}
782
783#[cfg(test)]
784mod tests {
785    use std::sync::{Arc, Mutex};
786
787    use arrow::datatypes::Metadata;
788
789    use datafusion_common::tree_node::Transformed;
790    use datafusion_common::{
791        Column, DFSchema, DFSchemaRef, DataFusionError, Result, assert_contains, plan_err,
792    };
793    use datafusion_expr::logical_plan::EmptyRelation;
794    use datafusion_expr::{
795        Expr, JoinType, LogicalPlan, LogicalPlanBuilder, Projection, col, lit,
796    };
797
798    use crate::optimizer::Optimizer;
799    use crate::test::{test_table_scan, test_table_scan_with_name};
800    use crate::{OptimizerConfig, OptimizerContext, OptimizerRule};
801
802    use super::ApplyOrder;
803
804    #[test]
805    fn skip_failing_rule() {
806        let opt = Optimizer::with_rules(vec![Arc::new(BadRule {})]);
807        let config = OptimizerContext::new().with_skip_failing_rules(true);
808        let plan = LogicalPlan::EmptyRelation(EmptyRelation {
809            produce_one_row: false,
810            schema: Arc::new(DFSchema::empty()),
811        });
812        opt.optimize(plan, &config, &observe).unwrap();
813    }
814
815    #[test]
816    fn no_skip_failing_rule() {
817        let opt = Optimizer::with_rules(vec![Arc::new(BadRule {})]);
818        let config = OptimizerContext::new().with_skip_failing_rules(false);
819        let plan = LogicalPlan::EmptyRelation(EmptyRelation {
820            produce_one_row: false,
821            schema: Arc::new(DFSchema::empty()),
822        });
823        let err = opt.optimize(plan, &config, &observe).unwrap_err();
824        assert_eq!(
825            "Optimizer rule 'bad rule' failed\ncaused by\n\
826            Error during planning: rule failed",
827            err.strip_backtrace()
828        );
829    }
830
831    #[test]
832    fn generate_different_schema() {
833        let opt = Optimizer::with_rules(vec![Arc::new(GetTableScanRule {})]);
834        let config = OptimizerContext::new().with_skip_failing_rules(false);
835        let plan = LogicalPlan::EmptyRelation(EmptyRelation {
836            produce_one_row: false,
837            schema: Arc::new(DFSchema::empty()),
838        });
839        let err = opt.optimize(plan, &config, &observe).unwrap_err();
840
841        // Simplify assert to check the error message contains the expected message
842        assert_contains!(
843            err.strip_backtrace(),
844            "Failed due to a difference in schemas: original schema: DFSchema"
845        );
846    }
847
848    #[test]
849    fn skip_generate_different_schema() {
850        let opt = Optimizer::with_rules(vec![Arc::new(GetTableScanRule {})]);
851        let config = OptimizerContext::new().with_skip_failing_rules(true);
852        let plan = LogicalPlan::EmptyRelation(EmptyRelation {
853            produce_one_row: false,
854            schema: Arc::new(DFSchema::empty()),
855        });
856        opt.optimize(plan, &config, &observe).unwrap();
857    }
858
859    #[test]
860    fn generate_same_schema_different_metadata() -> Result<()> {
861        // if the plan creates more metadata than previously (because
862        // some wrapping functions are removed, etc) do not error
863        let opt = Optimizer::with_rules(vec![Arc::new(GetTableScanRule {})]);
864        let config = OptimizerContext::new().with_skip_failing_rules(false);
865
866        let input = Arc::new(test_table_scan()?);
867        let input_schema = Arc::clone(input.schema());
868
869        let plan = LogicalPlan::Projection(Projection::try_new_with_schema(
870            vec![col("a"), col("b"), col("c")],
871            input,
872            add_metadata_to_fields(input_schema.as_ref()),
873        )?);
874
875        // optimizing should be ok, but the schema will have changed  (no metadata)
876        assert_ne!(plan.schema().as_ref(), input_schema.as_ref());
877        let optimized_plan = opt.optimize(plan, &config, &observe)?;
878        // metadata was removed
879        assert_eq!(optimized_plan.schema().as_ref(), input_schema.as_ref());
880        Ok(())
881    }
882
883    #[test]
884    fn in_place_rewrite_recomputes_parent_schema_when_child_schema_changes() -> Result<()>
885    {
886        let left = LogicalPlanBuilder::from(test_table_scan_with_name("left")?)
887            .project(vec![col("left.a"), col("left.b"), col("left.c")])?
888            .build()?;
889        let right = LogicalPlanBuilder::from(test_table_scan_with_name("right")?)
890            .project(vec![col("right.a"), col("right.b"), col("right.c")])?
891            .build()?;
892        let mut plan = LogicalPlanBuilder::from(left)
893            .join_on(right, JoinType::Inner, [col("left.a").eq(col("right.a"))])?
894            .build()?;
895
896        assert_eq!(plan.schema().fields().len(), 6);
897
898        let changed = super::rewrite_plan_in_place(
899            &mut plan,
900            ApplyOrder::TopDown,
901            &KeepOnlyAProjectionRule {},
902            &OptimizerContext::new(),
903        )?;
904
905        assert!(changed);
906        assert_eq!(plan.schema().fields().len(), 2);
907        assert!(plan.schema().has_column_with_unqualified_name("a"));
908        Ok(())
909    }
910
911    #[test]
912    fn optimizer_detects_plan_equal_to_the_initial() -> Result<()> {
913        // Run a goofy optimizer, which rotates projection columns
914        // [1, 2, 3] -> [2, 3, 1] -> [3, 1, 2] -> [1, 2, 3]
915
916        let opt = Optimizer::with_rules(vec![Arc::new(RotateProjectionRule::new(false))]);
917        let config = OptimizerContext::new().with_max_passes(16);
918
919        let initial_plan = LogicalPlanBuilder::empty(false)
920            .project([lit(1), lit(2), lit(3)])?
921            .project([lit(100)])? // to not trigger changed schema error
922            .build()?;
923
924        let mut plans: Vec<LogicalPlan> = Vec::new();
925        let final_plan =
926            opt.optimize(initial_plan.clone(), &config, |p, _| plans.push(p.clone()))?;
927
928        // initial_plan is not observed, so we have 3 plans
929        assert_eq!(3, plans.len());
930
931        // we got again the initial_plan with [1, 2, 3]
932        assert_eq!(initial_plan, final_plan);
933
934        Ok(())
935    }
936
937    #[test]
938    fn optimizer_detects_plan_equal_to_a_non_initial() -> Result<()> {
939        // Run a goofy optimizer, which reverses and rotates projection columns
940        // [1, 2, 3] -> [3, 2, 1] -> [2, 1, 3] -> [1, 3, 2] -> [3, 2, 1]
941
942        let opt = Optimizer::with_rules(vec![Arc::new(RotateProjectionRule::new(true))]);
943        let config = OptimizerContext::new().with_max_passes(16);
944
945        let initial_plan = LogicalPlanBuilder::empty(false)
946            .project([lit(1), lit(2), lit(3)])?
947            .project([lit(100)])? // to not trigger changed schema error
948            .build()?;
949
950        let mut plans: Vec<LogicalPlan> = Vec::new();
951        let final_plan =
952            opt.optimize(initial_plan, &config, |p, _| plans.push(p.clone()))?;
953
954        // initial_plan is not observed, so we have 4 plans
955        assert_eq!(4, plans.len());
956
957        // we got again the plan with [3, 2, 1]
958        assert_eq!(plans[0], final_plan);
959
960        Ok(())
961    }
962
963    fn add_metadata_to_fields(schema: &DFSchema) -> DFSchemaRef {
964        let new_fields = schema
965            .iter()
966            .enumerate()
967            .map(|(i, (qualifier, field))| {
968                let metadata = Metadata::new().with("key", format!("value {i}"));
969
970                let new_arrow_field = field.as_ref().clone().with_metadata(metadata);
971                (qualifier.cloned(), Arc::new(new_arrow_field))
972            })
973            .collect::<Vec<_>>();
974
975        let new_metadata = schema.metadata().clone();
976        Arc::new(DFSchema::new_with_metadata(new_fields, new_metadata).unwrap())
977    }
978
979    fn observe(_plan: &LogicalPlan, _rule: &dyn OptimizerRule) {}
980
981    #[derive(Default, Debug)]
982    struct BadRule {}
983
984    impl OptimizerRule for BadRule {
985        fn name(&self) -> &str {
986            "bad rule"
987        }
988
989        fn rewrite(
990            &self,
991            _plan: LogicalPlan,
992            _config: &dyn OptimizerConfig,
993        ) -> Result<Transformed<LogicalPlan>, DataFusionError> {
994            plan_err!("rule failed")
995        }
996    }
997
998    /// Replaces whatever plan with a single table scan
999    #[derive(Default, Debug)]
1000    struct GetTableScanRule {}
1001
1002    impl OptimizerRule for GetTableScanRule {
1003        fn name(&self) -> &str {
1004            "get table_scan rule"
1005        }
1006
1007        fn rewrite(
1008            &self,
1009            _plan: LogicalPlan,
1010            _config: &dyn OptimizerConfig,
1011        ) -> Result<Transformed<LogicalPlan>> {
1012            let table_scan = test_table_scan()?;
1013            Ok(Transformed::yes(
1014                LogicalPlanBuilder::from(table_scan).build()?,
1015            ))
1016        }
1017    }
1018
1019    #[derive(Default, Debug)]
1020    struct KeepOnlyAProjectionRule {}
1021
1022    impl OptimizerRule for KeepOnlyAProjectionRule {
1023        fn name(&self) -> &str {
1024            "keep_only_a_projection"
1025        }
1026
1027        fn apply_order(&self) -> Option<ApplyOrder> {
1028            Some(ApplyOrder::TopDown)
1029        }
1030
1031        fn rewrite(
1032            &self,
1033            plan: LogicalPlan,
1034            _config: &dyn OptimizerConfig,
1035        ) -> Result<Transformed<LogicalPlan>> {
1036            let LogicalPlan::Projection(projection) = plan else {
1037                return Ok(Transformed::no(plan));
1038            };
1039
1040            let expr = Expr::from(Column::from(projection.schema.qualified_field(0)));
1041
1042            Ok(Transformed::yes(LogicalPlan::Projection(
1043                Projection::try_new(vec![expr], Arc::clone(&projection.input))?,
1044            )))
1045        }
1046    }
1047
1048    /// A goofy rule doing rotation of columns in all projections.
1049    ///
1050    /// Useful to test cycle detection.
1051    #[derive(Default, Debug)]
1052    struct RotateProjectionRule {
1053        // reverse exprs instead of rotating on the first pass
1054        reverse_on_first_pass: Mutex<bool>,
1055    }
1056
1057    impl RotateProjectionRule {
1058        fn new(reverse_on_first_pass: bool) -> Self {
1059            Self {
1060                reverse_on_first_pass: Mutex::new(reverse_on_first_pass),
1061            }
1062        }
1063    }
1064
1065    impl OptimizerRule for RotateProjectionRule {
1066        fn name(&self) -> &str {
1067            "rotate_projection"
1068        }
1069
1070        fn apply_order(&self) -> Option<ApplyOrder> {
1071            Some(ApplyOrder::TopDown)
1072        }
1073
1074        fn rewrite(
1075            &self,
1076            plan: LogicalPlan,
1077            _config: &dyn OptimizerConfig,
1078        ) -> Result<Transformed<LogicalPlan>> {
1079            let projection = match plan {
1080                LogicalPlan::Projection(p) if p.expr.len() >= 2 => p,
1081                _ => return Ok(Transformed::no(plan)),
1082            };
1083
1084            let mut exprs = projection.expr.clone();
1085
1086            let mut reverse = self.reverse_on_first_pass.lock().unwrap();
1087            if *reverse {
1088                exprs.reverse();
1089                *reverse = false;
1090            } else {
1091                exprs.rotate_left(1);
1092            }
1093
1094            Ok(Transformed::yes(LogicalPlan::Projection(
1095                Projection::try_new(exprs, Arc::clone(&projection.input))?,
1096            )))
1097        }
1098    }
1099}