datafusion_session/physical_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//! Physical optimizer interfaces.
6
7use std::fmt::Debug;
8use std::sync::Arc;
9
10use datafusion_common::config::ConfigOptions;
11use datafusion_common::{Result, Statistics};
12use datafusion_physical_plan::ExecutionPlan;
13use datafusion_physical_plan::operator_statistics::StatisticsRegistry;
14use datafusion_physical_plan::statistics::{StatisticsArgs, StatisticsContext};
15
16/// Context available to physical optimizer rules.
17///
18/// This trait provides access to configuration options and an optional statistics
19/// registry for enhanced statistics lookup.
20pub trait PhysicalOptimizerContext: Send + Sync {
21 /// Returns the configuration options.
22 fn config_options(&self) -> &ConfigOptions;
23
24 /// Returns the statistics registry for enhanced statistics lookup.
25 ///
26 /// Returns `None` if no registry is configured, in which case rules
27 /// should fall back to using [`ExecutionPlan::partition_statistics`].
28 fn statistics_registry(&self) -> Option<&StatisticsRegistry> {
29 None
30 }
31
32 /// Returns a [`StatisticsContext`] shared by every rule of one optimizer
33 /// run, so statistics computed by one rule are reused by later rules.
34 ///
35 /// The context must be built from [`Self::statistics_registry`]. Its cache
36 /// entries hold the plan nodes they were computed for, so it is safe to
37 /// share across plan rewrites (see [`StatisticsContext`]).
38 ///
39 /// Returns `None` if no shared context is available, in which case rules
40 /// create their own context.
41 fn statistics_context(&self) -> Option<&StatisticsContext> {
42 None
43 }
44
45 /// Computes the statistics of `plan` with [`Self::statistics_context`],
46 /// or, if it is `None`, with a new context built from
47 /// [`Self::statistics_registry`].
48 ///
49 /// Rules that compute statistics should use this, so they reuse the
50 /// statistics computed by earlier rules and consult the same statistics
51 /// providers as the built-in rules.
52 ///
53 /// # Example
54 ///
55 /// ```
56 /// # use std::sync::Arc;
57 /// # use arrow_schema::Schema;
58 /// # use datafusion_common::config::ConfigOptions;
59 /// # use datafusion_physical_plan::ExecutionPlan;
60 /// # use datafusion_physical_plan::empty::EmptyExec;
61 /// # use datafusion_physical_plan::statistics::StatisticsArgs;
62 /// # use datafusion_session::PhysicalOptimizerContext;
63 /// # struct MyContext(ConfigOptions);
64 /// # impl PhysicalOptimizerContext for MyContext {
65 /// # fn config_options(&self) -> &ConfigOptions {
66 /// # &self.0
67 /// # }
68 /// # }
69 /// # let context = MyContext(ConfigOptions::new());
70 /// let plan: Arc<dyn ExecutionPlan> = Arc::new(EmptyExec::new(Arc::new(Schema::empty())));
71 /// let statistics = context.compute_statistics(&plan, &StatisticsArgs::new())?;
72 /// # Ok::<(), datafusion_common::DataFusionError>(())
73 /// ```
74 fn compute_statistics(
75 &self,
76 plan: &Arc<dyn ExecutionPlan>,
77 args: &StatisticsArgs,
78 ) -> Result<Arc<Statistics>> {
79 with_statistics_context(self, |stats_ctx| stats_ctx.compute_arc(plan, args))
80 }
81}
82
83/// Calls `f` with [`PhysicalOptimizerContext::statistics_context`], or, if it
84/// is `None`, with a new context built from
85/// [`PhysicalOptimizerContext::statistics_registry`].
86///
87/// Use this to pass one [`StatisticsContext`] down a traversal. To compute
88/// the statistics of a single plan, use
89/// [`PhysicalOptimizerContext::compute_statistics`].
90pub fn with_statistics_context<C, R>(
91 context: &C,
92 f: impl FnOnce(&StatisticsContext) -> R,
93) -> R
94where
95 C: PhysicalOptimizerContext + ?Sized,
96{
97 if let Some(shared) = context.statistics_context() {
98 return f(shared);
99 }
100 let local = match context.statistics_registry() {
101 Some(registry) => StatisticsContext::new_with_registry(registry.clone()),
102 None => StatisticsContext::new(),
103 };
104 f(&local)
105}
106
107/// `PhysicalOptimizerRule` transforms one [`ExecutionPlan`] into another which
108/// computes the same results, but in a potentially more efficient way.
109///
110/// The returned plan must be valid and produce the same results as the input
111/// plan. See [`PhysicalOptimizer`] for more details.
112///
113/// Use [`SessionStateBuilder::with_physical_optimizer_rule`] to register additional
114/// `PhysicalOptimizerRule`s.
115///
116/// [`PhysicalOptimizer`]: https://docs.rs/datafusion-physical-optimizer/latest/datafusion_physical_optimizer/optimizer/struct.PhysicalOptimizer.html
117/// [`SessionStateBuilder::with_physical_optimizer_rule`]: https://docs.rs/datafusion/latest/datafusion/execution/session_state/struct.SessionStateBuilder.html#method.with_physical_optimizer_rule
118pub trait PhysicalOptimizerRule: Debug + std::any::Any {
119 /// Rewrite `plan` to an optimized form.
120 ///
121 /// This is the primary optimization method. For rules that need access to
122 /// the statistics registry, override [`optimize_with_context`](Self::optimize_with_context) instead.
123 fn optimize(
124 &self,
125 plan: Arc<dyn ExecutionPlan>,
126 config: &ConfigOptions,
127 ) -> Result<Arc<dyn ExecutionPlan>>;
128
129 /// Rewrite `plan` with access to extended context (statistics registry, etc.).
130 ///
131 /// Override this method if you need access to the statistics registry for
132 /// enhanced statistics lookup. The default implementation simply calls
133 /// [`optimize`](Self::optimize) with the config options from the context.
134 fn optimize_with_context(
135 &self,
136 plan: Arc<dyn ExecutionPlan>,
137 context: &dyn PhysicalOptimizerContext,
138 ) -> Result<Arc<dyn ExecutionPlan>> {
139 self.optimize(plan, context.config_options())
140 }
141
142 /// A human readable name for this optimizer rule
143 fn name(&self) -> &str;
144
145 /// A flag to indicate whether the physical planner should validate that the rule will not
146 /// change the schema of the plan after the rewriting.
147 /// Some of the optimization rules might change the nullable properties of the schema
148 /// and should disable the schema check.
149 ///
150 /// The planner reads this from the rule it holds, so a rule that runs
151 /// *other* rules inside its own [`optimize`] must account for what the
152 /// whole wrapped transformation does to the schema, not just its own body:
153 ///
154 /// * A wrapper around a single rule should forward that rule's value.
155 /// * A wrapper that runs multiple rules should return `true` only if the
156 /// complete wrapped transformation preserves the schema contract. When
157 /// that is derived solely from the wrapped rules, every wrapped rule must
158 /// enable the check (`all()`, not `any()`): if any wrapped rule is allowed
159 /// to change the schema, returning `true` makes the checker assert a
160 /// change it should tolerate.
161 /// * A wrapper mixing schema-preserving and schema-changing rules cannot be
162 /// expressed as a single flag; validate per-rule inside the wrapper so the
163 /// inner checks are retained.
164 ///
165 /// When the flag can be derived from the wrapped rules, `all()` (not
166 /// `any()`) is the safe combinator:
167 ///
168 /// ```text
169 /// fn schema_check(&self) -> bool {
170 /// self.wrapped.iter().all(|rule| rule.schema_check())
171 /// }
172 /// ```
173 ///
174 /// Returning a blanket `false` still silently disables validation for
175 /// everything inside, including rules that asked for it.
176 ///
177 /// [`optimize`]: PhysicalOptimizerRule::optimize
178 fn schema_check(&self) -> bool;
179}