Skip to main content

datafusion_physical_plan/
execution_plan.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
5pub use crate::display::{DefaultDisplay, DisplayAs, DisplayFormatType, VerboseDisplay};
6use crate::distribution_requirements::InputDistributionRequirements;
7use crate::filter_pushdown::{
8    ChildPushdownResult, FilterDescription, FilterPushdownPhase,
9    FilterPushdownPropagation,
10};
11pub use crate::metrics::Metric;
12pub use crate::ordering::InputOrderMode;
13use crate::sort_pushdown::SortOrderPushdownResult;
14pub use crate::stream::EmptyRecordBatchStream;
15
16use arrow_schema::Schema;
17pub use datafusion_common::hash_utils;
18use datafusion_common::tree_node::{
19    Transformed, TransformedResult, TreeNode, TreeNodeRecursion,
20};
21pub use datafusion_common::utils::project_schema;
22pub use datafusion_common::{ColumnStatistics, Statistics, internal_err};
23pub use datafusion_execution::{RecordBatchStream, SendableRecordBatchStream};
24pub use datafusion_expr::{Accumulator, ColumnarValue};
25use datafusion_physical_expr::projection::ProjectionExpr;
26pub use datafusion_physical_expr::window::WindowExpr;
27pub use datafusion_physical_expr::{
28    Distribution, Partitioning, PhysicalExpr, expressions,
29};
30
31use std::any::Any;
32use std::collections::HashSet;
33use std::fmt::Debug;
34use std::sync::{Arc, LazyLock};
35
36use crate::coalesce_partitions::CoalescePartitionsExec;
37use crate::display::DisplayableExecutionPlan;
38use crate::metrics::MetricsSet;
39use crate::projection::ProjectionExec;
40use crate::repartition::RepartitionExec;
41use crate::sorts::sort_preserving_merge::SortPreservingMergeExec;
42use crate::statistics::{ChildStats, StatisticsArgs};
43use crate::stream::RecordBatchStreamAdapter;
44
45use arrow::array::{Array, RecordBatch};
46use arrow::datatypes::SchemaRef;
47use datafusion_common::config::ConfigOptions;
48use datafusion_common::{
49    Constraints, DataFusionError, Result, assert_eq_or_internal_err,
50    assert_or_internal_err, exec_err,
51};
52use datafusion_common_runtime::JoinSet;
53use datafusion_execution::TaskContext;
54use datafusion_physical_expr::EquivalenceProperties;
55use datafusion_physical_expr_common::sort_expr::{
56    LexOrdering, OrderingRequirements, PhysicalSortExpr,
57};
58
59use futures::stream::{StreamExt, TryStreamExt};
60
61/// Represent nodes in the DataFusion Physical Plan.
62///
63/// Calling [`execute`] produces an `async` [`SendableRecordBatchStream`] of
64/// [`RecordBatch`] that incrementally computes a partition of the
65/// `ExecutionPlan`'s output from its input. See [`Partitioning`] for more
66/// details on partitioning.
67///
68/// Methods such as [`Self::schema`] and [`Self::properties`] communicate
69/// properties of the output to the DataFusion optimizer, and methods such as
70/// [`required_input_distribution`] and [`required_input_ordering`] express
71/// requirements of the `ExecutionPlan` from its input.
72///
73/// [`ExecutionPlan`] can be displayed in a simplified form using the
74/// return value from [`displayable`] in addition to the (normally
75/// quite verbose) `Debug` output.
76///
77/// [`execute`]: ExecutionPlan::execute
78/// [`required_input_distribution`]: ExecutionPlan::required_input_distribution
79/// [`required_input_ordering`]: ExecutionPlan::required_input_ordering
80///
81/// # Examples
82///
83/// See [`datafusion-examples`] for examples, including
84/// [`memory_pool_execution_plan.rs`] which shows how to implement a custom
85/// `ExecutionPlan` with memory tracking and spilling support.
86///
87/// [`datafusion-examples`]: https://github.com/apache/datafusion/tree/main/datafusion-examples
88/// [`memory_pool_execution_plan.rs`]: https://github.com/apache/datafusion/blob/main/datafusion-examples/examples/execution_monitoring/memory_pool_execution_plan.rs
89pub trait ExecutionPlan: Any + Debug + DisplayAs + Send + Sync {
90    /// Short name for the ExecutionPlan, such as 'DataSourceExec'.
91    ///
92    /// Implementation note: this method can just proxy to
93    /// [`static_name`](ExecutionPlan::static_name) if no special action is
94    /// needed. It doesn't provide a default implementation like that because
95    /// this method doesn't require the `Sized` constrain to allow a wilder
96    /// range of use cases.
97    fn name(&self) -> &str;
98
99    /// Short name for the ExecutionPlan, such as 'DataSourceExec'.
100    /// Like [`name`](ExecutionPlan::name) but can be called without an instance.
101    fn static_name() -> &'static str
102    where
103        Self: Sized,
104    {
105        let full_name = std::any::type_name::<Self>();
106        let maybe_start_idx = full_name.rfind(':');
107        match maybe_start_idx {
108            Some(start_idx) => &full_name[start_idx + 1..],
109            None => "UNKNOWN",
110        }
111    }
112
113    /// Returns the plan that provides this plan's public
114    /// [`ExecutionPlan`] downcast identity.
115    ///
116    /// This hook is for wrapper nodes that delegate their public downcast
117    /// identity to another plan while adding cross-cutting behavior such as
118    /// instrumentation. The default implementation returns `None`, meaning this
119    /// plan's concrete type is used for type introspection.
120    ///
121    /// Most `ExecutionPlan` implementations should use the default `None`;
122    /// override this only for wrapper plans that intentionally delegate their
123    /// public downcast identity to another plan.
124    ///
125    /// The `is` and `downcast_ref` helpers follow the returned delegate instead
126    /// of checking the current concrete type, making intermediate delegating
127    /// wrappers invisible to normal downcast-based inspection.
128    ///
129    /// Implementations that opt in should return the delegate plan, not `self`.
130    ///
131    /// This is independent from [`Self::children`] and should not be used for
132    /// plan traversal or optimizer rewrites.
133    fn downcast_delegate(&self) -> Option<&dyn ExecutionPlan> {
134        None
135    }
136
137    /// Get the schema for this execution plan
138    fn schema(&self) -> SchemaRef {
139        Arc::clone(self.properties().schema())
140    }
141
142    /// Return properties of the output of the `ExecutionPlan`, such as output
143    /// ordering(s), partitioning information etc.
144    ///
145    /// This information is available via methods on [`ExecutionPlanProperties`]
146    /// trait, which is implemented for all `ExecutionPlan`s.
147    fn properties(&self) -> &Arc<PlanProperties>;
148
149    /// Returns an error if this individual node does not conform to its invariants.
150    /// These invariants are typically only checked in debug mode.
151    ///
152    /// A default set of invariants is provided in the [check_default_invariants] function.
153    /// The default implementation of `check_invariants` calls this function.
154    /// Extension nodes can provide their own invariants.
155    fn check_invariants(&self, check: InvariantLevel) -> Result<()> {
156        check_default_invariants(self, check)
157    }
158
159    /// Returns the dynamic expressions produced by this plan node.
160    ///
161    /// A dynamic expression is produced when this node updates or completes its
162    /// runtime state during execution. Expressions that this node only consumes
163    /// must not be returned. This method is shallow and does not include dynamic
164    /// expressions produced by child plans.
165    ///
166    /// Each returned expression must have a [`PhysicalExpr::expression_id`]
167    /// since all dynamic expressions such as [`DynamicFilterPhysicalExpr`]
168    /// have an expression id.
169    ///
170    /// [`DynamicFilterPhysicalExpr`]: datafusion_physical_expr::expressions::DynamicFilterPhysicalExpr
171    fn dynamic_expressions_produced(&self) -> Vec<Arc<dyn PhysicalExpr>> {
172        Vec::new()
173    }
174
175    /// Specifies simple per-child input distribution requirements.
176    ///
177    /// Deprecated: override [`Self::input_distribution_requirements`] instead.
178    ///
179    /// By default, each child has [`Distribution::UnspecifiedDistribution`].
180    #[deprecated(since = "55.0.0", note = "Use input_distribution_requirements")]
181    fn required_input_distribution(&self) -> Vec<Distribution> {
182        vec![Distribution::UnspecifiedDistribution; self.children().len()]
183    }
184
185    /// Specifies the input distribution requirements for this plan.
186    ///
187    /// The default implementation wraps [`Self::required_input_distribution`].
188    /// Override this method for richer requirements, such as allowing alternate
189    /// satisfaction policies or requiring multiple children to be co-partitioned.
190    /// See [`InputDistributionRequirements`] for details.
191    fn input_distribution_requirements(&self) -> InputDistributionRequirements {
192        #[expect(
193            deprecated,
194            reason = "compatibility shim for external ExecutionPlan implementations"
195        )]
196        InputDistributionRequirements::new(self.required_input_distribution())
197    }
198
199    /// Specifies the ordering required for all of the children of this
200    /// `ExecutionPlan`.
201    ///
202    /// For each child, it's the local ordering requirement within
203    /// each partition rather than the global ordering
204    ///
205    /// NOTE that checking `!is_empty()` does **not** check for a
206    /// required input ordering. Instead, the correct check is that at
207    /// least one entry must be `Some`
208    fn required_input_ordering(&self) -> Vec<Option<OrderingRequirements>> {
209        vec![None; self.children().len()]
210    }
211
212    /// Returns `false` if this `ExecutionPlan`'s implementation may reorder
213    /// rows within or between partitions.
214    ///
215    /// For example, Projection, Filter, and Limit maintain the order
216    /// of inputs -- they may transform values (Projection) or not
217    /// produce the same number of rows that went in (Filter and
218    /// Limit), but the rows that are produced go in the same way.
219    ///
220    /// DataFusion uses this metadata to apply certain optimizations
221    /// such as automatically repartitioning correctly.
222    ///
223    /// The default implementation returns `false`
224    ///
225    /// WARNING: if you override this default, you *MUST* ensure that
226    /// the `ExecutionPlan`'s maintains the ordering invariant or else
227    /// DataFusion may produce incorrect results.
228    fn maintains_input_order(&self) -> Vec<bool> {
229        vec![false; self.children().len()]
230    }
231
232    /// Specifies whether the `ExecutionPlan` benefits from increased
233    /// parallelization at its input for each child.
234    ///
235    /// If returns `true`, the `ExecutionPlan` would benefit from partitioning
236    /// its corresponding child (and thus from more parallelism). For
237    /// `ExecutionPlan` that do very little work the overhead of extra
238    /// parallelism may outweigh any benefits
239    ///
240    /// The default implementation returns `true` unless this `ExecutionPlan`
241    /// has signalled it requires a single child input partition.
242    fn benefits_from_input_partitioning(&self) -> Vec<bool> {
243        // By default try to maximize parallelism with more CPUs if
244        // possible
245        self.input_distribution_requirements()
246            .per_child_distributions()
247            .map(|dist| !matches!(dist, Distribution::SinglePartition))
248            .collect()
249    }
250
251    /// Get a list of children `ExecutionPlan`s that act as inputs to this plan.
252    /// The returned list will be empty for leaf nodes such as scans, will contain
253    /// a single value for unary nodes, or two values for binary nodes (such as
254    /// joins).
255    fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>>;
256
257    /// Returns a clone of the existing plan with the children replaced,
258    /// skipping recomputation of plan properties when the options indicate
259    /// the new children's properties are unchanged.
260    ///
261    /// Callers should typically call [`replace_children_if_necessary`] and
262    /// not invoke this method directly.
263    fn replace_children(
264        self: Arc<Self>,
265        children: Vec<Arc<dyn ExecutionPlan>>,
266        options: ReplaceChildrenOptions,
267    ) -> Result<Arc<dyn ExecutionPlan>> {
268        #[expect(deprecated)]
269        match options.children_properties {
270            ChildrenPropertiesMode::Keep => {
271                self.with_new_children_and_same_properties(children)
272            }
273            ChildrenPropertiesMode::Recompute => self.with_new_children(children),
274        }
275    }
276
277    /// Apply a closure `f` to each root expression that this node owns and uses
278    /// during execution, either by evaluating it or updating it dynamically.
279    ///
280    /// An expression must not be visited solely because it describes an input or
281    /// output property, such as cached ordering, partitioning, or equivalence
282    /// metadata. However, these may be traversed indirectly. For example,
283    /// `RepartitionExec` visits the partitioning expressions it evaluates  and
284    /// `SortExec` visits the sort expressions it evaluates to order rows.
285    ///
286    /// This method is shallow: it must not visit expression children or expressions
287    /// owned by child execution plans.
288    ///
289    /// Similarly to other [`TreeNode`] APIs, the closure can return
290    /// [`TreeNodeRecursion::Stop`] to stop iteration, otherwise iteration
291    /// should continue. Note that [`TreeNodeRecursion::Continue`] and
292    /// [`TreeNodeRecursion::Jump`] are equivalent because this method is not
293    /// recursive.
294    ///
295    ///
296    /// # Example Usage
297    /// ```
298    /// # use std::sync::Arc;
299    /// # use datafusion_physical_plan::ExecutionPlan;
300    /// # use datafusion_common::tree_node::TreeNodeRecursion;
301    /// # fn example(plan: Arc<dyn ExecutionPlan>) -> datafusion_common::Result<()> {
302    /// // Count the number of expressions
303    /// let mut count = 0;
304    /// plan.apply_expressions(&mut |_expr| {
305    ///     count += 1;
306    ///     Ok(TreeNodeRecursion::Continue)
307    /// })?;
308    /// # Ok(())
309    /// # }
310    /// ```
311    ///
312    /// # Implementation Examples
313    ///
314    /// ## Node with expressions (e.g., FilterExec, ProjectionExec)
315    ///
316    /// Use [`apply_expression_roots`] to implement this method. It abstracts away the
317    /// [`TreeNodeRecursion`] iteration from implementors.
318    /// ```ignore
319    /// fn apply_expressions(
320    ///     &self,
321    ///     f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> Result<TreeNodeRecursion>,
322    /// ) -> Result<TreeNodeRecursion> {
323    ///     apply_expression_roots([&self.predicate], f)
324    /// }
325    /// ```
326    ///
327    /// ## Node with no expressions (e.g., EmptyExec, MemoryExec)
328    /// ```ignore
329    /// fn apply_expressions(
330    ///     &self,
331    ///     _f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> Result<TreeNodeRecursion>,
332    /// ) -> Result<TreeNodeRecursion> {
333    ///     Ok(TreeNodeRecursion::Continue)
334    /// }
335    /// ```
336    fn apply_expressions(
337        &self,
338        f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> Result<TreeNodeRecursion>,
339    ) -> Result<TreeNodeRecursion>;
340
341    /// Deprecated.
342    ///
343    /// DataFusion will remove this method in the future in favor of
344    /// [`ExecutionPlan::replace_children`].
345    ///
346    /// Note that this method is still required by the trait; implementations
347    /// should delegate to [`ExecutionPlan::replace_children`] with
348    /// [`ChildrenPropertiesMode::Recompute`].
349    ///
350    /// # Example Implementation
351    /// ```
352    /// # #![allow(deprecated)]
353    /// # use std::fmt;
354    /// # use std::sync::Arc;
355    /// # use datafusion_common::Result;
356    /// # use datafusion_common::tree_node::TreeNodeRecursion;
357    /// # use datafusion_execution::{SendableRecordBatchStream, TaskContext};
358    /// # use datafusion_physical_expr::PhysicalExpr;
359    /// # use datafusion_physical_plan::{
360    /// #     ChildrenPropertiesMode, DisplayAs, DisplayFormatType, ExecutionPlan,
361    /// #     PlanProperties, ReplaceChildrenOptions,
362    /// # };
363    /// # #[derive(Debug)]
364    /// # struct MyExec {
365    /// #     input: Arc<dyn ExecutionPlan>,
366    /// # }
367    /// # impl DisplayAs for MyExec {
368    /// #     fn fmt_as(&self, _t: DisplayFormatType, f: &mut fmt::Formatter) -> fmt::Result {
369    /// #         write!(f, "MyExec")
370    /// #     }
371    /// # }
372    /// impl ExecutionPlan for MyExec {
373    ///     // ...
374    /// #    fn name(&self) -> &'static str {
375    /// #        "MyExec"
376    /// #    }
377    /// #    fn properties(&self) -> &Arc<PlanProperties> {
378    /// #        self.input.properties()
379    /// #    }
380    /// #    fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
381    /// #        vec![&self.input]
382    /// #    }
383    /// #    fn apply_expressions(
384    /// #        &self,
385    /// #        _f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> Result<TreeNodeRecursion>,
386    /// #    ) -> Result<TreeNodeRecursion> {
387    /// #        Ok(TreeNodeRecursion::Continue)
388    /// #    }
389    /// #    fn execute(
390    /// #        &self,
391    /// #        _partition: usize,
392    /// #        _context: Arc<TaskContext>,
393    /// #    ) -> Result<SendableRecordBatchStream> {
394    /// #        unimplemented!()
395    /// #    }
396    ///     fn replace_children(
397    ///         self: Arc<Self>,
398    ///         mut children: Vec<Arc<dyn ExecutionPlan>>,
399    ///         _options: ReplaceChildrenOptions,
400    ///     ) -> Result<Arc<dyn ExecutionPlan>> {
401    ///         Ok(Arc::new(MyExec {
402    ///             input: children.swap_remove(0),
403    ///         }))
404    ///     }
405    ///
406    ///     fn with_new_children(
407    ///         self: Arc<Self>,
408    ///         children: Vec<Arc<dyn ExecutionPlan>>,
409    ///     ) -> Result<Arc<dyn ExecutionPlan>> {
410    ///         // call into `replace_children` with `ReplaceChildrenOptions`
411    ///         self.replace_children(
412    ///             children,
413    ///             ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute),
414    ///         )
415    ///     }
416    /// }
417    /// ```
418    #[deprecated(
419        since = "55.0.0",
420        note = "Use `ExecutionPlan::replace_children` with `ReplaceChildrenOptions`"
421    )]
422    fn with_new_children(
423        self: Arc<Self>,
424        children: Vec<Arc<dyn ExecutionPlan>>,
425    ) -> Result<Arc<dyn ExecutionPlan>>;
426
427    /// Deprecated. Implement [`ExecutionPlan::replace_children`] instead.
428    #[deprecated(
429        since = "55.0.0",
430        note = "Use `ExecutionPlan::replace_children` with `ReplaceChildrenOptions`"
431    )]
432    #[expect(deprecated)]
433    fn with_new_children_and_same_properties(
434        self: Arc<Self>,
435        children: Vec<Arc<dyn ExecutionPlan>>,
436    ) -> Result<Arc<dyn ExecutionPlan>> {
437        self.with_new_children(children)
438    }
439
440    /// Reset any internal state within this [`ExecutionPlan`].
441    ///
442    /// This method is called when an [`ExecutionPlan`] needs to be re-executed,
443    /// such as in recursive queries. Unlike [`ExecutionPlan::replace_children`], this method
444    /// ensures that any stateful components (e.g., [`DynamicFilterPhysicalExpr`])
445    /// are reset to their initial state.
446    ///
447    /// The default implementation simply calls [`ExecutionPlan::replace_children`] with the existing children,
448    /// effectively creating a new instance of the [`ExecutionPlan`] with the same children but without
449    /// necessarily resetting any internal state. Implementations that require resetting of some
450    /// internal state should override this method to provide the necessary logic.
451    ///
452    /// This method should *not* reset state recursively for children, as it is expected that
453    /// it will be called from within a walk of the execution plan tree so that it will be called on each child later
454    /// or was already called on each child.
455    ///
456    /// Note to implementers: unlike [`ExecutionPlan::replace_children`] this method does not accept new children as an argument,
457    /// thus it is expected that any cached plan properties will remain valid after the reset.
458    ///
459    /// [`DynamicFilterPhysicalExpr`]: datafusion_physical_expr::expressions::DynamicFilterPhysicalExpr
460    fn reset_state(self: Arc<Self>) -> Result<Arc<dyn ExecutionPlan>> {
461        let children = self.children().into_iter().cloned().collect();
462        self.replace_children(
463            children,
464            ReplaceChildrenOptions::new(ChildrenPropertiesMode::Keep),
465        )
466    }
467
468    /// If supported, attempt to increase the partitioning of this `ExecutionPlan` to
469    /// produce `target_partitions` partitions.
470    ///
471    /// If the `ExecutionPlan` does not support changing its partitioning,
472    /// returns `Ok(None)` (the default).
473    ///
474    /// If the `ExecutionPlan` can increase its partitioning, but not to
475    /// `target_partitions`, it may return an ExecutionPlan with fewer
476    /// partitions. This might happen, for example, if each new partition would
477    /// be too small to be efficiently processed individually.
478    ///
479    /// The DataFusion optimizer attempts to use as many threads as possible by
480    /// repartitioning its inputs to match the target number of threads
481    /// available (`target_partitions`). Some data sources, such as the built in
482    /// CSV and Parquet readers, implement this method as they are able to read
483    /// from their input files in parallel, regardless of how the source data is
484    /// split amongst files.
485    fn repartitioned(
486        &self,
487        _target_partitions: usize,
488        _config: &ConfigOptions,
489    ) -> Result<Option<Arc<dyn ExecutionPlan>>> {
490        Ok(None)
491    }
492
493    /// Begin execution of `partition`, returning a [`Stream`] of
494    /// [`RecordBatch`]es.
495    ///
496    /// # Notes
497    ///
498    /// The `execute` method itself is not `async` but it returns an `async`
499    /// [`futures::stream::Stream`]. This `Stream` should incrementally compute
500    /// the output, `RecordBatch` by `RecordBatch` (in a streaming fashion).
501    /// Most `ExecutionPlan`s should not do any work before the first
502    /// `RecordBatch` is requested from the stream.
503    ///
504    /// [`RecordBatchStreamAdapter`] can be used to convert an `async`
505    /// [`Stream`] into a [`SendableRecordBatchStream`].
506    ///
507    /// Using `async` `Streams` allows for network I/O during execution and
508    /// takes advantage of Rust's built in support for `async` continuations and
509    /// crate ecosystem.
510    ///
511    /// [`Stream`]: futures::stream::Stream
512    /// [`StreamExt`]: futures::stream::StreamExt
513    /// [`TryStreamExt`]: futures::stream::TryStreamExt
514    /// [`RecordBatchStreamAdapter`]: crate::stream::RecordBatchStreamAdapter
515    ///
516    /// # Error handling
517    ///
518    /// Any error that occurs during execution is sent as an `Err` in the output
519    /// stream.
520    ///
521    /// `ExecutionPlan` implementations in DataFusion cancel additional work
522    /// immediately once an error occurs. The rationale is that if the overall
523    /// query will return an error,  any additional work such as continued
524    /// polling of inputs will be wasted as it will be thrown away.
525    ///
526    /// # Cancellation / Aborting Execution
527    ///
528    /// The [`Stream`] that is returned must ensure that any allocated resources
529    /// are freed when the stream itself is dropped. This is particularly
530    /// important for [`spawn`]ed tasks or threads. Unless care is taken to
531    /// "abort" such tasks, they may continue to consume resources even after
532    /// the plan is dropped, generating intermediate results that are never
533    /// used.
534    /// Thus, [`spawn`] is disallowed, and instead use [`SpawnedTask`].
535    ///
536    /// To enable timely cancellation, the [`Stream`] that is returned must not
537    /// block the CPU indefinitely and must yield back to the tokio runtime regularly.
538    /// In a typical [`ExecutionPlan`], this automatically happens unless there are
539    /// special circumstances; e.g. when the computational complexity of processing a
540    /// batch is superlinear. See this [general guideline][async-guideline] for more context
541    /// on this point, which explains why one should avoid spending a long time without
542    /// reaching an `await`/yield point in asynchronous runtimes.
543    /// This can be achieved by using the utilities from the [`coop`](crate::coop) module, by
544    /// manually returning [`Poll::Pending`] and setting up wakers appropriately, or by calling
545    /// [`tokio::task::yield_now()`] when appropriate.
546    /// In special cases that warrant manual yielding, determination for "regularly" may be
547    /// made using the [Tokio task budget](https://docs.rs/tokio/latest/tokio/task/coop/index.html),
548    /// a timer (being careful with the overhead-heavy system call needed to take the time), or by
549    /// counting rows or batches.
550    ///
551    /// The [cancellation benchmark] tracks some cases of how quickly queries can
552    /// be cancelled.
553    ///
554    /// For more details see [`SpawnedTask`], [`JoinSet`] and [`RecordBatchReceiverStreamBuilder`]
555    /// for structures to help ensure all background tasks are cancelled.
556    ///
557    /// [`spawn`]: tokio::task::spawn
558    /// [cancellation benchmark]: https://github.com/apache/datafusion/blob/main/benchmarks/README.md#cancellation
559    /// [`JoinSet`]: datafusion_common_runtime::JoinSet
560    /// [`SpawnedTask`]: datafusion_common_runtime::SpawnedTask
561    /// [`RecordBatchReceiverStreamBuilder`]: crate::stream::RecordBatchReceiverStreamBuilder
562    /// [`Poll::Pending`]: std::task::Poll::Pending
563    /// [async-guideline]: https://ryhl.io/blog/async-what-is-blocking/
564    ///
565    /// # Implementation Examples
566    ///
567    /// While `async` `Stream`s have a non trivial learning curve, the
568    /// [`futures`] crate provides [`StreamExt`] and [`TryStreamExt`]
569    /// which help simplify many common operations.
570    ///
571    /// Here are some common patterns:
572    ///
573    /// ## Return Precomputed `RecordBatch`
574    ///
575    /// We can return a precomputed `RecordBatch` as a `Stream`:
576    ///
577    /// ```
578    /// # use std::sync::Arc;
579    /// # use arrow::array::RecordBatch;
580    /// # use arrow::datatypes::SchemaRef;
581    /// # use datafusion_common::Result;
582    /// # use datafusion_execution::{SendableRecordBatchStream, TaskContext};
583    /// # use datafusion_physical_plan::memory::MemoryStream;
584    /// # use datafusion_physical_plan::stream::RecordBatchStreamAdapter;
585    /// struct MyPlan {
586    ///     batch: RecordBatch,
587    /// }
588    ///
589    /// impl MyPlan {
590    ///     fn execute(
591    ///         &self,
592    ///         partition: usize,
593    ///         context: Arc<TaskContext>,
594    ///     ) -> Result<SendableRecordBatchStream> {
595    ///         // use functions from futures crate to convert the batch into a stream
596    ///         let fut = futures::future::ready(Ok(self.batch.clone()));
597    ///         let stream = futures::stream::once(fut);
598    ///         Ok(Box::pin(RecordBatchStreamAdapter::new(
599    ///             self.batch.schema(),
600    ///             stream,
601    ///         )))
602    ///     }
603    /// }
604    /// ```
605    ///
606    /// ## Lazily (async) Compute `RecordBatch`
607    ///
608    /// We can also lazily compute a `RecordBatch` when the returned `Stream` is polled
609    ///
610    /// ```
611    /// # use std::sync::Arc;
612    /// # use arrow::array::RecordBatch;
613    /// # use arrow::datatypes::SchemaRef;
614    /// # use datafusion_common::Result;
615    /// # use datafusion_execution::{SendableRecordBatchStream, TaskContext};
616    /// # use datafusion_physical_plan::memory::MemoryStream;
617    /// # use datafusion_physical_plan::stream::RecordBatchStreamAdapter;
618    /// struct MyPlan {
619    ///     schema: SchemaRef,
620    /// }
621    ///
622    /// /// Returns a single batch when the returned stream is polled
623    /// async fn get_batch() -> Result<RecordBatch> {
624    ///     todo!()
625    /// }
626    ///
627    /// impl MyPlan {
628    ///     fn execute(
629    ///         &self,
630    ///         partition: usize,
631    ///         context: Arc<TaskContext>,
632    ///     ) -> Result<SendableRecordBatchStream> {
633    ///         let fut = get_batch();
634    ///         let stream = futures::stream::once(fut);
635    ///         Ok(Box::pin(RecordBatchStreamAdapter::new(
636    ///             self.schema.clone(),
637    ///             stream,
638    ///         )))
639    ///     }
640    /// }
641    /// ```
642    ///
643    /// ## Lazily (async) create a Stream
644    ///
645    /// If you need to create the return `Stream` using an `async` function,
646    /// you can do so by flattening the result:
647    ///
648    /// ```
649    /// # use std::sync::Arc;
650    /// # use arrow::array::RecordBatch;
651    /// # use arrow::datatypes::SchemaRef;
652    /// # use futures::TryStreamExt;
653    /// # use datafusion_common::Result;
654    /// # use datafusion_execution::{SendableRecordBatchStream, TaskContext};
655    /// # use datafusion_physical_plan::memory::MemoryStream;
656    /// # use datafusion_physical_plan::stream::RecordBatchStreamAdapter;
657    /// struct MyPlan {
658    ///     schema: SchemaRef,
659    /// }
660    ///
661    /// /// async function that returns a stream
662    /// async fn get_batch_stream() -> Result<SendableRecordBatchStream> {
663    ///     todo!()
664    /// }
665    ///
666    /// impl MyPlan {
667    ///     fn execute(
668    ///         &self,
669    ///         partition: usize,
670    ///         context: Arc<TaskContext>,
671    ///     ) -> Result<SendableRecordBatchStream> {
672    ///         // A future that yields a stream
673    ///         let fut = get_batch_stream();
674    ///         // Use TryStreamExt::try_flatten to flatten the stream of streams
675    ///         let stream = futures::stream::once(fut).try_flatten();
676    ///         Ok(Box::pin(RecordBatchStreamAdapter::new(
677    ///             self.schema.clone(),
678    ///             stream,
679    ///         )))
680    ///     }
681    /// }
682    /// ```
683    fn execute(
684        &self,
685        partition: usize,
686        context: Arc<TaskContext>,
687    ) -> Result<SendableRecordBatchStream>;
688
689    /// Return a snapshot of the set of [`Metric`]s for this
690    /// [`ExecutionPlan`]. If no `Metric`s are available, return None.
691    ///
692    /// While the values of the metrics in the returned
693    /// [`MetricsSet`]s may change as execution progresses, the
694    /// specific metrics will not.
695    ///
696    /// New metrics may be registered during execution, including while streams
697    /// returned by [`Self::execute`] are being polled. Call again to obtain
698    /// metrics registered since the previous snapshot.
699    fn metrics(&self) -> Option<MetricsSet> {
700        None
701    }
702
703    /// Returns statistics for a specific partition of this `ExecutionPlan` node.
704    ///
705    /// Deprecated: use [`StatisticsContext::compute`] instead.
706    ///
707    /// [`StatisticsContext::compute`]: crate::statistics::StatisticsContext::compute
708    #[deprecated(since = "55.0.0", note = "Use StatisticsContext::compute instead")]
709    fn partition_statistics(&self, partition: Option<usize>) -> Result<Arc<Statistics>> {
710        if let Some(idx) = partition {
711            // Validate partition index
712            let partition_count = self.properties().partitioning.partition_count();
713            assert_or_internal_err!(
714                idx < partition_count,
715                "Invalid partition index: {}, the partition count is {}",
716                idx,
717                partition_count
718            );
719        }
720        Ok(Arc::new(Statistics::new_unknown(&self.schema())))
721    }
722
723    /// Returns statistics for a specific partition of this `ExecutionPlan` node,
724    /// given pre-computed child statistics.
725    ///
726    /// If statistics are not available, should return [`Statistics::new_unknown`]
727    /// (the default), not an error.
728    /// If `args.partition()` is `None`, it returns statistics for all partitions.
729    ///
730    /// Implementations should not call [`StatisticsContext::compute`] from within
731    /// this method; child statistics are provided via `input_stats`.
732    ///
733    /// Use [`StatisticsContext::compute`] to initiate a full plan-tree walk.
734    ///
735    /// [`StatisticsContext::compute`]: crate::statistics::StatisticsContext::compute
736    fn statistics_from_inputs(
737        &self,
738        _input_stats: &[Arc<Statistics>],
739        args: &StatisticsArgs,
740    ) -> Result<Arc<Statistics>> {
741        #[expect(deprecated)]
742        self.partition_statistics(args.partition())
743    }
744
745    /// Returns, per child, which statistics the [`StatisticsContext`] should resolve
746    /// before calling [`Self::statistics_from_inputs`].
747    ///
748    /// One entry per child (same order as [`Self::children`]): [`ChildStats::At`]
749    /// requests the child's statistics at a partition (`None` = overall);
750    /// [`ChildStats::Skip`] omits a child whose statistics this node does not need
751    /// (a `Statistics::new_unknown` placeholder fills its `input_stats` slot).
752    ///
753    /// The default skips every child, so a node that derives nothing from its
754    /// children (for example one that only overrides the deprecated
755    /// [`Self::partition_statistics`]) triggers no child traversal. A node that reads
756    /// `input_stats` in [`Self::statistics_from_inputs`] must override this to declare
757    /// the children it uses.
758    ///
759    /// [`StatisticsContext`]: crate::statistics::StatisticsContext
760    fn child_stats_requests(&self, _partition: Option<usize>) -> Vec<ChildStats> {
761        self.children().iter().map(|_| ChildStats::Skip).collect()
762    }
763
764    /// Returns `true` if a limit can be safely pushed down through this
765    /// `ExecutionPlan` node.
766    ///
767    /// DataFusion's own operators still return the same values as before, so
768    /// a wrapper that forwards this to its input keeps working.
769    #[deprecated(
770        since = "56.0.0",
771        note = "implement `limit_behavior` instead; the default `limit_behavior` reads this"
772    )]
773    fn supports_limit_pushdown(&self) -> bool {
774        false
775    }
776
777    /// What a row limit (`LIMIT` / `OFFSET`) on this node's output means for
778    /// its input. The optimizer rules that move limits read only this; see
779    /// [`LimitBehavior`].
780    ///
781    /// The default keeps the behavior of nodes that still implement the
782    /// deprecated [`Self::supports_limit_pushdown`]: [`LimitBehavior::Stops`]
783    /// if it returns `false`, otherwise [`LimitBehavior::MoveToInput`] when
784    /// [`Self::cardinality_effect`] is [`CardinalityEffect::Equal`] and
785    /// [`LimitBehavior::CopyToChildren`] when it is not.
786    fn limit_behavior(&self) -> LimitBehavior {
787        #[expect(deprecated)]
788        let supports_limit_pushdown = self.supports_limit_pushdown();
789        if !supports_limit_pushdown {
790            return LimitBehavior::Stops;
791        }
792        match self.cardinality_effect() {
793            CardinalityEffect::Equal => LimitBehavior::MoveToInput,
794            _ => LimitBehavior::CopyToChildren,
795        }
796    }
797
798    /// Returns a fetching variant of this `ExecutionPlan` node, if it supports
799    /// fetch limits. Returns `None` otherwise.
800    ///
801    /// See physical optimizer rule [`limit_pushdown`] for details.
802    ///
803    /// [`limit_pushdown`]: https://docs.rs/datafusion/latest/datafusion/physical_optimizer/limit_pushdown/index.html
804    fn with_fetch(&self, _limit: Option<usize>) -> Option<Arc<dyn ExecutionPlan>> {
805        None
806    }
807
808    /// Gets the fetch count for the operator, `None` means there is no fetch.
809    fn fetch(&self) -> Option<usize> {
810        None
811    }
812
813    /// Gets the effect on cardinality, if known
814    fn cardinality_effect(&self) -> CardinalityEffect {
815        CardinalityEffect::Unknown
816    }
817
818    /// Attempts to push down the given projection into the input of this `ExecutionPlan`.
819    ///
820    /// If the operator supports this optimization, the resulting plan will be:
821    /// `self_new <- projection <- source`, starting from `projection <- self <- source`.
822    /// Otherwise, it returns the current `ExecutionPlan` as-is.
823    ///
824    /// Returns `Ok(Some(...))` if pushdown is applied, `Ok(None)` if it is not supported
825    /// or not possible, or `Err` on failure.
826    fn try_swapping_with_projection(
827        &self,
828        _projection: &ProjectionExec,
829    ) -> Result<Option<Arc<dyn ExecutionPlan>>> {
830        Ok(None)
831    }
832
833    /// Collect filters that this node can push down to its children.
834    /// Filters that are being pushed down from parents are passed in,
835    /// and the node may generate additional filters to push down.
836    /// For example, given the plan FilterExec -> HashJoinExec -> DataSourceExec,
837    /// what will happen is that we recurse down the plan calling `ExecutionPlan::gather_filters_for_pushdown`:
838    /// 1. `FilterExec::gather_filters_for_pushdown` is called with no parent
839    ///    filters so it only returns that `FilterExec` wants to push down its own predicate.
840    /// 2. `HashJoinExec::gather_filters_for_pushdown` is called with the filter from
841    ///    `FilterExec`, which it only allows to push down to one side of the join (unless it's on the join key)
842    ///    but it also adds its own filters (e.g. pushing down a bloom filter of the hash table to the scan side of the join).
843    /// 3. `DataSourceExec::gather_filters_for_pushdown` is called with both filters from `HashJoinExec`
844    ///    and `FilterExec`, however `DataSourceExec::gather_filters_for_pushdown` doesn't actually do anything
845    ///    since it has no children and no additional filters to push down.
846    ///    It's only once [`ExecutionPlan::handle_child_pushdown_result`] is called on `DataSourceExec` as we recurse
847    ///    up the plan that `DataSourceExec` can actually bind the filters.
848    ///
849    /// The default implementation bars all parent filters from being pushed down and adds no new filters.
850    /// This is the safest option, making filter pushdown opt-in on a per-node basis.
851    ///
852    /// There are two different phases in filter pushdown, which some operators may handle the same and some differently.
853    /// Depending on the phase the operator may or may not be allowed to modify the plan.
854    /// See [`FilterPushdownPhase`] for more details.
855    ///
856    /// Implementations must preserve the order of `parent_filters` in the
857    /// returned child [`FilterDescription`]: each child parent-filter result is
858    /// matched back to the corresponding input parent filter by position.
859    /// Unsupported filters should therefore be marked unsupported in place,
860    /// rather than removed or appended after supported filters.
861    fn gather_filters_for_pushdown(
862        &self,
863        _phase: FilterPushdownPhase,
864        parent_filters: Vec<Arc<dyn PhysicalExpr>>,
865        _config: &ConfigOptions,
866    ) -> Result<FilterDescription> {
867        Ok(FilterDescription::all_unsupported(
868            &parent_filters,
869            &self.children(),
870        ))
871    }
872
873    /// Handle the result of a child pushdown.
874    ///
875    /// This method is called as we recurse back up the plan tree after pushing
876    /// filters down to child nodes via [`ExecutionPlan::gather_filters_for_pushdown`].
877    /// It allows the current node to process the results of filter pushdown from
878    /// its children, deciding whether to absorb filters, modify the plan, or pass
879    /// filters back up to its parent.
880    ///
881    /// **Purpose and Context:**
882    /// Filter pushdown is a critical optimization in DataFusion that aims to
883    /// reduce the amount of data processed by applying filters as early as
884    /// possible in the query plan. This method is part of the second phase of
885    /// filter pushdown, where results are propagated back up the tree after
886    /// being pushed down. Each node can inspect the pushdown results from its
887    /// children and decide how to handle any unapplied filters, potentially
888    /// optimizing the plan structure or filter application.
889    ///
890    /// **Behavior in Different Nodes:**
891    /// - For a `DataSourceExec`, this often means absorbing the filters to apply
892    ///   them during the scan phase (late materialization), reducing the data
893    ///   read from the source.
894    /// - A `FilterExec` may absorb any filters its children could not handle,
895    ///   combining them with its own predicate. If no filters remain (i.e., the
896    ///   predicate becomes trivially true), it may remove itself from the plan
897    ///   altogether. It typically marks parent filters as supported, indicating
898    ///   they have been handled.
899    /// - A `HashJoinExec` might ignore the pushdown result if filters need to
900    ///   be applied during the join operation. It passes the parent filters back
901    ///   up wrapped in [`FilterPushdownPropagation::if_any`], discarding
902    ///   any self-filters from children.
903    ///
904    /// **Example Walkthrough:**
905    /// Consider a query plan: `FilterExec (f1) -> HashJoinExec -> DataSourceExec`.
906    /// 1. **Downward Phase (`gather_filters_for_pushdown`):** Starting at
907    ///    `FilterExec`, the filter `f1` is gathered and pushed down to
908    ///    `HashJoinExec`. `HashJoinExec` may allow `f1` to pass to one side of
909    ///    the join or add its own filters (e.g., a min-max filter from the build side),
910    ///    then pushes filters to `DataSourceExec`. `DataSourceExec`, being a leaf node,
911    ///    has no children to push to, so it prepares to handle filters in the
912    ///    upward phase.
913    /// 2. **Upward Phase (`handle_child_pushdown_result`):** Starting at
914    ///    `DataSourceExec`, it absorbs applicable filters from `HashJoinExec`
915    ///    for late materialization during scanning, marking them as supported.
916    ///    `HashJoinExec` receives the result, decides whether to apply any
917    ///    remaining filters during the join, and passes unhandled filters back
918    ///    up to `FilterExec`. `FilterExec` absorbs any unhandled filters,
919    ///    updates its predicate if necessary, or removes itself if the predicate
920    ///    becomes trivial (e.g., `lit(true)`), and marks filters as supported
921    ///    for its parent.
922    ///
923    /// The default implementation is a no-op that passes the result of pushdown
924    /// from the children to its parent transparently, ensuring no filters are
925    /// lost if a node does not override this behavior.
926    ///
927    /// **Notes for Implementation:**
928    /// When returning filters via [`FilterPushdownPropagation`], the order of
929    /// filters need not match the order they were passed in via
930    /// `child_pushdown_result`. However, preserving the order is recommended for
931    /// debugging and ease of reasoning about the resulting plans.
932    ///
933    /// **Helper Methods for Customization:**
934    /// There are various helper methods to simplify implementing this method:
935    /// - [`FilterPushdownPropagation::if_any`]: Marks all parent filters as
936    ///   supported as long as at least one child supports them.
937    /// - [`FilterPushdownPropagation::if_all`]: Marks all parent filters as
938    ///   supported as long as all children support them.
939    /// - [`FilterPushdownPropagation::with_parent_pushdown_result`]: Allows adding filters
940    ///   to the propagation result, indicating which filters are supported by
941    ///   the current node.
942    /// - [`FilterPushdownPropagation::with_updated_node`]: Allows updating the
943    ///   current node in the propagation result, used if the node
944    ///   has modified its plan based on the pushdown results.
945    ///
946    /// **Filter Pushdown Phases:**
947    /// There are two different phases in filter pushdown (`Pre` and others),
948    /// which some operators may handle differently. Depending on the phase, the
949    /// operator may or may not be allowed to modify the plan. See
950    /// [`FilterPushdownPhase`] for more details on phase-specific behavior.
951    ///
952    /// [`PushedDownPredicate::supported`]: crate::filter_pushdown::PushedDownPredicate::supported
953    fn handle_child_pushdown_result(
954        &self,
955        _phase: FilterPushdownPhase,
956        child_pushdown_result: ChildPushdownResult,
957        _config: &ConfigOptions,
958    ) -> Result<FilterPushdownPropagation<Arc<dyn ExecutionPlan>>> {
959        Ok(FilterPushdownPropagation::if_all(child_pushdown_result))
960    }
961
962    /// Injects arbitrary run-time state into this execution plan, returning a new plan
963    /// instance that incorporates that state *if* it is relevant to the concrete
964    /// node implementation.
965    ///
966    /// This is a generic entry point: the `state` can be any type wrapped in
967    /// `Arc<dyn Any + Send + Sync>`.  A node that cares about the state should
968    /// down-cast it to the concrete type it expects and, if successful, return a
969    /// modified copy of itself that captures the provided value.  If the state is
970    /// not applicable, the default behaviour is to return `None` so that parent
971    /// nodes can continue propagating the attempt further down the plan tree.
972    ///
973    /// For example, [`WorkTableExec`](crate::work_table::WorkTableExec)
974    /// down-casts the supplied state to an `Arc<WorkTable>`
975    /// in order to wire up the working table used during recursive-CTE execution.
976    /// Similar patterns can be followed by custom nodes that need late-bound
977    /// dependencies or shared state.
978    fn with_new_state(
979        &self,
980        _state: Arc<dyn Any + Send + Sync>,
981    ) -> Option<Arc<dyn ExecutionPlan>> {
982        None
983    }
984
985    /// Try to push down sort ordering requirements to this node.
986    ///
987    /// This method is called during sort pushdown optimization to determine if this
988    /// node can optimize for a requested sort ordering. Implementations should:
989    ///
990    /// - Return [`SortOrderPushdownResult::Exact`] if the node can guarantee the exact
991    ///   ordering (allowing the Sort operator to be removed)
992    /// - Return [`SortOrderPushdownResult::Inexact`] if the node can optimize for the
993    ///   ordering but cannot guarantee perfect sorting (Sort operator is kept)
994    /// - Return [`SortOrderPushdownResult::Unsupported`] if the node cannot optimize
995    ///   for the ordering
996    ///
997    /// For transparent nodes (that preserve ordering), implement this to delegate to
998    /// children and wrap the result with a new instance of this node.
999    ///
1000    /// Default implementation returns `Unsupported`.
1001    fn try_pushdown_sort(
1002        &self,
1003        _order: &[PhysicalSortExpr],
1004    ) -> Result<SortOrderPushdownResult<Arc<dyn ExecutionPlan>>> {
1005        Ok(SortOrderPushdownResult::Unsupported)
1006    }
1007
1008    /// Returns a variant of this `ExecutionPlan` that is aware of order-sensitivity.
1009    ///
1010    /// No longer called by DataFusion: a data source that advertises an output
1011    /// ordering always preserves it, so no optimizer rule needs to request it.
1012    #[deprecated(
1013        since = "56.0.0",
1014        note = "no longer called: a scan that advertises an output ordering always preserves it"
1015    )]
1016    fn with_preserve_order(
1017        &self,
1018        _preserve_order: bool,
1019    ) -> Option<Arc<dyn ExecutionPlan>> {
1020        None
1021    }
1022
1023    /// Serialize this plan to its protobuf representation, if it knows how.
1024    ///
1025    /// This is the `ExecutionPlan` analog of
1026    /// [`PhysicalExpr::try_to_proto`].
1027    ///
1028    /// * `Ok(None)` (the default) — "I don't serialize myself"; the caller
1029    ///   (`datafusion-proto`) falls back to the central downcast chain. Every
1030    ///   un-migrated plan keeps its existing behavior.
1031    /// * `Ok(Some(node))` — fully serialized; the caller must not fall back.
1032    /// * `Err(_)` — a real failure (e.g. a child failed to serialize).
1033    ///
1034    /// Only *self-contained* plans should override this — see [`crate::proto`]
1035    /// for the session-dependency boundary.
1036    #[cfg(feature = "proto")]
1037    fn try_to_proto(
1038        &self,
1039        _ctx: &crate::proto::ExecutionPlanEncodeCtx<'_>,
1040    ) -> Result<Option<datafusion_proto_models::protobuf::PhysicalPlanNode>> {
1041        Ok(None)
1042    }
1043}
1044
1045/// Options for [`ExecutionPlan::replace_children`]
1046#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1047pub struct ReplaceChildrenOptions {
1048    /// Describes how plan properties should be handled for the replacement
1049    /// children.
1050    pub children_properties: ChildrenPropertiesMode,
1051}
1052
1053impl ReplaceChildrenOptions {
1054    /// Create new options for [`ExecutionPlan::replace_children`].
1055    pub const fn new(children_properties: ChildrenPropertiesMode) -> Self {
1056        Self {
1057            children_properties,
1058        }
1059    }
1060}
1061
1062/// Indicates whether the plan properties of the new children must be recomputed.
1063///
1064/// Part of [`ReplaceChildrenOptions`].
1065#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1066pub enum ChildrenPropertiesMode {
1067    /// The plan properties of the new children are identical to the properties
1068    /// of the existing children, so we can skip recomputation.
1069    Keep,
1070    /// The plan properties of the new children are different from the properties
1071    /// of the existing children, so we must recompute the properties from scratch.
1072    Recompute,
1073}
1074
1075/// Allows a type to be treated as a reference to an
1076/// [`Arc<dyn PhysicalExpr>`].
1077///
1078/// Used by [`apply_expression_roots`].
1079pub trait AsPhysicalExprRef {
1080    /// Returns the referenced physical expression.
1081    fn as_physical_expr_ref(&self) -> &Arc<dyn PhysicalExpr>;
1082}
1083
1084/// Allows an [`Arc<dyn PhysicalExpr>`] to be treated as a reference to itself.
1085///
1086/// This is needed because `Arc<dyn PhysicalExpr>` does not implement
1087/// `AsRef<Arc<dyn PhysicalExpr>>`.
1088impl AsPhysicalExprRef for Arc<dyn PhysicalExpr> {
1089    fn as_physical_expr_ref(&self) -> &Arc<dyn PhysicalExpr> {
1090        self
1091    }
1092}
1093
1094/// Allows a [`ProjectionExpr`] to be treated as a reference to its
1095/// [`Arc<dyn PhysicalExpr>`].
1096impl AsPhysicalExprRef for ProjectionExpr {
1097    fn as_physical_expr_ref(&self) -> &Arc<dyn PhysicalExpr> {
1098        self.as_ref()
1099    }
1100}
1101
1102impl<T> AsPhysicalExprRef for &T
1103where
1104    T: AsPhysicalExprRef + ?Sized,
1105{
1106    fn as_physical_expr_ref(&self) -> &Arc<dyn PhysicalExpr> {
1107        (*self).as_physical_expr_ref()
1108    }
1109}
1110
1111/// Applies `f` to a shallow sequence of physical expression roots.
1112///
1113/// [`TreeNodeRecursion::Stop`] stops iteration and is returned immediately.
1114/// [`TreeNodeRecursion::Jump`] is normalized to [`TreeNodeRecursion::Continue`]
1115/// because this function does not visit expression children.
1116pub fn apply_expression_roots<I>(
1117    roots: I,
1118    f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> Result<TreeNodeRecursion>,
1119) -> Result<TreeNodeRecursion>
1120where
1121    I: IntoIterator,
1122    I::Item: AsPhysicalExprRef,
1123{
1124    for root in roots {
1125        match f(root.as_physical_expr_ref())? {
1126            TreeNodeRecursion::Stop => return Ok(TreeNodeRecursion::Stop),
1127            TreeNodeRecursion::Continue | TreeNodeRecursion::Jump => {}
1128        }
1129    }
1130    Ok(TreeNodeRecursion::Continue)
1131}
1132
1133/// Returns whether `plan` contains a physical expression with `expression_id`.
1134///
1135/// This traverses both the execution plan and the children of each expression root
1136/// reported by [`ExecutionPlan::apply_expressions`].
1137///
1138/// Producers of dynamic filters use this to find out whether anything downstream
1139/// holds the filter they pushed, since a node that replies
1140/// [`PushedDown::No`](crate::filter_pushdown::PushedDown::No) may still retain it
1141/// for statistics pruning.
1142pub fn plan_contains_expression_id(
1143    plan: &Arc<dyn ExecutionPlan>,
1144    expression_id: u64,
1145) -> Result<bool> {
1146    let mut found = false;
1147    plan.apply(|node| {
1148        node.apply_expressions(&mut |root| {
1149            root.apply(|expr| {
1150                if expr.expression_id() == Some(expression_id) {
1151                    found = true;
1152                    Ok(TreeNodeRecursion::Stop)
1153                } else {
1154                    Ok(TreeNodeRecursion::Continue)
1155                }
1156            })
1157        })?;
1158
1159        Ok(if found {
1160            TreeNodeRecursion::Stop
1161        } else {
1162            TreeNodeRecursion::Continue
1163        })
1164    })?;
1165    Ok(found)
1166}
1167
1168impl dyn ExecutionPlan {
1169    /// Returns `true` if the plan is of type `T`.
1170    ///
1171    /// If this plan provides a [`ExecutionPlan::downcast_delegate`], delegates
1172    /// to it.
1173    ///
1174    /// Prefer this over `downcast_ref::<T>().is_some()`. Works correctly when
1175    /// called on `Arc<dyn ExecutionPlan>` via auto-deref.
1176    pub fn is<T: ExecutionPlan>(&self) -> bool {
1177        match self.downcast_delegate() {
1178            Some(delegate) => delegate.is::<T>(),
1179            None => (self as &dyn Any).is::<T>(),
1180        }
1181    }
1182
1183    /// Attempts to downcast this plan to a concrete type `T`, returning `None`
1184    /// if the plan is not of that type.
1185    ///
1186    /// If this plan provides a [`ExecutionPlan::downcast_delegate`], delegates
1187    /// to it.
1188    ///
1189    /// Works correctly when called on `Arc<dyn ExecutionPlan>` via auto-deref,
1190    /// unlike `(&arc as &dyn Any).downcast_ref::<T>()` which would attempt to
1191    /// downcast the `Arc` itself.
1192    pub fn downcast_ref<T: ExecutionPlan>(&self) -> Option<&T> {
1193        match self.downcast_delegate() {
1194            Some(delegate) => delegate.downcast_ref::<T>(),
1195            None => (self as &dyn Any).downcast_ref(),
1196        }
1197    }
1198}
1199
1200/// [`ExecutionPlan`] Invariant Level
1201///
1202/// What set of assertions ([Invariant]s)  holds for a particular `ExecutionPlan`
1203///
1204/// [Invariant]: https://en.wikipedia.org/wiki/Invariant_(mathematics)#Invariants_in_computer_science
1205#[derive(Clone, Copy)]
1206pub enum InvariantLevel {
1207    /// Invariants that are always true for the [`ExecutionPlan`] node
1208    /// such as the number of expected children.
1209    Always,
1210    /// Invariants that must hold true for the [`ExecutionPlan`] node
1211    /// to be "executable", such as ordering and/or distribution requirements
1212    /// being fulfilled.
1213    Executable,
1214}
1215
1216/// Extension trait provides an easy API to fetch various properties of
1217/// [`ExecutionPlan`] objects based on [`ExecutionPlan::properties`].
1218pub trait ExecutionPlanProperties {
1219    /// Specifies how the output of this `ExecutionPlan` is split into
1220    /// partitions.
1221    fn output_partitioning(&self) -> &Partitioning;
1222
1223    /// If the output of this `ExecutionPlan` within each partition is sorted,
1224    /// returns `Some(keys)` describing the ordering. A `None` return value
1225    /// indicates no assumptions should be made on the output ordering.
1226    ///
1227    /// For example, `SortExec` (obviously) produces sorted output as does
1228    /// `SortPreservingMergeStream`. Less obviously, `Projection` produces sorted
1229    /// output if its input is sorted as it does not reorder the input rows.
1230    fn output_ordering(&self) -> Option<&LexOrdering>;
1231
1232    /// Boundedness information of the stream corresponding to this `ExecutionPlan`.
1233    /// For more details, see [`Boundedness`].
1234    fn boundedness(&self) -> Boundedness;
1235
1236    /// Indicates how the stream of this `ExecutionPlan` emits its results.
1237    /// For more details, see [`EmissionType`].
1238    fn pipeline_behavior(&self) -> EmissionType;
1239
1240    /// Get the [`EquivalenceProperties`] within the plan.
1241    ///
1242    /// Equivalence properties tell DataFusion what columns are known to be
1243    /// equal, during various optimization passes. By default, this returns "no
1244    /// known equivalences" which is always correct, but may cause DataFusion to
1245    /// unnecessarily resort data.
1246    ///
1247    /// If this ExecutionPlan makes no changes to the schema of the rows flowing
1248    /// through it or how columns within each row relate to each other, it
1249    /// should return the equivalence properties of its input. For
1250    /// example, since [`FilterExec`] may remove rows from its input, but does not
1251    /// otherwise modify them, it preserves its input equivalence properties.
1252    /// However, since `ProjectionExec` may calculate derived expressions, it
1253    /// needs special handling.
1254    ///
1255    /// See also [`ExecutionPlan::maintains_input_order`] and [`Self::output_ordering`]
1256    /// for related concepts.
1257    ///
1258    /// [`FilterExec`]: crate::filter::FilterExec
1259    fn equivalence_properties(&self) -> &EquivalenceProperties;
1260}
1261
1262impl ExecutionPlanProperties for Arc<dyn ExecutionPlan> {
1263    fn output_partitioning(&self) -> &Partitioning {
1264        self.properties().output_partitioning()
1265    }
1266
1267    fn output_ordering(&self) -> Option<&LexOrdering> {
1268        self.properties().output_ordering()
1269    }
1270
1271    fn boundedness(&self) -> Boundedness {
1272        self.properties().boundedness
1273    }
1274
1275    fn pipeline_behavior(&self) -> EmissionType {
1276        self.properties().emission_type
1277    }
1278
1279    fn equivalence_properties(&self) -> &EquivalenceProperties {
1280        self.properties().equivalence_properties()
1281    }
1282}
1283
1284impl ExecutionPlanProperties for &dyn ExecutionPlan {
1285    fn output_partitioning(&self) -> &Partitioning {
1286        self.properties().output_partitioning()
1287    }
1288
1289    fn output_ordering(&self) -> Option<&LexOrdering> {
1290        self.properties().output_ordering()
1291    }
1292
1293    fn boundedness(&self) -> Boundedness {
1294        self.properties().boundedness
1295    }
1296
1297    fn pipeline_behavior(&self) -> EmissionType {
1298        self.properties().emission_type
1299    }
1300
1301    fn equivalence_properties(&self) -> &EquivalenceProperties {
1302        self.properties().equivalence_properties()
1303    }
1304}
1305
1306/// Represents whether a stream of data **generated** by an operator is bounded (finite)
1307/// or unbounded (infinite).
1308///
1309/// This is used to determine whether an execution plan will eventually complete
1310/// processing all its data (bounded) or could potentially run forever (unbounded).
1311///
1312/// For unbounded streams, it also tracks whether the operator requires finite memory
1313/// to process the stream or if memory usage could grow unbounded.
1314///
1315/// Boundedness of the output stream is based on the boundedness of the input stream and the nature of
1316/// the operator. For example, limit or topk with fetch operator can convert an unbounded stream to a bounded stream.
1317#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1318pub enum Boundedness {
1319    /// The data stream is bounded (finite) and will eventually complete
1320    Bounded,
1321    /// The data stream is unbounded (infinite) and could run forever
1322    Unbounded {
1323        /// Whether this operator requires infinite memory to process the unbounded stream.
1324        /// If false, the operator can process an infinite stream with bounded memory.
1325        /// If true, memory usage may grow unbounded while processing the stream.
1326        ///
1327        /// For example, `Median` requires infinite memory to compute the median of an unbounded stream.
1328        /// `Min/Max` requires infinite memory if the stream is unordered, but can be computed with bounded memory if the stream is ordered.
1329        requires_infinite_memory: bool,
1330    },
1331}
1332
1333impl Boundedness {
1334    pub fn is_unbounded(&self) -> bool {
1335        matches!(self, Boundedness::Unbounded { .. })
1336    }
1337}
1338
1339/// Represents how an operator emits its output records.
1340///
1341/// This is used to determine whether an operator emits records incrementally as they arrive,
1342/// only emits a final result at the end, or can do both. Note that it generates the output -- record batch with `batch_size` rows
1343/// but it may still buffer data internally until it has enough data to emit a record batch or the source is exhausted.
1344///
1345/// For example, in the following plan:
1346/// ```text
1347///   SortExec [EmissionType::Final]
1348///     |_ on: [col1 ASC]
1349///     FilterExec [EmissionType::Incremental]
1350///       |_ pred: col2 > 100
1351///       DataSourceExec [EmissionType::Incremental]
1352///         |_ file: "data.csv"
1353/// ```
1354/// - DataSourceExec emits records incrementally as it reads from the file
1355/// - FilterExec processes and emits filtered records incrementally as they arrive
1356/// - SortExec must wait for all input records before it can emit the sorted result,
1357///   since it needs to see all values to determine their final order
1358///
1359/// Left joins can emit both incrementally and finally:
1360/// - Incrementally emit matches as they are found
1361/// - Finally emit non-matches after all input is processed
1362#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1363pub enum EmissionType {
1364    /// Records are emitted incrementally as they arrive and are processed
1365    Incremental,
1366    /// Records are only emitted once all input has been processed
1367    Final,
1368    /// Records can be emitted both incrementally and as a final result
1369    Both,
1370}
1371
1372/// Represents whether an operator's `Stream` has been implemented to actively cooperate with the
1373/// Tokio scheduler or not. Please refer to the [`coop`](crate::coop) module for more details.
1374#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1375pub enum SchedulingType {
1376    /// The stream generated by [`execute`](ExecutionPlan::execute) does not actively participate in
1377    /// cooperative scheduling. This means the implementation of the `Stream` returned by
1378    /// [`ExecutionPlan::execute`] does not contain explicit task budget consumption such as
1379    /// [`tokio::task::coop::consume_budget`].
1380    ///
1381    /// `NonCooperative` is the default value and is acceptable for most operators. Please refer to
1382    /// the [`coop`](crate::coop) module for details on when it may be useful to use
1383    /// `Cooperative` instead.
1384    NonCooperative,
1385    /// The stream generated by [`execute`](ExecutionPlan::execute) actively participates in
1386    /// cooperative scheduling by consuming task budget when it was able to produce a
1387    /// [`RecordBatch`].
1388    Cooperative,
1389}
1390
1391/// Represents how an operator's stream drives [`RecordBatch`] production
1392/// relative to downstream demand.
1393///
1394/// This is execution-topology metadata for optimizers. It distinguishes streams
1395/// whose batch production is driven directly by downstream calls to
1396/// `Stream::poll_next` from streams that may also drive input or output
1397/// production independently, such as by spawning tasks or buffering batches
1398/// ahead of demand.
1399#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1400pub enum EvaluationType {
1401    /// The stream generated by [`execute`](ExecutionPlan::execute) is
1402    /// demand-driven: it produces [`RecordBatch`]es in response to downstream
1403    /// calls to `Stream::poll_next`.
1404    ///
1405    /// Filter, projection, and join operators are examples of lazy operators.
1406    ///
1407    /// Lazy operators are also known as demand-driven operators.
1408    Lazy,
1409    /// The stream generated by [`execute`](ExecutionPlan::execute) may drive
1410    /// input or output [`RecordBatch`] production ahead of, or independently
1411    /// from, downstream calls to `Stream::poll_next`.
1412    ///
1413    /// Eager operators commonly poll input streams from spawned Tokio tasks,
1414    /// buffer batches ahead of demand, or otherwise create an independent
1415    /// child-polling pipeline. Eager work may start when `execute` creates the
1416    /// stream or when the returned stream is first polled; that timing is an
1417    /// implementation detail.
1418    ///
1419    /// Repartition, coalesce partitions, sort-preserving merge, buffer, and
1420    /// analyze operators are examples of eager operators.
1421    ///
1422    /// Eager operators are also known as a data-driven operators.
1423    Eager,
1424}
1425
1426/// Utility to determine an operator's boundedness based on its children's boundedness.
1427///
1428/// Assumes boundedness can be inferred from child operators:
1429/// - Unbounded (requires_infinite_memory: true) takes precedence.
1430/// - Unbounded (requires_infinite_memory: false) is considered next.
1431/// - Otherwise, the operator is bounded.
1432///
1433/// **Note:** This is a general-purpose utility and may not apply to
1434/// all multi-child operators. Ensure your operator's behavior aligns
1435/// with these assumptions before using.
1436pub(crate) fn boundedness_from_children<'a>(
1437    children: impl IntoIterator<Item = &'a Arc<dyn ExecutionPlan>>,
1438) -> Boundedness {
1439    let mut unbounded_with_finite_mem = false;
1440
1441    for child in children {
1442        match child.boundedness() {
1443            Boundedness::Unbounded {
1444                requires_infinite_memory: true,
1445            } => {
1446                return Boundedness::Unbounded {
1447                    requires_infinite_memory: true,
1448                };
1449            }
1450            Boundedness::Unbounded {
1451                requires_infinite_memory: false,
1452            } => {
1453                unbounded_with_finite_mem = true;
1454            }
1455            Boundedness::Bounded => {}
1456        }
1457    }
1458
1459    if unbounded_with_finite_mem {
1460        Boundedness::Unbounded {
1461            requires_infinite_memory: false,
1462        }
1463    } else {
1464        Boundedness::Bounded
1465    }
1466}
1467
1468/// Determines the emission type of an operator based on its children's pipeline behavior.
1469///
1470/// The precedence of emission types is:
1471/// - `Final` has the highest precedence.
1472/// - `Both` is next: if any child emits both incremental and final results, the parent inherits this behavior unless a `Final` is present.
1473/// - `Incremental` is the default if all children emit incremental results.
1474///
1475/// **Note:** This is a general-purpose utility and may not apply to
1476/// all multi-child operators. Verify your operator's behavior aligns
1477/// with these assumptions.
1478pub(crate) fn emission_type_from_children<'a>(
1479    children: impl IntoIterator<Item = &'a Arc<dyn ExecutionPlan>>,
1480) -> EmissionType {
1481    let mut inc_and_final = false;
1482
1483    for child in children {
1484        match child.pipeline_behavior() {
1485            EmissionType::Final => return EmissionType::Final,
1486            EmissionType::Both => inc_and_final = true,
1487            EmissionType::Incremental => {}
1488        }
1489    }
1490
1491    if inc_and_final {
1492        EmissionType::Both
1493    } else {
1494        EmissionType::Incremental
1495    }
1496}
1497
1498/// Stores plan properties used in query optimization.
1499///
1500/// Serves as a cache for these properties, which are often
1501/// expensive to compute.
1502#[derive(Debug, Clone)]
1503pub struct PlanProperties {
1504    /// See [ExecutionPlanProperties::equivalence_properties]
1505    pub eq_properties: EquivalenceProperties,
1506    /// See [ExecutionPlanProperties::output_partitioning]
1507    pub partitioning: Partitioning,
1508    /// See [ExecutionPlanProperties::pipeline_behavior]
1509    pub emission_type: EmissionType,
1510    /// See [ExecutionPlanProperties::boundedness]
1511    pub boundedness: Boundedness,
1512    pub evaluation_type: EvaluationType,
1513    pub scheduling_type: SchedulingType,
1514    /// See [ExecutionPlanProperties::output_ordering]
1515    output_ordering: Option<LexOrdering>,
1516}
1517
1518impl PlanProperties {
1519    /// Construct a new `PlanPropertiesCache` from the
1520    pub fn new(
1521        eq_properties: EquivalenceProperties,
1522        partitioning: Partitioning,
1523        emission_type: EmissionType,
1524        boundedness: Boundedness,
1525    ) -> Self {
1526        // Output ordering can be derived from `eq_properties`.
1527        let output_ordering = eq_properties.output_ordering();
1528        Self {
1529            eq_properties,
1530            partitioning,
1531            emission_type,
1532            boundedness,
1533            evaluation_type: EvaluationType::Lazy,
1534            scheduling_type: SchedulingType::NonCooperative,
1535            output_ordering,
1536        }
1537    }
1538
1539    /// Overwrite output partitioning with its new value.
1540    pub fn with_partitioning(mut self, partitioning: Partitioning) -> Self {
1541        self.partitioning = partitioning;
1542        self
1543    }
1544
1545    /// Set equivalence properties having mut reference.
1546    pub fn set_eq_properties(&mut self, eq_properties: EquivalenceProperties) {
1547        // Changing equivalence properties also changes output ordering, so
1548        // make sure to overwrite it:
1549        self.output_ordering = eq_properties.output_ordering();
1550        self.eq_properties = eq_properties;
1551    }
1552
1553    /// Overwrite equivalence properties with its new value.
1554    pub fn with_eq_properties(mut self, eq_properties: EquivalenceProperties) -> Self {
1555        self.set_eq_properties(eq_properties);
1556        self
1557    }
1558
1559    /// Overwrite boundedness with its new value.
1560    pub fn with_boundedness(mut self, boundedness: Boundedness) -> Self {
1561        self.boundedness = boundedness;
1562        self
1563    }
1564
1565    /// Overwrite emission type with its new value.
1566    pub fn with_emission_type(mut self, emission_type: EmissionType) -> Self {
1567        self.emission_type = emission_type;
1568        self
1569    }
1570
1571    /// Set the [`SchedulingType`].
1572    ///
1573    /// Defaults to [`SchedulingType::NonCooperative`]
1574    pub fn with_scheduling_type(mut self, scheduling_type: SchedulingType) -> Self {
1575        self.scheduling_type = scheduling_type;
1576        self
1577    }
1578
1579    /// Set the [`EvaluationType`].
1580    ///
1581    /// Defaults to [`EvaluationType::Lazy`]
1582    pub fn with_evaluation_type(mut self, drive_type: EvaluationType) -> Self {
1583        self.evaluation_type = drive_type;
1584        self
1585    }
1586
1587    /// Set constraints having mut reference.
1588    pub fn set_constraints(&mut self, constraints: Constraints) {
1589        self.eq_properties.set_constraints(constraints);
1590    }
1591
1592    /// Overwrite constraints with its new value.
1593    pub fn with_constraints(mut self, constraints: Constraints) -> Self {
1594        self.set_constraints(constraints);
1595        self
1596    }
1597
1598    pub fn equivalence_properties(&self) -> &EquivalenceProperties {
1599        &self.eq_properties
1600    }
1601
1602    pub fn output_partitioning(&self) -> &Partitioning {
1603        &self.partitioning
1604    }
1605
1606    pub fn output_ordering(&self) -> Option<&LexOrdering> {
1607        self.output_ordering.as_ref()
1608    }
1609
1610    /// Get schema of the node.
1611    pub(crate) fn schema(&self) -> &SchemaRef {
1612        self.eq_properties.schema()
1613    }
1614}
1615
1616#[derive(Debug)]
1617struct DefaultInvariantChecker<'a> {
1618    plan_name: &'a str,
1619}
1620
1621impl<'a> DefaultInvariantChecker<'a> {
1622    fn new(plan_name: &'a str) -> Self {
1623        Self { plan_name }
1624    }
1625
1626    /// All dynamic expressions must have an expression id.
1627    fn check_dynamic_expression_invariants(
1628        &self,
1629        dynamic_expressions: Vec<Arc<dyn PhysicalExpr>>,
1630    ) -> Result<()> {
1631        let mut produced_ids = HashSet::with_capacity(dynamic_expressions.len());
1632        for expr in dynamic_expressions {
1633            let Some(expression_id) = expr.expression_id() else {
1634                return internal_err!(
1635                    "{}::dynamic_expressions_produced returned an expression without an expression ID",
1636                    self.plan_name
1637                );
1638            };
1639            assert_or_internal_err!(
1640                produced_ids.insert(expression_id),
1641                "{}::dynamic_expressions_produced returned duplicate expression ID {expression_id}",
1642                self.plan_name
1643            );
1644        }
1645        Ok(())
1646    }
1647}
1648
1649macro_rules! check_len {
1650    ($target:expr, $func_name:ident, $expected_len:expr) => {
1651        let actual_len = $target.$func_name().len();
1652        assert_eq_or_internal_err!(
1653            actual_len,
1654            $expected_len,
1655            "{}::{} returned Vec with incorrect size: {} != {}",
1656            $target.name(),
1657            stringify!($func_name),
1658            actual_len,
1659            $expected_len
1660        );
1661    };
1662}
1663
1664/// Checks a set of invariants that apply to all ExecutionPlan implementations.
1665/// Returns an error if the given node does not conform.
1666pub fn check_default_invariants<P: ExecutionPlan + ?Sized>(
1667    plan: &P,
1668    check: InvariantLevel,
1669) -> Result<(), DataFusionError> {
1670    let children_len = plan.children().len();
1671
1672    check_len!(plan, maintains_input_order, children_len);
1673    check_len!(plan, required_input_ordering, children_len);
1674    check_len!(plan, benefits_from_input_partitioning, children_len);
1675
1676    let input_distribution_requirements = plan.input_distribution_requirements();
1677    let children = plan.children();
1678    let checker = DefaultInvariantChecker::new(plan.name());
1679    input_distribution_requirements.check_invariants(
1680        checker.plan_name,
1681        children,
1682        check,
1683    )?;
1684    let dynamic_expressions = plan.dynamic_expressions_produced();
1685    if !dynamic_expressions.is_empty() {
1686        checker.check_dynamic_expression_invariants(dynamic_expressions)?;
1687    }
1688
1689    Ok(())
1690}
1691
1692/// Indicate whether a data exchange is needed for the input of `plan`.
1693///
1694/// This identifies physical operators that redistribute child partitions or
1695/// gather multiple child partitions into one output partition:
1696///
1697/// 1. RepartitionExec for non-round-robin repartitioning
1698/// 2. CoalescePartitionsExec for collapsing multiple partitions into one without ordering guarantee
1699/// 3. SortPreservingMergeExec for collapsing multiple sorted partitions into one with ordering guarantee
1700#[expect(clippy::needless_pass_by_value)]
1701pub fn need_data_exchange(plan: Arc<dyn ExecutionPlan>) -> bool {
1702    if let Some(repartition) = plan.downcast_ref::<RepartitionExec>() {
1703        !matches!(repartition.partitioning(), Partitioning::RoundRobinBatch(_))
1704    } else if let Some(coalesce) = plan.downcast_ref::<CoalescePartitionsExec>() {
1705        coalesce.input().output_partitioning().partition_count() > 1
1706    } else if let Some(sort_preserving_merge) =
1707        plan.downcast_ref::<SortPreservingMergeExec>()
1708    {
1709        sort_preserving_merge
1710            .input()
1711            .output_partitioning()
1712            .partition_count()
1713            > 1
1714    } else {
1715        false
1716    }
1717}
1718
1719/// Returns a plan with the given children, skipping as much work as possible.
1720///
1721/// This helper is the single entry point for "rebuild a plan from new
1722/// children" and applies three layers of short-circuits, from cheapest to
1723/// most expensive:
1724///
1725/// 1. **Same child pointers** — if every `children[i]` is `Arc::ptr_eq` to the
1726///    corresponding existing child, the original `plan` is returned
1727///    unchanged (no allocation, no [`ExecutionPlan::replace_children`]
1728///    call).
1729/// 2. **Same child properties** — if the children's `PlanProperties` Arcs
1730///    match (via [`has_same_children_properties`]), the plan's own
1731///    `PlanProperties` cache can be reused. This calls
1732///    [`ExecutionPlan::replace_children`] with [`ChildrenPropertiesMode::Keep`],
1733///    which swaps the child pointers without recomputing `PlanProperties`.
1734/// 3. **Full recompute** — otherwise, delegate to
1735///    [`ExecutionPlan::replace_children`] with [`ChildrenPropertiesMode::Recompute`],
1736///    which recomputes `PlanProperties` from scratch.
1737///
1738/// The size of `children` must be equal to the size of `ExecutionPlan::children()`.
1739pub fn replace_children_if_necessary(
1740    plan: Arc<dyn ExecutionPlan>,
1741    children: Vec<Arc<dyn ExecutionPlan>>,
1742) -> Result<Arc<dyn ExecutionPlan>> {
1743    let old_children = plan.children();
1744    assert_eq_or_internal_err!(
1745        children.len(),
1746        old_children.len(),
1747        "Wrong number of children"
1748    );
1749    if !children.is_empty() {
1750        // Layer 1: same child pointers → return the plan unchanged.
1751        if children
1752            .iter()
1753            .zip(old_children.iter())
1754            .all(|(c1, c2)| Arc::ptr_eq(c1, c2))
1755        {
1756            return Ok(plan);
1757        }
1758        // Layer 2: same child properties → reuse `PlanProperties` cache.
1759        if has_same_children_properties(plan.as_ref(), &children)? {
1760            return plan.replace_children(
1761                children,
1762                ReplaceChildrenOptions::new(ChildrenPropertiesMode::Keep),
1763            );
1764        }
1765    }
1766    // Layer 3: full recompute.
1767    plan.replace_children(
1768        children,
1769        ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute),
1770    )
1771}
1772
1773#[deprecated(since = "55.0.0", note = "Use `replace_children_if_necessary`")]
1774pub fn with_new_children_if_necessary(
1775    plan: Arc<dyn ExecutionPlan>,
1776    children: Vec<Arc<dyn ExecutionPlan>>,
1777) -> Result<Arc<dyn ExecutionPlan>> {
1778    replace_children_if_necessary(plan, children)
1779}
1780
1781/// Return a [`DisplayableExecutionPlan`] wrapper around an
1782/// [`ExecutionPlan`] which can be displayed in various easier to
1783/// understand ways.
1784///
1785/// See examples on [`DisplayableExecutionPlan`]
1786pub fn displayable(plan: &dyn ExecutionPlan) -> DisplayableExecutionPlan<'_> {
1787    DisplayableExecutionPlan::new(plan)
1788}
1789
1790/// Execute the [ExecutionPlan] and collect the results in memory
1791pub async fn collect(
1792    plan: Arc<dyn ExecutionPlan>,
1793    context: Arc<TaskContext>,
1794) -> Result<Vec<RecordBatch>> {
1795    let stream = execute_stream(plan, context)?;
1796    crate::common::collect(stream).await
1797}
1798
1799/// Execute the [ExecutionPlan] and return a single stream of `RecordBatch`es.
1800///
1801/// See [collect] to buffer the `RecordBatch`es in memory.
1802///
1803/// # Aborting Execution
1804///
1805/// Dropping the stream will abort the execution of the query, and free up
1806/// any allocated resources
1807#[expect(
1808    clippy::needless_pass_by_value,
1809    reason = "Public API that historically takes owned Arcs"
1810)]
1811pub fn execute_stream(
1812    plan: Arc<dyn ExecutionPlan>,
1813    context: Arc<TaskContext>,
1814) -> Result<SendableRecordBatchStream> {
1815    match plan.output_partitioning().partition_count() {
1816        0 => Ok(Box::pin(EmptyRecordBatchStream::new(plan.schema()))),
1817        1 => plan.execute(0, context),
1818        2.. => {
1819            // merge into a single partition
1820            let plan = CoalescePartitionsExec::new(Arc::clone(&plan));
1821            // CoalescePartitionsExec must produce a single partition
1822            assert_eq!(1, plan.properties().output_partitioning().partition_count());
1823            plan.execute(0, context)
1824        }
1825    }
1826}
1827
1828/// Execute the [ExecutionPlan] and collect the results in memory
1829pub async fn collect_partitioned(
1830    plan: Arc<dyn ExecutionPlan>,
1831    context: Arc<TaskContext>,
1832) -> Result<Vec<Vec<RecordBatch>>> {
1833    // Avoid `JoinSet::spawn` for single partition
1834    if plan.output_partitioning().partition_count() == 1 {
1835        let stream = plan.execute(0, context)?;
1836        let batches: Vec<RecordBatch> = stream.try_collect().await?;
1837        return Ok(vec![batches]);
1838    }
1839
1840    let streams = execute_stream_partitioned(plan, context)?;
1841
1842    let mut join_set = JoinSet::new();
1843    // Execute the plan and collect the results into batches.
1844    streams.into_iter().enumerate().for_each(|(idx, stream)| {
1845        join_set.spawn(async move {
1846            let result: Result<Vec<RecordBatch>> = stream.try_collect().await;
1847            (idx, result)
1848        });
1849    });
1850
1851    let mut batches = Vec::with_capacity(join_set.len());
1852    // Note that currently this doesn't identify the thread that panicked
1853    //
1854    // TODO: Replace with [join_next_with_id](https://docs.rs/tokio/latest/tokio/task/struct.JoinSet.html#method.join_next_with_id
1855    // once it is stable
1856    while let Some(result) = join_set.join_next().await {
1857        match result {
1858            Ok((idx, res)) => batches.push((idx, res?)),
1859            Err(e) => {
1860                if e.is_panic() {
1861                    std::panic::resume_unwind(e.into_panic());
1862                } else {
1863                    unreachable!();
1864                }
1865            }
1866        }
1867    }
1868
1869    batches.sort_by_key(|(idx, _)| *idx);
1870    let batches = batches.into_iter().map(|(_, batch)| batch).collect();
1871
1872    Ok(batches)
1873}
1874
1875/// Execute the [ExecutionPlan] and return a vec with one stream per output
1876/// partition
1877///
1878/// # Aborting Execution
1879///
1880/// Dropping the stream will abort the execution of the query, and free up
1881/// any allocated resources
1882#[expect(
1883    clippy::needless_pass_by_value,
1884    reason = "Public API that historically takes owned Arcs"
1885)]
1886pub fn execute_stream_partitioned(
1887    plan: Arc<dyn ExecutionPlan>,
1888    context: Arc<TaskContext>,
1889) -> Result<Vec<SendableRecordBatchStream>> {
1890    let num_partitions = plan.output_partitioning().partition_count();
1891    let mut streams = Vec::with_capacity(num_partitions);
1892    for i in 0..num_partitions {
1893        streams.push(plan.execute(i, Arc::clone(&context))?);
1894    }
1895    Ok(streams)
1896}
1897
1898/// Executes an input stream and ensures that the resulting stream adheres to
1899/// the `not null` constraints specified in the `sink_schema`.
1900///
1901/// # Arguments
1902///
1903/// * `input` - An execution plan
1904/// * `sink_schema` - The schema to be applied to the output stream
1905/// * `partition` - The partition index to be executed
1906/// * `context` - The task context
1907///
1908/// # Returns
1909///
1910/// * `Result<SendableRecordBatchStream>` - A stream of `RecordBatch`es if successful
1911///
1912/// This function first executes the given input plan for the specified partition
1913/// and context. It then checks if there are any columns in the input that might
1914/// violate the `not null` constraints specified in the `sink_schema`. If there are
1915/// such columns, it wraps the resulting stream to enforce the `not null` constraints
1916/// by invoking the [`check_not_null_constraints`] function on each batch of the stream.
1917#[expect(
1918    clippy::needless_pass_by_value,
1919    reason = "Public API that historically takes owned Arcs"
1920)]
1921pub fn execute_input_stream(
1922    input: Arc<dyn ExecutionPlan>,
1923    sink_schema: SchemaRef,
1924    partition: usize,
1925    context: Arc<TaskContext>,
1926) -> Result<SendableRecordBatchStream> {
1927    let input_stream = input.execute(partition, context)?;
1928
1929    debug_assert_eq!(sink_schema.fields().len(), input.schema().fields().len());
1930
1931    // Find input columns that may violate the not null constraint.
1932    let risky_columns: Vec<_> = sink_schema
1933        .fields()
1934        .iter()
1935        .zip(input.schema().fields().iter())
1936        .enumerate()
1937        .filter_map(|(idx, (sink_field, input_field))| {
1938            (!sink_field.is_nullable() && input_field.is_nullable()).then_some(idx)
1939        })
1940        .collect();
1941
1942    if risky_columns.is_empty() {
1943        Ok(input_stream)
1944    } else {
1945        // Check not null constraint on the input stream
1946        Ok(Box::pin(RecordBatchStreamAdapter::new(
1947            sink_schema,
1948            input_stream
1949                .map(move |batch| check_not_null_constraints(batch?, &risky_columns)),
1950        )))
1951    }
1952}
1953
1954/// Checks a `RecordBatch` for `not null` constraints on specified columns.
1955///
1956/// # Arguments
1957///
1958/// * `batch` - The `RecordBatch` to be checked
1959/// * `column_indices` - A vector of column indices that should be checked for
1960///   `not null` constraints.
1961///
1962/// # Returns
1963///
1964/// * `Result<RecordBatch>` - The original `RecordBatch` if all constraints are met
1965///
1966/// This function iterates over the specified column indices and ensures that none
1967/// of the columns contain null values. If any column contains null values, an error
1968/// is returned.
1969pub fn check_not_null_constraints(
1970    batch: RecordBatch,
1971    column_indices: &Vec<usize>,
1972) -> Result<RecordBatch> {
1973    for &index in column_indices {
1974        if batch.num_columns() <= index {
1975            return exec_err!(
1976                "Invalid batch column count {} expected > {}",
1977                batch.num_columns(),
1978                index
1979            );
1980        }
1981
1982        if batch
1983            .column(index)
1984            .logical_nulls()
1985            .map(|nulls| nulls.null_count())
1986            .unwrap_or_default()
1987            > 0
1988        {
1989            return exec_err!(
1990                "Invalid batch column at '{}' has null but schema specifies non-nullable",
1991                index
1992            );
1993        }
1994    }
1995
1996    Ok(batch)
1997}
1998
1999/// Make plan ready to be re-executed returning its clone with state reset for all nodes.
2000///
2001/// Some plans will change their internal states after execution, making them unable to be executed again.
2002/// This function uses [`ExecutionPlan::reset_state`] to reset any internal state within the plan.
2003///
2004/// An example is `CrossJoinExec`, which loads the left table into memory and stores it in the plan.
2005/// However, if the data of the left table is derived from the work table, it will become outdated
2006/// as the work table changes. When the next iteration executes this plan again, we must clear the left table.
2007///
2008/// # Limitations
2009///
2010/// While this function enables plan reuse, it does not allow the same plan to be executed if it (OR):
2011///
2012/// * uses dynamic filters and the original plan (or another reset copy) is still
2013///   executing, because operators such as `HashJoinExec` and `AggregateExec`
2014///   reset their shared dynamic filter in place,
2015/// * represents a recursive query.
2016///
2017pub fn reset_plan_states(plan: Arc<dyn ExecutionPlan>) -> Result<Arc<dyn ExecutionPlan>> {
2018    plan.transform_up(|plan| {
2019        let new_plan = Arc::clone(&plan).reset_state()?;
2020        Ok(Transformed::yes(new_plan))
2021    })
2022    .data()
2023}
2024
2025/// Check if the `plan` children has the same properties as passed `children`.
2026/// In this case plan can avoid self properties re-computation when its children
2027/// replace is requested.
2028/// The size of `children` must be equal to the size of `ExecutionPlan::children()`.
2029pub fn has_same_children_properties(
2030    plan: &dyn ExecutionPlan,
2031    children: &[Arc<dyn ExecutionPlan>],
2032) -> Result<bool> {
2033    let old_children = plan.children();
2034    assert_eq_or_internal_err!(
2035        children.len(),
2036        old_children.len(),
2037        "Wrong number of children"
2038    );
2039    for (lhs, rhs) in old_children.iter().zip(children.iter()) {
2040        if !Arc::ptr_eq(lhs.properties(), rhs.properties()) {
2041            return Ok(false);
2042        }
2043    }
2044    Ok(true)
2045}
2046
2047/// Helper macro to avoid properties re-computation if passed children properties
2048/// the same as plan already has. Could be used to implement fast-path for method
2049/// [`ExecutionPlan::with_new_children`].
2050///
2051/// New call sites should route through [`replace_children_if_necessary`],
2052/// which applies this check together with the child-pointer short-circuit
2053/// (see [`replace_children_if_necessary`] for the layered policy). This
2054/// macro remains for direct-caller sites that have not been migrated yet.
2055#[macro_export]
2056macro_rules! check_if_same_properties {
2057    ($plan: expr, $children: expr) => {
2058        if $crate::execution_plan::has_same_children_properties(
2059            $plan.as_ref(),
2060            &$children,
2061        )? {
2062            return ::std::sync::Arc::clone(&$plan)
2063                .with_new_children_and_same_properties($children);
2064        }
2065    };
2066}
2067
2068/// Helper macro to validate that replacement children match a plan's existing
2069/// child count.
2070///
2071/// This is useful for [`ExecutionPlan::replace_children`] implementations that
2072/// need to preserve the same child-count validation behavior.
2073#[macro_export]
2074macro_rules! validate_child_count {
2075    ($plan: expr, $children: expr) => {
2076        datafusion_common::assert_eq_or_internal_err!(
2077            $children.len(),
2078            $plan.children().len(),
2079            "Wrong number of children"
2080        );
2081    };
2082}
2083
2084/// Utility function yielding a string representation of the given [`ExecutionPlan`].
2085pub fn get_plan_string(plan: &Arc<dyn ExecutionPlan>) -> Vec<String> {
2086    let formatted = displayable(plan.as_ref()).indent(true).to_string();
2087    let actual: Vec<&str> = formatted.trim().lines().collect();
2088    actual.iter().map(|elem| (*elem).to_string()).collect()
2089}
2090
2091/// What a row limit on an operator's output means for the operator's input.
2092/// Returned by [`ExecutionPlan::limit_behavior`].
2093///
2094/// A limit can be *copied* below a node as an early-stop hint while it also
2095/// stays above the node, or *moved* below a node, leaving nothing above it.
2096/// Copying is safe whenever the first `n` output rows need at most the first
2097/// `n` rows of each child. Moving also needs the node to output exactly the
2098/// rows of its input.
2099#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2100pub enum LimitBehavior {
2101    /// A limit above this node must stay above it. The default.
2102    Stops,
2103    /// This node applies `OFFSET skip LIMIT fetch` to its single input
2104    /// (`GlobalLimitExec`, `LocalLimitExec`).
2105    Limit { skip: usize, fetch: Option<usize> },
2106    /// A limit may be copied to each child, but may not move: this node can
2107    /// output more rows than any one child (`UnionExec`).
2108    CopyToChildren,
2109    /// This node outputs exactly the rows of its input: a limit may move to
2110    /// its input (`ProjectionExec`).
2111    MoveToInput,
2112    /// This node merges its input partitions, so it sees every row and can
2113    /// enforce a limit with its own fetch (`CoalescePartitionsExec`,
2114    /// `SortPreservingMergeExec`). Without a fetch of its own
2115    /// ([`ExecutionPlan::fetch`]) it outputs exactly the rows of its input,
2116    /// like [`Self::MoveToInput`]. With one, it already selects rows, so a
2117    /// limit above it may not move below it.
2118    Merge,
2119    /// A window function node, with how far it reads ahead of each output
2120    /// row; `None` if that is not known before execution. Only
2121    /// `LimitPushPastWindows` copies a limit below a window.
2122    Window(Option<WindowLookahead>),
2123}
2124
2125/// How many input rows a window needs for its first `n` output rows. See
2126/// [`LimitBehavior::Window`].
2127#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
2128pub struct WindowLookahead {
2129    /// At least this many input rows, whatever `n` is.
2130    pub min_rows: Option<usize>,
2131    /// Output row `i` reads input rows up to `i + frame_end` (`ROWS` frames).
2132    pub frame_end: usize,
2133    /// The window functions read this many rows past the frame
2134    /// (e.g. `LEAD(x, 2)`).
2135    pub relative: usize,
2136}
2137
2138/// Indicates the effect an execution plan operator will have on the cardinality
2139/// of its input stream
2140pub enum CardinalityEffect {
2141    /// Unknown effect. This is the default
2142    Unknown,
2143    /// The operator is guaranteed to produce exactly one row for
2144    /// each input row
2145    Equal,
2146    /// The operator may produce fewer output rows than it receives input rows
2147    LowerEqual,
2148    /// The operator may produce more output rows than it receives input rows
2149    GreaterEqual,
2150}
2151
2152/// Can be used in contexts where properties have not yet been initialized properly.
2153pub(crate) fn stub_properties() -> Arc<PlanProperties> {
2154    static STUB_PROPERTIES: LazyLock<Arc<PlanProperties>> = LazyLock::new(|| {
2155        Arc::new(PlanProperties::new(
2156            EquivalenceProperties::new(Arc::new(Schema::empty())),
2157            Partitioning::UnknownPartitioning(1),
2158            EmissionType::Final,
2159            Boundedness::Bounded,
2160        ))
2161    });
2162
2163    Arc::clone(&STUB_PROPERTIES)
2164}
2165
2166#[cfg(test)]
2167mod tests {
2168
2169    use super::*;
2170    use crate::buffer::BufferExec;
2171    use crate::test::exec::MockExec;
2172    use crate::{DisplayAs, DisplayFormatType, ExecutionPlan};
2173
2174    use arrow::array::{DictionaryArray, Int32Array, NullArray, RunArray};
2175    use arrow::datatypes::{DataType, Field, Schema};
2176    use datafusion_physical_expr::expressions::{DynamicFilterPhysicalExpr, lit};
2177
2178    #[derive(Debug)]
2179    pub struct EmptyExec {
2180        children: Vec<Arc<dyn ExecutionPlan>>,
2181        dynamic_expressions: Vec<Arc<dyn PhysicalExpr>>,
2182        maintains_input_order_len: Option<usize>,
2183        required_input_ordering_len: Option<usize>,
2184        benefits_from_input_partitioning_len: Option<usize>,
2185        input_distribution_requirements: Option<InputDistributionRequirements>,
2186    }
2187
2188    impl EmptyExec {
2189        pub fn new(_schema: SchemaRef) -> Self {
2190            Self {
2191                children: vec![],
2192                dynamic_expressions: vec![],
2193                maintains_input_order_len: None,
2194                required_input_ordering_len: None,
2195                benefits_from_input_partitioning_len: None,
2196                input_distribution_requirements: None,
2197            }
2198        }
2199
2200        fn with_child(mut self, child: Arc<dyn ExecutionPlan>) -> Self {
2201            self.children.push(child);
2202            self
2203        }
2204
2205        fn with_dynamic_expressions(
2206            mut self,
2207            dynamic_expressions: Vec<Arc<dyn PhysicalExpr>>,
2208        ) -> Self {
2209            self.dynamic_expressions = dynamic_expressions;
2210            self
2211        }
2212
2213        fn with_maintains_input_order_len(mut self, len: usize) -> Self {
2214            self.maintains_input_order_len = Some(len);
2215            self
2216        }
2217
2218        fn with_required_input_ordering_len(mut self, len: usize) -> Self {
2219            self.required_input_ordering_len = Some(len);
2220            self
2221        }
2222
2223        fn with_benefits_from_input_partitioning_len(mut self, len: usize) -> Self {
2224            self.benefits_from_input_partitioning_len = Some(len);
2225            self
2226        }
2227
2228        fn with_input_distribution_requirements_len(mut self, len: usize) -> Self {
2229            self.input_distribution_requirements =
2230                Some(InputDistributionRequirements::new(
2231                    vec![Distribution::UnspecifiedDistribution; len],
2232                ));
2233            self
2234        }
2235
2236        fn with_input_distribution_requirements(
2237            mut self,
2238            requirements: InputDistributionRequirements,
2239        ) -> Self {
2240            self.input_distribution_requirements = Some(requirements);
2241            self
2242        }
2243    }
2244
2245    impl DisplayAs for EmptyExec {
2246        fn fmt_as(
2247            &self,
2248            _t: DisplayFormatType,
2249            _f: &mut std::fmt::Formatter,
2250        ) -> std::fmt::Result {
2251            unimplemented!()
2252        }
2253    }
2254
2255    impl ExecutionPlan for EmptyExec {
2256        fn name(&self) -> &'static str {
2257            Self::static_name()
2258        }
2259
2260        fn properties(&self) -> &Arc<PlanProperties> {
2261            unimplemented!()
2262        }
2263
2264        fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
2265            self.children.iter().collect()
2266        }
2267
2268        fn maintains_input_order(&self) -> Vec<bool> {
2269            vec![
2270                false;
2271                self.maintains_input_order_len
2272                    .unwrap_or(self.children.len())
2273            ]
2274        }
2275
2276        fn required_input_ordering(&self) -> Vec<Option<OrderingRequirements>> {
2277            vec![
2278                None;
2279                self.required_input_ordering_len
2280                    .unwrap_or(self.children.len())
2281            ]
2282        }
2283
2284        fn benefits_from_input_partitioning(&self) -> Vec<bool> {
2285            vec![
2286                true;
2287                self.benefits_from_input_partitioning_len
2288                    .unwrap_or(self.children.len())
2289            ]
2290        }
2291
2292        fn input_distribution_requirements(&self) -> InputDistributionRequirements {
2293            self.input_distribution_requirements
2294                .clone()
2295                .unwrap_or_else(|| {
2296                    InputDistributionRequirements::new(vec![
2297                    Distribution::UnspecifiedDistribution;
2298                    self.children.len()
2299                ])
2300                })
2301        }
2302
2303        fn replace_children(
2304            self: Arc<Self>,
2305            _: Vec<Arc<dyn ExecutionPlan>>,
2306            _: ReplaceChildrenOptions,
2307        ) -> Result<Arc<dyn ExecutionPlan>> {
2308            unimplemented!()
2309        }
2310
2311        fn apply_expressions(
2312            &self,
2313            _f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> Result<TreeNodeRecursion>,
2314        ) -> Result<TreeNodeRecursion> {
2315            Ok(TreeNodeRecursion::Continue)
2316        }
2317
2318        fn with_new_children(
2319            self: Arc<Self>,
2320            children: Vec<Arc<dyn ExecutionPlan>>,
2321        ) -> Result<Arc<dyn ExecutionPlan>> {
2322            self.replace_children(
2323                children,
2324                ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute),
2325            )
2326        }
2327
2328        fn dynamic_expressions_produced(&self) -> Vec<Arc<dyn PhysicalExpr>> {
2329            self.dynamic_expressions.iter().map(Arc::clone).collect()
2330        }
2331
2332        fn execute(
2333            &self,
2334            _partition: usize,
2335            _context: Arc<TaskContext>,
2336        ) -> Result<SendableRecordBatchStream> {
2337            unimplemented!()
2338        }
2339
2340        fn statistics_from_inputs(
2341            &self,
2342            _input_stats: &[Arc<Statistics>],
2343            _args: &StatisticsArgs,
2344        ) -> Result<Arc<Statistics>> {
2345            unimplemented!()
2346        }
2347    }
2348
2349    #[test]
2350    fn test_dynamic_expression_invariants() -> Result<()> {
2351        let schema = Arc::new(Schema::empty());
2352        let dynamic: Arc<dyn PhysicalExpr> =
2353            Arc::new(DynamicFilterPhysicalExpr::new(vec![], lit(true)));
2354        let valid = EmptyExec::new(Arc::clone(&schema))
2355            .with_dynamic_expressions(vec![Arc::clone(&dynamic)]);
2356        check_default_invariants(&valid, InvariantLevel::Always)?;
2357
2358        let missing_id =
2359            EmptyExec::new(Arc::clone(&schema)).with_dynamic_expressions(vec![lit(true)]);
2360        let error = check_default_invariants(&missing_id, InvariantLevel::Always)
2361            .unwrap_err()
2362            .strip_backtrace();
2363        assert!(error.contains("without an expression ID"), "{error}");
2364
2365        let duplicate = EmptyExec::new(schema)
2366            .with_dynamic_expressions(vec![Arc::clone(&dynamic), dynamic]);
2367        let error = check_default_invariants(&duplicate, InvariantLevel::Always)
2368            .unwrap_err()
2369            .strip_backtrace();
2370        assert!(error.contains("duplicate expression ID"), "{error}");
2371
2372        Ok(())
2373    }
2374
2375    #[test]
2376    fn test_default_invariant_lengths() -> Result<()> {
2377        let schema = Arc::new(Schema::empty());
2378        let child: Arc<dyn ExecutionPlan> = Arc::new(EmptyExec::new(Arc::clone(&schema)));
2379        let make_plan =
2380            || EmptyExec::new(Arc::clone(&schema)).with_child(Arc::clone(&child));
2381
2382        check_default_invariants(&make_plan(), InvariantLevel::Always)?;
2383
2384        let cases = [
2385            (
2386                make_plan().with_maintains_input_order_len(0),
2387                "Internal error: Assertion failed: actual_len == children_len (left: 0, right: 1): EmptyExec::maintains_input_order returned Vec with incorrect size: 0 != 1",
2388            ),
2389            (
2390                make_plan().with_required_input_ordering_len(0),
2391                "Internal error: Assertion failed: actual_len == children_len (left: 0, right: 1): EmptyExec::required_input_ordering returned Vec with incorrect size: 0 != 1",
2392            ),
2393            (
2394                make_plan().with_benefits_from_input_partitioning_len(0),
2395                "Internal error: Assertion failed: actual_len == children_len (left: 0, right: 1): EmptyExec::benefits_from_input_partitioning returned Vec with incorrect size: 0 != 1",
2396            ),
2397            (
2398                make_plan().with_input_distribution_requirements_len(0),
2399                "Internal error: EmptyExec::input_distribution_requirements returned incorrect child count: 0 != 1",
2400            ),
2401        ];
2402
2403        for (plan, expected) in cases {
2404            let error = check_default_invariants(&plan, InvariantLevel::Always)
2405                .unwrap_err()
2406                .strip_backtrace();
2407            assert!(error.starts_with(expected), "{error}");
2408        }
2409
2410        let invalid_co_partitioning = make_plan()
2411            .with_child(child)
2412            .with_input_distribution_requirements(
2413                InputDistributionRequirements::co_partitioned(vec![
2414                    Distribution::UnspecifiedDistribution,
2415                    Distribution::UnspecifiedDistribution,
2416                ]),
2417            );
2418        let error =
2419            check_default_invariants(&invalid_co_partitioning, InvariantLevel::Always)
2420                .unwrap_err()
2421                .strip_backtrace();
2422        assert!(
2423            error.starts_with(
2424                "Internal error: EmptyExec has invalid co-partitioning requirement: child 0 has unspecified distribution"
2425            ),
2426            "{error}"
2427        );
2428
2429        let left: Arc<dyn ExecutionPlan> =
2430            Arc::new(crate::empty::EmptyExec::new(Arc::clone(&schema)));
2431        let right: Arc<dyn ExecutionPlan> =
2432            Arc::new(crate::empty::EmptyExec::new(Arc::clone(&schema)));
2433        let valid_co_partitioning = EmptyExec::new(schema)
2434            .with_child(left)
2435            .with_child(right)
2436            .with_input_distribution_requirements(
2437                InputDistributionRequirements::co_partitioned(vec![
2438                    Distribution::SinglePartition,
2439                    Distribution::SinglePartition,
2440                ]),
2441            );
2442        check_default_invariants(&valid_co_partitioning, InvariantLevel::Executable)?;
2443
2444        Ok(())
2445    }
2446
2447    #[test]
2448    fn test_default_invariants_accept_trait_object() -> Result<()> {
2449        let plan = EmptyExec::new(Arc::new(Schema::empty()));
2450        let plan: &dyn ExecutionPlan = &plan;
2451
2452        check_default_invariants(plan, InvariantLevel::Always)?;
2453        plan.check_invariants(InvariantLevel::Always)
2454    }
2455
2456    #[derive(Debug)]
2457    pub struct RenamedEmptyExec;
2458
2459    impl RenamedEmptyExec {
2460        pub fn new(_schema: SchemaRef) -> Self {
2461            Self
2462        }
2463    }
2464
2465    impl DisplayAs for RenamedEmptyExec {
2466        fn fmt_as(
2467            &self,
2468            _t: DisplayFormatType,
2469            _f: &mut std::fmt::Formatter,
2470        ) -> std::fmt::Result {
2471            unimplemented!()
2472        }
2473    }
2474
2475    impl ExecutionPlan for RenamedEmptyExec {
2476        fn name(&self) -> &'static str {
2477            Self::static_name()
2478        }
2479
2480        fn static_name() -> &'static str
2481        where
2482            Self: Sized,
2483        {
2484            "MyRenamedEmptyExec"
2485        }
2486
2487        fn properties(&self) -> &Arc<PlanProperties> {
2488            unimplemented!()
2489        }
2490
2491        fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
2492            vec![]
2493        }
2494
2495        fn apply_expressions(
2496            &self,
2497            _f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> Result<TreeNodeRecursion>,
2498        ) -> Result<TreeNodeRecursion> {
2499            Ok(TreeNodeRecursion::Continue)
2500        }
2501
2502        fn replace_children(
2503            self: Arc<Self>,
2504            _: Vec<Arc<dyn ExecutionPlan>>,
2505            _: ReplaceChildrenOptions,
2506        ) -> Result<Arc<dyn ExecutionPlan>> {
2507            unimplemented!()
2508        }
2509
2510        fn with_new_children(
2511            self: Arc<Self>,
2512            children: Vec<Arc<dyn ExecutionPlan>>,
2513        ) -> Result<Arc<dyn ExecutionPlan>> {
2514            self.replace_children(
2515                children,
2516                ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute),
2517            )
2518        }
2519
2520        fn execute(
2521            &self,
2522            _partition: usize,
2523            _context: Arc<TaskContext>,
2524        ) -> Result<SendableRecordBatchStream> {
2525            unimplemented!()
2526        }
2527
2528        fn statistics_from_inputs(
2529            &self,
2530            _input_stats: &[Arc<Statistics>],
2531            _args: &StatisticsArgs,
2532        ) -> Result<Arc<Statistics>> {
2533            unimplemented!()
2534        }
2535    }
2536
2537    #[derive(Debug)]
2538    struct DowncastDelegatingExec(Arc<dyn ExecutionPlan>);
2539
2540    impl DisplayAs for DowncastDelegatingExec {
2541        fn fmt_as(
2542            &self,
2543            _t: DisplayFormatType,
2544            _f: &mut std::fmt::Formatter,
2545        ) -> std::fmt::Result {
2546            unimplemented!()
2547        }
2548    }
2549
2550    impl ExecutionPlan for DowncastDelegatingExec {
2551        fn name(&self) -> &'static str {
2552            Self::static_name()
2553        }
2554
2555        fn properties(&self) -> &Arc<PlanProperties> {
2556            unimplemented!()
2557        }
2558
2559        fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
2560            vec![]
2561        }
2562
2563        fn apply_expressions(
2564            &self,
2565            f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> Result<TreeNodeRecursion>,
2566        ) -> Result<TreeNodeRecursion> {
2567            self.0.apply_expressions(f)
2568        }
2569
2570        fn replace_children(
2571            self: Arc<Self>,
2572            _: Vec<Arc<dyn ExecutionPlan>>,
2573            _: ReplaceChildrenOptions,
2574        ) -> Result<Arc<dyn ExecutionPlan>> {
2575            unimplemented!()
2576        }
2577
2578        fn with_new_children(
2579            self: Arc<Self>,
2580            children: Vec<Arc<dyn ExecutionPlan>>,
2581        ) -> Result<Arc<dyn ExecutionPlan>> {
2582            self.replace_children(
2583                children,
2584                ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute),
2585            )
2586        }
2587
2588        fn downcast_delegate(&self) -> Option<&dyn ExecutionPlan> {
2589            Some(self.0.as_ref())
2590        }
2591
2592        fn execute(
2593            &self,
2594            _partition: usize,
2595            _context: Arc<TaskContext>,
2596        ) -> Result<SendableRecordBatchStream> {
2597            unimplemented!()
2598        }
2599
2600        fn partition_statistics(
2601            &self,
2602            _partition: Option<usize>,
2603        ) -> Result<Arc<Statistics>> {
2604            unimplemented!()
2605        }
2606    }
2607    /// Test leaf plan with a real [`PlanProperties`] cache. Different instances
2608    /// can share the same cache Arc by cloning `cache`.
2609    #[derive(Debug, Clone)]
2610    struct WithChildrenTestLeaf {
2611        cache: Arc<PlanProperties>,
2612    }
2613
2614    impl WithChildrenTestLeaf {
2615        fn new(cache: Arc<PlanProperties>) -> Self {
2616            Self { cache }
2617        }
2618    }
2619
2620    impl DisplayAs for WithChildrenTestLeaf {
2621        fn fmt_as(
2622            &self,
2623            _t: DisplayFormatType,
2624            _f: &mut std::fmt::Formatter,
2625        ) -> std::fmt::Result {
2626            unimplemented!()
2627        }
2628    }
2629
2630    impl ExecutionPlan for WithChildrenTestLeaf {
2631        fn name(&self) -> &'static str {
2632            "WithChildrenTestLeaf"
2633        }
2634        fn properties(&self) -> &Arc<PlanProperties> {
2635            &self.cache
2636        }
2637        fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
2638            vec![]
2639        }
2640        fn apply_expressions(
2641            &self,
2642            _f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> Result<TreeNodeRecursion>,
2643        ) -> Result<TreeNodeRecursion> {
2644            Ok(TreeNodeRecursion::Continue)
2645        }
2646
2647        fn replace_children(
2648            self: Arc<Self>,
2649            _: Vec<Arc<dyn ExecutionPlan>>,
2650            _: ReplaceChildrenOptions,
2651        ) -> Result<Arc<dyn ExecutionPlan>> {
2652            Ok(self)
2653        }
2654        fn with_new_children(
2655            self: Arc<Self>,
2656            children: Vec<Arc<dyn ExecutionPlan>>,
2657        ) -> Result<Arc<dyn ExecutionPlan>> {
2658            self.replace_children(
2659                children,
2660                ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute),
2661            )
2662        }
2663        fn execute(
2664            &self,
2665            _partition: usize,
2666            _context: Arc<TaskContext>,
2667        ) -> Result<SendableRecordBatchStream> {
2668            unimplemented!()
2669        }
2670    }
2671
2672    /// Test unary plan that counts which of `with_new_children` (full
2673    /// recompute) vs `with_new_children_and_same_properties` (fast path) is
2674    /// taken.
2675    #[derive(Debug, Clone)]
2676    struct WithChildrenTestParent {
2677        input: Arc<dyn ExecutionPlan>,
2678        cache: Arc<PlanProperties>,
2679        recompute_calls: Arc<std::sync::atomic::AtomicUsize>,
2680        fast_path_calls: Arc<std::sync::atomic::AtomicUsize>,
2681    }
2682
2683    impl WithChildrenTestParent {
2684        fn new(input: Arc<dyn ExecutionPlan>) -> Self {
2685            let cache = Arc::new(PlanProperties::new(
2686                EquivalenceProperties::new(Arc::new(Schema::empty())),
2687                Partitioning::UnknownPartitioning(1),
2688                EmissionType::Final,
2689                Boundedness::Bounded,
2690            ));
2691            Self {
2692                input,
2693                cache,
2694                recompute_calls: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
2695                fast_path_calls: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
2696            }
2697        }
2698    }
2699
2700    impl DisplayAs for WithChildrenTestParent {
2701        fn fmt_as(
2702            &self,
2703            _t: DisplayFormatType,
2704            _f: &mut std::fmt::Formatter,
2705        ) -> std::fmt::Result {
2706            unimplemented!()
2707        }
2708    }
2709
2710    impl ExecutionPlan for WithChildrenTestParent {
2711        fn name(&self) -> &'static str {
2712            "WithChildrenTestParent"
2713        }
2714        fn properties(&self) -> &Arc<PlanProperties> {
2715            &self.cache
2716        }
2717        fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
2718            vec![&self.input]
2719        }
2720        fn apply_expressions(
2721            &self,
2722            _f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> Result<TreeNodeRecursion>,
2723        ) -> Result<TreeNodeRecursion> {
2724            Ok(TreeNodeRecursion::Continue)
2725        }
2726
2727        fn replace_children(
2728            self: Arc<Self>,
2729            mut children: Vec<Arc<dyn ExecutionPlan>>,
2730            options: ReplaceChildrenOptions,
2731        ) -> Result<Arc<dyn ExecutionPlan>> {
2732            match options.children_properties {
2733                ChildrenPropertiesMode::Keep => {
2734                    self.fast_path_calls
2735                        .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
2736                    Ok(Arc::new(Self {
2737                        input: children.swap_remove(0),
2738                        ..Self::clone(&*self)
2739                    }))
2740                }
2741                ChildrenPropertiesMode::Recompute => {
2742                    self.recompute_calls
2743                        .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
2744                    // Full recompute: allocate a fresh `PlanProperties` Arc so this
2745                    // path is observable via `Arc::ptr_eq` on properties.
2746                    let new_input = children.swap_remove(0);
2747                    let cache = Arc::new(PlanProperties::new(
2748                        EquivalenceProperties::new(Arc::new(Schema::empty())),
2749                        Partitioning::UnknownPartitioning(1),
2750                        EmissionType::Final,
2751                        Boundedness::Bounded,
2752                    ));
2753                    Ok(Arc::new(Self {
2754                        input: new_input,
2755                        cache,
2756                        recompute_calls: Arc::clone(&self.recompute_calls),
2757                        fast_path_calls: Arc::clone(&self.fast_path_calls),
2758                    }))
2759                }
2760            }
2761        }
2762        fn with_new_children(
2763            self: Arc<Self>,
2764            children: Vec<Arc<dyn ExecutionPlan>>,
2765        ) -> Result<Arc<dyn ExecutionPlan>> {
2766            self.replace_children(
2767                children,
2768                ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute),
2769            )
2770        }
2771        fn with_new_children_and_same_properties(
2772            self: Arc<Self>,
2773            children: Vec<Arc<dyn ExecutionPlan>>,
2774        ) -> Result<Arc<dyn ExecutionPlan>> {
2775            self.replace_children(
2776                children,
2777                ReplaceChildrenOptions::new(ChildrenPropertiesMode::Keep),
2778            )
2779        }
2780        fn execute(
2781            &self,
2782            _partition: usize,
2783            _context: Arc<TaskContext>,
2784        ) -> Result<SendableRecordBatchStream> {
2785            unimplemented!()
2786        }
2787    }
2788
2789    /// Test unary plan that does **not** override
2790    /// `with_new_children_and_same_properties`. Used to verify the default
2791    /// trait fallback still routes through `with_new_children` (which is
2792    /// the semantics-preserving path for downstream / external
2793    /// `ExecutionPlan` implementations that haven't opted into the
2794    /// fast path yet).
2795    #[derive(Debug, Clone)]
2796    struct WithChildrenTestParentDefault {
2797        input: Arc<dyn ExecutionPlan>,
2798        cache: Arc<PlanProperties>,
2799        recompute_calls: Arc<std::sync::atomic::AtomicUsize>,
2800    }
2801
2802    impl WithChildrenTestParentDefault {
2803        fn new(input: Arc<dyn ExecutionPlan>) -> Self {
2804            let cache = Arc::new(PlanProperties::new(
2805                EquivalenceProperties::new(Arc::new(Schema::empty())),
2806                Partitioning::UnknownPartitioning(1),
2807                EmissionType::Final,
2808                Boundedness::Bounded,
2809            ));
2810            Self {
2811                input,
2812                cache,
2813                recompute_calls: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
2814            }
2815        }
2816    }
2817
2818    impl DisplayAs for WithChildrenTestParentDefault {
2819        fn fmt_as(
2820            &self,
2821            _t: DisplayFormatType,
2822            _f: &mut std::fmt::Formatter,
2823        ) -> std::fmt::Result {
2824            unimplemented!()
2825        }
2826    }
2827
2828    impl ExecutionPlan for WithChildrenTestParentDefault {
2829        fn name(&self) -> &'static str {
2830            "WithChildrenTestParentDefault"
2831        }
2832        fn properties(&self) -> &Arc<PlanProperties> {
2833            &self.cache
2834        }
2835        fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
2836            vec![&self.input]
2837        }
2838        fn apply_expressions(
2839            &self,
2840            _f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> Result<TreeNodeRecursion>,
2841        ) -> Result<TreeNodeRecursion> {
2842            Ok(TreeNodeRecursion::Continue)
2843        }
2844        fn with_new_children(
2845            self: Arc<Self>,
2846            mut children: Vec<Arc<dyn ExecutionPlan>>,
2847        ) -> Result<Arc<dyn ExecutionPlan>> {
2848            self.recompute_calls
2849                .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
2850            let new_input = children.swap_remove(0);
2851            let cache = Arc::new(PlanProperties::new(
2852                EquivalenceProperties::new(Arc::new(Schema::empty())),
2853                Partitioning::UnknownPartitioning(1),
2854                EmissionType::Final,
2855                Boundedness::Bounded,
2856            ));
2857            Ok(Arc::new(Self {
2858                input: new_input,
2859                cache,
2860                recompute_calls: Arc::clone(&self.recompute_calls),
2861            }))
2862        }
2863        // Intentionally does **not** override
2864        // `with_new_children_and_same_properties` — relies on the trait
2865        // default that falls back to `with_new_children`.
2866        fn execute(
2867            &self,
2868            _partition: usize,
2869            _context: Arc<TaskContext>,
2870        ) -> Result<SendableRecordBatchStream> {
2871            unimplemented!()
2872        }
2873    }
2874
2875    /// Cover the three short-circuit layers of
2876    /// [`replace_children_if_necessary`].
2877    #[test]
2878    fn test_replace_children_if_necessary_layers() -> Result<()> {
2879        use std::sync::atomic::Ordering;
2880
2881        // Two leaves that share the same `PlanProperties` Arc but sit behind
2882        // distinct `Arc<dyn ExecutionPlan>` pointers.
2883        let leaf_props = Arc::new(PlanProperties::new(
2884            EquivalenceProperties::new(Arc::new(Schema::empty())),
2885            Partitioning::UnknownPartitioning(1),
2886            EmissionType::Final,
2887            Boundedness::Bounded,
2888        ));
2889        let leaf_a: Arc<dyn ExecutionPlan> =
2890            Arc::new(WithChildrenTestLeaf::new(Arc::clone(&leaf_props)));
2891        let leaf_b: Arc<dyn ExecutionPlan> =
2892            Arc::new(WithChildrenTestLeaf::new(Arc::clone(&leaf_props)));
2893        // A third leaf with a *different* `PlanProperties` Arc — for layer 3.
2894        let leaf_c_props = Arc::new(PlanProperties::new(
2895            EquivalenceProperties::new(Arc::new(Schema::empty())),
2896            Partitioning::UnknownPartitioning(1),
2897            EmissionType::Final,
2898            Boundedness::Bounded,
2899        ));
2900        let leaf_c: Arc<dyn ExecutionPlan> =
2901            Arc::new(WithChildrenTestLeaf::new(leaf_c_props));
2902
2903        let parent = Arc::new(WithChildrenTestParent::new(Arc::clone(&leaf_a)));
2904        let parent_dyn: Arc<dyn ExecutionPlan> = Arc::clone(&parent) as _;
2905        let orig_props = Arc::clone(parent.properties());
2906
2907        // Layer 1: same child pointer → returns the original plan Arc verbatim.
2908        let out = replace_children_if_necessary(
2909            Arc::clone(&parent_dyn),
2910            vec![Arc::clone(&leaf_a)],
2911        )?;
2912        assert!(Arc::ptr_eq(&out, &parent_dyn));
2913        assert_eq!(parent.recompute_calls.load(Ordering::SeqCst), 0);
2914        assert_eq!(parent.fast_path_calls.load(Ordering::SeqCst), 0);
2915
2916        // Layer 2: distinct child Arc, but children share the same
2917        // `PlanProperties` Arc → fast path, parent's `PlanProperties` cache
2918        // Arc is reused (not reallocated).
2919        assert!(!Arc::ptr_eq(&leaf_a, &leaf_b));
2920        assert!(Arc::ptr_eq(leaf_a.properties(), leaf_b.properties()));
2921        let out = replace_children_if_necessary(
2922            Arc::clone(&parent_dyn),
2923            vec![Arc::clone(&leaf_b)],
2924        )?;
2925        assert!(Arc::ptr_eq(out.properties(), &orig_props));
2926        assert_eq!(parent.recompute_calls.load(Ordering::SeqCst), 0);
2927        assert_eq!(parent.fast_path_calls.load(Ordering::SeqCst), 1);
2928
2929        // Layer 3: child's `PlanProperties` Arc differs → full recompute.
2930        assert!(!Arc::ptr_eq(leaf_a.properties(), leaf_c.properties()));
2931        let out = replace_children_if_necessary(
2932            Arc::clone(&parent_dyn),
2933            vec![Arc::clone(&leaf_c)],
2934        )?;
2935        assert!(!Arc::ptr_eq(out.properties(), &orig_props));
2936        assert_eq!(parent.recompute_calls.load(Ordering::SeqCst), 1);
2937        assert_eq!(parent.fast_path_calls.load(Ordering::SeqCst), 1);
2938
2939        Ok(())
2940    }
2941
2942    /// A plan that does not override `with_new_children_and_same_properties`
2943    /// (per @kosiew's review on #23332) must still be routed through
2944    /// `with_new_children` when the helper hits the "same properties"
2945    /// branch. The default trait implementation forwards to
2946    /// `with_new_children`, so downstream / external `ExecutionPlan`
2947    /// implementations keep the semantics-preserving path.
2948    #[test]
2949    fn test_replace_children_if_necessary_default_fallback() -> Result<()> {
2950        use std::sync::atomic::Ordering;
2951
2952        let leaf_props = Arc::new(PlanProperties::new(
2953            EquivalenceProperties::new(Arc::new(Schema::empty())),
2954            Partitioning::UnknownPartitioning(1),
2955            EmissionType::Final,
2956            Boundedness::Bounded,
2957        ));
2958        let leaf_a: Arc<dyn ExecutionPlan> =
2959            Arc::new(WithChildrenTestLeaf::new(Arc::clone(&leaf_props)));
2960        let leaf_b: Arc<dyn ExecutionPlan> =
2961            Arc::new(WithChildrenTestLeaf::new(Arc::clone(&leaf_props)));
2962        assert!(!Arc::ptr_eq(&leaf_a, &leaf_b));
2963        assert!(Arc::ptr_eq(leaf_a.properties(), leaf_b.properties()));
2964
2965        let parent = Arc::new(WithChildrenTestParentDefault::new(Arc::clone(&leaf_a)));
2966        let parent_dyn: Arc<dyn ExecutionPlan> = Arc::clone(&parent) as _;
2967
2968        // Using the same child means we return the original plan Arc verbatim, so even when
2969        // the `replace_children` `ChildrenPropertiesMode::Keep` path is not defined,
2970        // we do not recompute.
2971        let out = replace_children_if_necessary(
2972            Arc::clone(&parent_dyn),
2973            vec![Arc::clone(&leaf_a)],
2974        )?;
2975        assert!(Arc::ptr_eq(&out, &parent_dyn));
2976        assert_eq!(parent.recompute_calls.load(Ordering::SeqCst), 0);
2977
2978        // Using a distinct child but the same `PlanProperties` Arc means the helper
2979        // attempts to enter the Keep branch. If it does not exist, we fall back
2980        // to recomputation.
2981        let out = replace_children_if_necessary(
2982            Arc::clone(&parent_dyn),
2983            vec![Arc::clone(&leaf_b)],
2984        )?;
2985        // `with_new_children` was invoked exactly once via the default.
2986        assert_eq!(parent.recompute_calls.load(Ordering::SeqCst), 1);
2987        // The returned plan has a freshly-recomputed `PlanProperties` Arc,
2988        // so it differs from the parent's original cache. This confirms
2989        // the fallback ran and did not short-circuit.
2990        assert!(!Arc::ptr_eq(out.properties(), parent.properties()));
2991
2992        Ok(())
2993    }
2994
2995    /// A test node that holds a fixed list of expressions, used to test
2996    /// `apply_expressions` behavior.
2997    #[derive(Debug)]
2998    struct MultiExprExec {
2999        exprs: Vec<Arc<dyn PhysicalExpr>>,
3000        children: Vec<Arc<dyn ExecutionPlan>>,
3001    }
3002
3003    impl DisplayAs for MultiExprExec {
3004        fn fmt_as(
3005            &self,
3006            _t: DisplayFormatType,
3007            _f: &mut std::fmt::Formatter,
3008        ) -> std::fmt::Result {
3009            unimplemented!()
3010        }
3011    }
3012
3013    impl ExecutionPlan for MultiExprExec {
3014        fn name(&self) -> &'static str {
3015            "MultiExprExec"
3016        }
3017
3018        fn properties(&self) -> &Arc<PlanProperties> {
3019            unimplemented!()
3020        }
3021
3022        fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
3023            self.children.iter().collect()
3024        }
3025
3026        fn with_new_children(
3027            self: Arc<Self>,
3028            _: Vec<Arc<dyn ExecutionPlan>>,
3029        ) -> Result<Arc<dyn ExecutionPlan>> {
3030            unimplemented!()
3031        }
3032
3033        fn apply_expressions(
3034            &self,
3035            f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> Result<TreeNodeRecursion>,
3036        ) -> Result<TreeNodeRecursion> {
3037            apply_expression_roots(&self.exprs, f)
3038        }
3039
3040        fn execute(
3041            &self,
3042            _partition: usize,
3043            _context: Arc<TaskContext>,
3044        ) -> Result<SendableRecordBatchStream> {
3045            unimplemented!()
3046        }
3047
3048        fn partition_statistics(
3049            &self,
3050            _partition: Option<usize>,
3051        ) -> Result<Arc<Statistics>> {
3052            unimplemented!()
3053        }
3054    }
3055
3056    /// Returns a simple literal `Arc<dyn PhysicalExpr>` for use in tests.
3057    fn lit_expr(val: i64) -> Arc<dyn PhysicalExpr> {
3058        use datafusion_physical_expr::expressions::Literal;
3059        Arc::new(Literal::new(datafusion_common::ScalarValue::Int64(Some(
3060            val,
3061        ))))
3062    }
3063
3064    /// `apply_expressions` visits all expressions when `f` always returns `Continue`.
3065    #[test]
3066    fn test_apply_expressions_continue_visits_all() -> Result<()> {
3067        let plan = MultiExprExec {
3068            exprs: vec![lit_expr(1), lit_expr(2), lit_expr(3)],
3069            children: vec![],
3070        };
3071        let mut visited = 0usize;
3072        plan.apply_expressions(&mut |_expr| {
3073            visited += 1;
3074            Ok(TreeNodeRecursion::Continue)
3075        })?;
3076        assert_eq!(visited, 3);
3077        Ok(())
3078    }
3079
3080    #[test]
3081    fn test_apply_expressions_stop_halts_early() -> Result<()> {
3082        let plan = MultiExprExec {
3083            exprs: vec![lit_expr(1), lit_expr(2), lit_expr(3)],
3084            children: vec![],
3085        };
3086        let mut visited = 0usize;
3087        let tnr = plan.apply_expressions(&mut |_expr| {
3088            visited += 1;
3089            Ok(TreeNodeRecursion::Stop)
3090        })?;
3091        // Only the first expression is visited; the rest are skipped.
3092        assert_eq!(visited, 1);
3093        assert_eq!(tnr, TreeNodeRecursion::Stop);
3094        Ok(())
3095    }
3096
3097    #[test]
3098    fn test_apply_expressions_jump_visits_next_root() -> Result<()> {
3099        let plan = MultiExprExec {
3100            exprs: vec![lit_expr(1), lit_expr(2), lit_expr(3)],
3101            children: vec![],
3102        };
3103        let mut visited = 0usize;
3104        let tnr = plan.apply_expressions(&mut |_expr| {
3105            visited += 1;
3106            Ok(TreeNodeRecursion::Jump)
3107        })?;
3108        assert_eq!(visited, 3);
3109        assert_eq!(tnr, TreeNodeRecursion::Continue);
3110        Ok(())
3111    }
3112
3113    #[test]
3114    fn test_apply_expressions_does_not_recurse() -> Result<()> {
3115        use datafusion_physical_expr::expressions::NegativeExpr;
3116
3117        let child: Arc<dyn ExecutionPlan> = Arc::new(MultiExprExec {
3118            exprs: vec![lit_expr(2)],
3119            children: vec![],
3120        });
3121        let nested: Arc<dyn PhysicalExpr> = Arc::new(NegativeExpr::new(lit_expr(1)));
3122        let plan = MultiExprExec {
3123            exprs: vec![nested],
3124            children: vec![child],
3125        };
3126
3127        let mut visited = 0;
3128        plan.apply_expressions(&mut |expr| {
3129            visited += 1;
3130            assert!(expr.is::<NegativeExpr>());
3131            Ok(TreeNodeRecursion::Continue)
3132        })?;
3133        assert_eq!(visited, 1);
3134        Ok(())
3135    }
3136
3137    #[test]
3138    fn test_apply_expressions_callback_can_retain_arc() -> Result<()> {
3139        let expected = lit_expr(1);
3140        let plan = MultiExprExec {
3141            exprs: vec![Arc::clone(&expected)],
3142            children: vec![],
3143        };
3144        let mut retained = None;
3145        plan.apply_expressions(&mut |expr| {
3146            retained = Some(Arc::clone(expr));
3147            Ok(TreeNodeRecursion::Continue)
3148        })?;
3149        drop(plan);
3150
3151        assert!(Arc::ptr_eq(
3152            &expected,
3153            retained
3154                .as_ref()
3155                .expect("callback should retain expression")
3156        ));
3157        Ok(())
3158    }
3159
3160    #[test]
3161    fn test_execution_plan_name() {
3162        let schema1 = Arc::new(Schema::empty());
3163        let default_name_exec = EmptyExec::new(schema1);
3164        assert_eq!(default_name_exec.name(), "EmptyExec");
3165
3166        let schema2 = Arc::new(Schema::empty());
3167        let renamed_exec = RenamedEmptyExec::new(schema2);
3168        assert_eq!(renamed_exec.name(), "MyRenamedEmptyExec");
3169        assert_eq!(RenamedEmptyExec::static_name(), "MyRenamedEmptyExec");
3170    }
3171
3172    #[test]
3173    fn test_execution_plan_downcast_delegates_to_downcast_delegate() {
3174        let schema = Arc::new(Schema::empty());
3175        let inner: Arc<dyn ExecutionPlan> = Arc::new(EmptyExec::new(schema));
3176        let wrapped: Arc<dyn ExecutionPlan> = Arc::new(DowncastDelegatingExec(inner));
3177        let nested: Arc<dyn ExecutionPlan> =
3178            Arc::new(DowncastDelegatingExec(Arc::clone(&wrapped)));
3179
3180        for plan in [wrapped.as_ref(), nested.as_ref()] {
3181            assert!(!plan.is::<DowncastDelegatingExec>());
3182            assert!(plan.downcast_ref::<DowncastDelegatingExec>().is_none());
3183            assert!(plan.is::<EmptyExec>());
3184            assert!(plan.downcast_ref::<EmptyExec>().is_some());
3185            assert!(!plan.is::<RenamedEmptyExec>());
3186            assert!(plan.downcast_ref::<RenamedEmptyExec>().is_none());
3187        }
3188    }
3189
3190    /// A compilation test to ensure that the `ExecutionPlan::name()` method can
3191    /// be called from a trait object.
3192    /// Related ticket: https://github.com/apache/datafusion/pull/11047
3193    #[expect(unused)]
3194    fn use_execution_plan_as_trait_object(plan: &dyn ExecutionPlan) {
3195        let _ = plan.name();
3196    }
3197
3198    #[test]
3199    fn buffer_exec_does_not_need_data_exchange() {
3200        let schema = Arc::new(Schema::empty());
3201        let input: Arc<dyn ExecutionPlan> = Arc::new(MockExec::new(vec![], schema));
3202        let buffer: Arc<dyn ExecutionPlan> = Arc::new(BufferExec::new(input, 1024));
3203
3204        assert!(!need_data_exchange(buffer));
3205    }
3206
3207    #[test]
3208    fn test_check_not_null_constraints_accept_non_null() -> Result<()> {
3209        check_not_null_constraints(
3210            RecordBatch::try_new(
3211                Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, true)])),
3212                vec![Arc::new(Int32Array::from(vec![Some(1), Some(2), Some(3)]))],
3213            )?,
3214            &vec![0],
3215        )?;
3216        Ok(())
3217    }
3218
3219    #[test]
3220    fn test_check_not_null_constraints_reject_null() -> Result<()> {
3221        let result = check_not_null_constraints(
3222            RecordBatch::try_new(
3223                Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, true)])),
3224                vec![Arc::new(Int32Array::from(vec![Some(1), None, Some(3)]))],
3225            )?,
3226            &vec![0],
3227        );
3228        assert!(result.is_err());
3229        assert_eq!(
3230            result.err().unwrap().strip_backtrace(),
3231            "Execution error: Invalid batch column at '0' has null but schema specifies non-nullable",
3232        );
3233        Ok(())
3234    }
3235
3236    #[test]
3237    fn test_check_not_null_constraints_with_run_end_array() -> Result<()> {
3238        // some null value inside REE array
3239        let run_ends = Int32Array::from(vec![1, 2, 3, 4]);
3240        let values = Int32Array::from(vec![Some(0), None, Some(1), None]);
3241        let run_end_array = RunArray::try_new(&run_ends, &values)?;
3242        let result = check_not_null_constraints(
3243            RecordBatch::try_new(
3244                Arc::new(Schema::new(vec![Field::new(
3245                    "a",
3246                    run_end_array.data_type().to_owned(),
3247                    true,
3248                )])),
3249                vec![Arc::new(run_end_array)],
3250            )?,
3251            &vec![0],
3252        );
3253        assert!(result.is_err());
3254        assert_eq!(
3255            result.err().unwrap().strip_backtrace(),
3256            "Execution error: Invalid batch column at '0' has null but schema specifies non-nullable",
3257        );
3258        Ok(())
3259    }
3260
3261    #[test]
3262    fn test_check_not_null_constraints_with_dictionary_array_with_null() -> Result<()> {
3263        let values = Arc::new(Int32Array::from(vec![Some(1), None, Some(3), Some(4)]));
3264        let keys = Int32Array::from(vec![0, 1, 2, 3]);
3265        let dictionary = DictionaryArray::new(keys, values);
3266        let result = check_not_null_constraints(
3267            RecordBatch::try_new(
3268                Arc::new(Schema::new(vec![Field::new(
3269                    "a",
3270                    dictionary.data_type().to_owned(),
3271                    true,
3272                )])),
3273                vec![Arc::new(dictionary)],
3274            )?,
3275            &vec![0],
3276        );
3277        assert!(result.is_err());
3278        assert_eq!(
3279            result.err().unwrap().strip_backtrace(),
3280            "Execution error: Invalid batch column at '0' has null but schema specifies non-nullable",
3281        );
3282        Ok(())
3283    }
3284
3285    #[test]
3286    fn test_check_not_null_constraints_with_dictionary_masking_null() -> Result<()> {
3287        // some null value marked out by dictionary array
3288        let values = Arc::new(Int32Array::from(vec![
3289            Some(1),
3290            None, // this null value is masked by dictionary keys
3291            Some(3),
3292            Some(4),
3293        ]));
3294        let keys = Int32Array::from(vec![0, /*1,*/ 2, 3]);
3295        let dictionary = DictionaryArray::new(keys, values);
3296        check_not_null_constraints(
3297            RecordBatch::try_new(
3298                Arc::new(Schema::new(vec![Field::new(
3299                    "a",
3300                    dictionary.data_type().to_owned(),
3301                    true,
3302                )])),
3303                vec![Arc::new(dictionary)],
3304            )?,
3305            &vec![0],
3306        )?;
3307        Ok(())
3308    }
3309
3310    #[test]
3311    fn test_check_not_null_constraints_on_null_type() -> Result<()> {
3312        // null value of Null type
3313        let result = check_not_null_constraints(
3314            RecordBatch::try_new(
3315                Arc::new(Schema::new(vec![Field::new("a", DataType::Null, true)])),
3316                vec![Arc::new(NullArray::new(3))],
3317            )?,
3318            &vec![0],
3319        );
3320        assert!(result.is_err());
3321        assert_eq!(
3322            result.err().unwrap().strip_backtrace(),
3323            "Execution error: Invalid batch column at '0' has null but schema specifies non-nullable",
3324        );
3325        Ok(())
3326    }
3327}