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 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}