Skip to main content

datafusion_physical_optimizer/
optimizer.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18//! Physical optimizer traits
19
20use std::fmt::Debug;
21use std::sync::Arc;
22
23use crate::aggregate_statistics::AggregateStatistics;
24use crate::combine_partial_final_agg::CombinePartialFinalAggregate;
25use crate::ensure_coop::EnsureCooperative;
26use crate::ensure_requirements::EnsureRequirements;
27use crate::filter_pushdown::FilterPushdown;
28use crate::join_selection::JoinSelection;
29use crate::limit_pushdown::LimitPushdown;
30use crate::limited_distinct_aggregation::LimitedDistinctAggregation;
31use crate::output_requirements::OutputRequirements;
32use crate::projection_pushdown::ProjectionPushdown;
33use crate::sanity_checker::SanityCheckPlan;
34use crate::topk_aggregation::TopKAggregation;
35use crate::topk_repartition::TopKRepartition;
36use crate::update_aggr_exprs::OptimizeAggregateOrder;
37
38use crate::hash_join_buffering::HashJoinBuffering;
39use crate::limit_pushdown_past_window::LimitPushPastWindows;
40use crate::pushdown_sort::PushdownSort;
41use crate::window_topn::WindowTopN;
42use datafusion_common::config::ConfigOptions;
43
44// Re-export from this module for backwards compatibility.
45pub use datafusion_session::{PhysicalOptimizerContext, PhysicalOptimizerRule};
46
47/// Simple context wrapping [`ConfigOptions`] for backward compatibility.
48///
49/// This struct provides a minimal implementation of [`PhysicalOptimizerContext`]
50/// that only supplies configuration options. Used when no statistics registry
51/// is available or needed.
52pub struct ConfigOnlyContext<'a> {
53    config: &'a ConfigOptions,
54}
55
56impl<'a> ConfigOnlyContext<'a> {
57    /// Create a new context wrapping the given config options.
58    pub fn new(config: &'a ConfigOptions) -> Self {
59        Self { config }
60    }
61}
62
63impl PhysicalOptimizerContext for ConfigOnlyContext<'_> {
64    fn config_options(&self) -> &ConfigOptions {
65        self.config
66    }
67}
68
69/// A rule-based physical optimizer.
70#[derive(Clone, Debug)]
71pub struct PhysicalOptimizer {
72    /// All rules to apply
73    pub rules: Vec<Arc<dyn PhysicalOptimizerRule + Send + Sync>>,
74}
75
76impl Default for PhysicalOptimizer {
77    fn default() -> Self {
78        Self::new()
79    }
80}
81
82impl PhysicalOptimizer {
83    /// Create a new optimizer using the recommended list of rules
84    pub fn new() -> Self {
85        // NOTEs:
86        // - The order of rules in this list is important, as it determines the
87        //   order in which they are applied.
88        // - Adding a new rule here is expensive as it will be applied to all
89        //   queries, and will likely increase the optimization time. Please extend
90        //   existing rules when possible, rather than adding a new rule.
91        let rules: Vec<Arc<dyn PhysicalOptimizerRule + Send + Sync>> = vec![
92            // If there is a output requirement of the query, make sure that
93            // this information is not lost across different rules during optimization.
94            Arc::new(OutputRequirements::new_add_mode()),
95            Arc::new(AggregateStatistics::new()),
96            // Statistics-based join selection will change the Auto mode to a real join implementation,
97            // like collect left, or hash join, or future sort merge join, which will influence the
98            // EnsureRequirements rule as it decides whether to add additional repartitioning and
99            // local sorting steps to meet distribution and ordering requirements. Therefore, it
100            // should run before EnsureRequirements.
101            Arc::new(JoinSelection::new()),
102            // The LimitedDistinctAggregation rule should be applied before EnsureRequirements,
103            // as that rule may inject other operations in between the different AggregateExecs.
104            // Applying the rule early means only directly-connected AggregateExecs must be examined.
105            Arc::new(LimitedDistinctAggregation::new()),
106            // The FilterPushdown rule tries to push down filters as far as it can.
107            // For example, it will push down filtering from a `FilterExec` to `DataSourceExec`.
108            // Note that this does not push down dynamic filters (such as those created by a `SortExec` operator in TopK mode),
109            // those are handled by the later `FilterPushdown` rule.
110            // See `FilterPushdownPhase` for more details.
111            Arc::new(FilterPushdown::new()),
112            // WindowTopN: replaces Filter(rn<=K) → Window(ROW_NUMBER)
113            // with Window(ROW_NUMBER) → PartitionedTopKExec(fetch=K).
114            // Must run before EnsureRequirements (so it can rewrite against the
115            // window's declared ordering without pattern-matching a SortExec)
116            // and before ProjectionPushdown (which embeds projections into FilterExec).
117            Arc::new(WindowTopN::new()),
118            // Ensures each input plan satisfies the distribution and ordering
119            // requirements declared by `ExecutionPlan::required_input_distribution`
120            // and `ExecutionPlan::required_input_ordering`.
121            //
122            // If the requirements are already satisfied, this rule leaves the plan
123            // unchanged. For example, it does not add sorting when the input is a
124            // file scan whose existing order already satisfies the required ordering.
125            // Otherwise, this rule inserts the necessary repartitioning and sorting
126            // operators.
127            //
128            // This used to be implemented as two separate rules: `EnforceDistribution`
129            // and `EnforceSorting`. It is now a single idempotent rule that decides
130            // distribution and sorting together in one bottom-up pass, so the
131            // `pushdown_sorts` step no longer breaks distribution invariants set
132            // earlier in the pipeline. See the module-level doc on
133            // [`EnsureRequirements`](crate::ensure_requirements) for the per-phase
134            // breakdown, and <https://github.com/apache/datafusion/issues/21973>
135            // for the original failure mode.
136            Arc::new(EnsureRequirements::new()),
137            // The CombinePartialFinalAggregate rule should be applied after distribution enforcement
138            Arc::new(CombinePartialFinalAggregate::new()),
139            // Run once after the local sorting requirement is changed
140            Arc::new(OptimizeAggregateOrder::new()),
141            // TODO: `try_embed_to_hash_join` in the ProjectionPushdown rule would be block by the CoalesceBatches, so add it before CoalesceBatches. Maybe optimize it in the future.
142            Arc::new(ProjectionPushdown::new()),
143            // Remove the ancillary output requirement operator since we are done with the planning
144            // phase.
145            Arc::new(OutputRequirements::new_remove_mode()),
146            // The aggregation limiter will try to find situations where the accumulator count
147            // is not tied to the cardinality, i.e. when the output of the aggregation is passed
148            // into an `order by max(x) limit y`. In this case it will copy the limit value down
149            // to the aggregation, allowing it to use only y number of accumulators.
150            Arc::new(TopKAggregation::new()),
151            // Tries to push limits down through window functions, growing as appropriate
152            // This can possibly be combined with [LimitPushdown]
153            // It needs to come after [EnsureRequirements] (which handles sort enforcement)
154            Arc::new(LimitPushPastWindows::new()),
155            // The HashJoinBuffering rule adds a BufferExec node with the configured capacity
156            // in the prob side of hash joins. That way, the probe side gets eagerly polled before
157            // the build side is completely finished.
158            Arc::new(HashJoinBuffering::new()),
159            // The LimitPushdown rule tries to push limits down as far as possible,
160            // replacing operators with fetching variants, or adding limits
161            // past operators that support limit pushdown.
162            Arc::new(LimitPushdown::new()),
163            // TopKRepartition pushes TopK (Sort with fetch) below Hash
164            // repartition when the partition key is a prefix of the sort key.
165            // This reduces data volume before a hash shuffle. It must run
166            // after LimitPushdown so that the TopK already exists on the SortExec.
167            Arc::new(TopKRepartition::new()),
168            // The ProjectionPushdown rule tries to push projections towards
169            // the sources in the execution plan. As a result of this process,
170            // a projection can disappear if it reaches the source providers, and
171            // sequential projections can merge into one. Even if these two cases
172            // are not present, the load of executors such as join or union will be
173            // reduced by narrowing their input tables.
174            Arc::new(ProjectionPushdown::new()),
175            // PushdownSort: Detect sorts that can be pushed down to data sources.
176            Arc::new(PushdownSort::new()),
177            Arc::new(EnsureCooperative::new()),
178            // This FilterPushdown handles dynamic filters that may have references to the source ExecutionPlan.
179            // Therefore, it should be run at the end of the optimization process since any changes to the plan may break the dynamic filter's references.
180            // See `FilterPushdownPhase` for more details.
181            Arc::new(FilterPushdown::new_post_optimization()),
182            // The SanityCheckPlan rule checks whether the order and
183            // distribution requirements of each node in the plan
184            // is satisfied. It will also reject non-runnable query
185            // plans that use pipeline-breaking operators on infinite
186            // input(s). The rule generates a diagnostic error
187            // message for invalid plans. It makes no changes to the
188            // given query plan; i.e. it only acts as a final
189            // gatekeeping rule.
190            Arc::new(SanityCheckPlan::new()),
191        ];
192
193        Self::with_rules(rules)
194    }
195
196    /// Create a new optimizer with the given rules
197    pub fn with_rules(rules: Vec<Arc<dyn PhysicalOptimizerRule + Send + Sync>>) -> Self {
198        Self { rules }
199    }
200}