Apache DataFusion SQL Query Engine
Update `ExecutionPlan` to know about sortedness and repartitioning optimizer pass respect the invariants (#1776)
Andrew Lamb071f14ade65b
diff --git a/ballista/rust/core/src/execution_plans/distributed_query.rs b/ballista/rust/core/src/execution_plans/distributed_query.rsindex 619cc9bc92..22160158cb 100644--- a/ballista/rust/core/src/execution_plans/distributed_query.rs+++ b/ballista/rust/core/src/execution_plans/distributed_query.rs@@ -33,6 +33,7 @@ use crate::utils::WrappedStream;use datafusion::arrow::datatypes::{Schema, SchemaRef};use datafusion::error::{DataFusionError, Result};use datafusion::logical_plan::LogicalPlan;+use datafusion::physical_plan::expressions::PhysicalSortExpr;use datafusion::physical_plan::{DisplayFormatType, ExecutionPlan, Partitioning, RecordBatchStream,SendableRecordBatchStream, Statistics,@@ -82,6 +83,14 @@ impl ExecutionPlan for DistributedQueryExec {Partitioning::UnknownPartitioning(1)}+ fn output_ordering(&self) -> Option<&[PhysicalSortExpr]> {+ None+ }++ fn relies_on_input_order(&self) -> bool {+ false+ }+fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {vec![]}diff --git a/ballista/rust/core/src/execution_plans/shuffle_reader.rs b/ballista/rust/core/src/execution_plans/shuffle_reader.rsindex ea3381deb0..7482c1843e 100644--- a/ballista/rust/core/src/execution_plans/shuffle_reader.rs+++ b/ballista/rust/core/src/execution_plans/shuffle_reader.rs@@ -28,6 +28,7 @@ use datafusion::arrow::datatypes::SchemaRef;use datafusion::arrow::error::Result as ArrowResult;use datafusion::arrow::record_batch::RecordBatch;use datafusion::execution::runtime_env::RuntimeEnv;+use datafusion::physical_plan::expressions::PhysicalSortExpr;use datafusion::physical_plan::metrics::{ExecutionPlanMetricsSet, MetricBuilder, MetricsSet,};@@ -85,6 +86,14 @@ impl ExecutionPlan for ShuffleReaderExec {Partitioning::UnknownPartitioning(self.partition.len())}+ fn output_ordering(&self) -> Option<&[PhysicalSortExpr]> {+ None+ }++ fn relies_on_input_order(&self) -> bool {+ false+ }+fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {vec![]}diff --git a/ballista/rust/core/src/execution_plans/shuffle_writer.rs b/ballista/rust/core/src/execution_plans/shuffle_writer.rsindex 724bb3518d..fbce0653a9 100644--- a/ballista/rust/core/src/execution_plans/shuffle_writer.rs+++ b/ballista/rust/core/src/execution_plans/shuffle_writer.rs@@ -20,6 +20,7 @@//! partition is re-partitioned and streamed to disk in Arrow IPC format. Future stages of the query//! will use the ShuffleReaderExec to read these results.+use datafusion::physical_plan::expressions::PhysicalSortExpr;use parking_lot::Mutex;use std::fs::File;use std::iter::Iterator;@@ -334,6 +335,14 @@ impl ExecutionPlan for ShuffleWriterExec {self.plan.output_partitioning()}+ fn output_ordering(&self) -> Option<&[PhysicalSortExpr]> {+ None+ }++ fn relies_on_input_order(&self) -> bool {+ false+ }+fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {vec![self.plan.clone()]}diff --git a/ballista/rust/core/src/execution_plans/unresolved_shuffle.rs b/ballista/rust/core/src/execution_plans/unresolved_shuffle.rsindex e14c1ebf0e..90b7c79319 100644--- a/ballista/rust/core/src/execution_plans/unresolved_shuffle.rs+++ b/ballista/rust/core/src/execution_plans/unresolved_shuffle.rs@@ -23,6 +23,7 @@ use crate::serde::scheduler::PartitionLocation;use async_trait::async_trait;use datafusion::arrow::datatypes::SchemaRef;use datafusion::execution::runtime_env::RuntimeEnv;+use datafusion::physical_plan::expressions::PhysicalSortExpr;use datafusion::physical_plan::{DisplayFormatType, ExecutionPlan, Partitioning, SendableRecordBatchStream, Statistics,};@@ -85,6 +86,14 @@ impl ExecutionPlan for UnresolvedShuffleExec {Partitioning::UnknownPartitioning(self.output_partition_count)}+ fn output_ordering(&self) -> Option<&[PhysicalSortExpr]> {+ None+ }++ fn relies_on_input_order(&self) -> bool {+ false+ }+fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {vec![]}diff --git a/ballista/rust/executor/src/collect.rs b/ballista/rust/executor/src/collect.rsindex 12c26ef587..37a7f7bb0d 100644--- a/ballista/rust/executor/src/collect.rs+++ b/ballista/rust/executor/src/collect.rs@@ -28,6 +28,7 @@ use datafusion::arrow::{};use datafusion::error::DataFusionError;use datafusion::execution::runtime_env::RuntimeEnv;+use datafusion::physical_plan::expressions::PhysicalSortExpr;use datafusion::physical_plan::{DisplayFormatType, ExecutionPlan, Partitioning, SendableRecordBatchStream, Statistics,};@@ -62,6 +63,10 @@ impl ExecutionPlan for CollectExec {Partitioning::UnknownPartitioning(1)}+ fn output_ordering(&self) -> Option<&[PhysicalSortExpr]> {+ None+ }+fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {vec![self.plan.clone()]}diff --git a/datafusion/src/physical_optimizer/repartition.rs b/datafusion/src/physical_optimizer/repartition.rsindex 1f4505324a..ae074d2893 100644--- a/datafusion/src/physical_optimizer/repartition.rs+++ b/datafusion/src/physical_optimizer/repartition.rs@@ -20,12 +20,102 @@ use std::sync::Arc;use super::optimizer::PhysicalOptimizerRule;use crate::physical_plan::Partitioning::*;-use crate::physical_plan::{- empty::EmptyExec, repartition::RepartitionExec, ExecutionPlan,-};+use crate::physical_plan::{repartition::RepartitionExec, ExecutionPlan};use crate::{error::Result, execution::context::ExecutionConfig};-/// Optimizer that introduces repartition to introduce more parallelism in the plan+/// Optimizer that introduces repartition to introduce more+/// parallelism in the plan+///+/// For example, given an input such as:+///+///+/// ```text+/// ┌─────────────────────────────────┐+/// │ │+/// │ ExecutionPlan │+/// │ │+/// └─────────────────────────────────┘+/// ▲ ▲+/// │ │+/// ┌─────┘ └─────┐+/// │ │+/// │ │+/// │ │+/// ┌───────────┐ ┌───────────┐+/// │ │ │ │+/// │ batch A1 │ │ batch B1 │+/// │ │ │ │+/// ├───────────┤ ├───────────┤+/// │ │ │ │+/// │ batch A2 │ │ batch B2 │+/// │ │ │ │+/// ├───────────┤ ├───────────┤+/// │ │ │ │+/// │ batch A3 │ │ batch B3 │+/// │ │ │ │+/// └───────────┘ └───────────┘+///+/// Input Input+/// A B+/// ```+///+/// This optimizer will attempt to add a `RepartitionExec` to increase+/// the parallism (to 3 in this case)+///+/// ```text+/// ┌─────────────────────────────────┐+/// │ │+/// │ ExecutionPlan │+/// │ │+/// └─────────────────────────────────┘+/// ▲ ▲ ▲ Input now has 3+/// │ │ │ partitions+/// ┌───────┘ │ └───────┐+/// │ │ │+/// │ │ │+/// ┌───────────┐ ┌───────────┐ ┌───────────┐+/// │ │ │ │ │ │+/// │ batch A1 │ │ batch A3 │ │ batch B3 │+/// │ │ │ │ │ │+/// ├───────────┤ ├───────────┤ ├───────────┤+/// │ │ │ │ │ │+/// │ batch B2 │ │ batch B1 │ │ batch A2 │+/// │ │ │ │ │ │+/// └───────────┘ └───────────┘ └───────────┘+/// ▲ ▲ ▲+/// │ │ │+/// └─────────┐ │ ┌──────────┘+/// │ │ │+/// │ │ │+/// ┌─────────────────────────────────┐ batches are+/// │ RepartitionExec(3) │ repartitioned+/// │ RoundRobin │+/// │ │+/// └─────────────────────────────────┘+/// ▲ ▲+/// │ │+/// ┌─────┘ └─────┐+/// │ │+/// │ │+/// │ │+/// ┌───────────┐ ┌───────────┐+/// │ │ │ │+/// │ batch A1 │ │ batch B1 │+/// │ │ │ │+/// ├───────────┤ ├───────────┤+/// │ │ │ │+/// │ batch A2 │ │ batch B2 │+/// │ │ │ │+/// ├───────────┤ ├───────────┤+/// │ │ │ │+/// │ batch A3 │ │ batch B3 │+/// │ │ │ │+/// └───────────┘ └───────────┘+///+///+/// Input Input+/// A B+/// ```#[derive(Default)]pub struct Repartition {}@@ -36,18 +126,59 @@ impl Repartition {}}+/// Recursively visits all `plan`s puts and then optionally adds a+/// `RepartitionExec` at the output of `plan` to match+/// `target_partitions` in an attempt to increase the overall parallelism.+///+/// It does so using depth first scan of the tree, and repartitions+/// any plan that:+///+/// 1. Has fewer partitions than `target_partitions`+///+/// 2. Has a direct parent that `benefits_from_input_partitioning`+///+/// 3. Does not have a parent that `relies_on_input_order` unless there+/// is an intervening node that does not `maintain_input_order`+///+/// if `can_reorder` is false, means that the output of this node+/// can not be reordered as as something upstream is relying on that order+///+/// If 'would_benefit` is false, the upstream operator doesn't+/// benefit from additional repartition+///fn optimize_partitions(target_partitions: usize,plan: Arc<dyn ExecutionPlan>,- should_repartition: bool,+ can_reorder: bool,+ would_benefit: bool,) -> Result<Arc<dyn ExecutionPlan>> {- // Recurse into children bottom-up (added nodes should be as deep as possible)+ // Recurse into children bottom-up (attempt to repartition as+ // early as possible)let new_plan = if plan.children().is_empty() {// leaf node - don't replace children- plan.clone()+ plan} else {- let should_repartition_children = plan.should_repartition_children();+ let can_reorder_children =+ match (plan.relies_on_input_order(), plan.maintains_input_order()) {+ (true, _) => {+ // `plan` itself relies on the order of its+ // children, so don't reorder them!+ false+ }+ (false, false) => {+ // `plan` may reorder the input itself, so no need+ // to preserve the order of any children+ true+ }+ (false, true) => {+ // `plan` will maintain the order, so we can only+ // repartition children if it is ok to reorder the+ // output of this node+ can_reorder+ }+ };+let children = plan.children().iter()@@ -55,14 +186,16 @@ fn optimize_partitions(optimize_partitions(target_partitions,child.clone(),- should_repartition_children,+ can_reorder_children,+ plan.benefits_from_input_partitioning(),)}).collect::<Result<_>>()?;plan.with_new_children(children)?};- let perform_repartition = match new_plan.output_partitioning() {+ // decide if we should bother trying to repartition the output of this plan+ let could_repartition = match new_plan.output_partitioning() {// Apply when underlying node has less than `self.target_partitions` amount of concurrencyRoundRobinBatch(x) => x < target_partitions,UnknownPartitioning(x) => x < target_partitions,@@ -71,11 +204,7 @@ fn optimize_partitions(Hash(_, _) => false,};- // TODO: EmptyExec causes failures with RepartitionExec- // But also not very useful to inlude- let is_empty_exec = plan.as_any().downcast_ref::<EmptyExec>().is_some();-- if perform_repartition && should_repartition && !is_empty_exec {+ if would_benefit && could_repartition && can_reorder {Ok(Arc::new(RepartitionExec::try_new(new_plan,RoundRobinBatch(target_partitions),@@ -95,7 +224,7 @@ impl PhysicalOptimizerRule for Repartition {if config.target_partitions == 1 {Ok(plan)} else {- optimize_partitions(config.target_partitions, plan, false)+ optimize_partitions(config.target_partitions, plan, false, false)}}@@ -105,15 +234,19 @@ impl PhysicalOptimizerRule for Repartition {}#[cfg(test)]mod tests {+ use arrow::compute::SortOptions;use arrow::datatypes::{DataType, Field, Schema, SchemaRef};use super::*;use crate::datasource::PartitionedFile;- use crate::physical_plan::expressions::col;+ use crate::physical_plan::expressions::{col, PhysicalSortExpr};use crate::physical_plan::file_format::{FileScanConfig, ParquetExec};use crate::physical_plan::filter::FilterExec;use crate::physical_plan::hash_aggregate::{AggregateMode, HashAggregateExec};use crate::physical_plan::limit::{GlobalLimitExec, LocalLimitExec};+ use crate::physical_plan::projection::ProjectionExec;+ use crate::physical_plan::sorts::sort::SortExec;+ use crate::physical_plan::sorts::sort_preserving_merge::SortPreservingMergeExec;use crate::physical_plan::union::UnionExec;use crate::physical_plan::{displayable, Statistics};use crate::test::object_store::TestObjectStore;@@ -137,10 +270,34 @@ mod tests {))}+ fn sort_preserving_merge_exec(+ input: Arc<dyn ExecutionPlan>,+ ) -> Arc<dyn ExecutionPlan> {+ let expr = vec![PhysicalSortExpr {+ expr: col("c1", &schema()).unwrap(),+ options: arrow::compute::SortOptions::default(),+ }];++ Arc::new(SortPreservingMergeExec::new(expr, input))+ }+fn filter_exec(input: Arc<dyn ExecutionPlan>) -> Arc<dyn ExecutionPlan> {Arc::new(FilterExec::try_new(col("c1", &schema()).unwrap(), input).unwrap())}+ fn sort_exec(input: Arc<dyn ExecutionPlan>) -> Arc<dyn ExecutionPlan> {+ let sort_exprs = vec![PhysicalSortExpr {+ expr: col("c1", &schema()).unwrap(),+ options: SortOptions::default(),+ }];+ Arc::new(SortExec::try_new(sort_exprs, input).unwrap())+ }++ fn projection_exec(input: Arc<dyn ExecutionPlan>) -> Arc<dyn ExecutionPlan> {+ let exprs = vec![(col("c1", &schema()).unwrap(), "c1".to_string())];+ Arc::new(ProjectionExec::try_new(exprs, input).unwrap())+ }+fn hash_aggregate(input: Arc<dyn ExecutionPlan>) -> Arc<dyn ExecutionPlan> {let schema = schema();Arc::new(@@ -178,38 +335,46 @@ mod tests {.collect()}+ /// Runs the repartition optimizer and asserts the plan against the expected+ macro_rules! assert_optimized {+ ($EXPECTED_LINES: expr, $PLAN: expr) => {+ let expected_lines: Vec<&str> = $EXPECTED_LINES.iter().map(|s| *s).collect();++ // run optimizer+ let optimizer = Repartition {};+ let optimized = optimizer+ .optimize($PLAN, &ExecutionConfig::new().with_target_partitions(10))?;++ // Now format correctly+ let plan = displayable(optimized.as_ref()).indent().to_string();+ let actual_lines = trim_plan_display(&plan);++ assert_eq!(+ &expected_lines, &actual_lines,+ "\n\nexpected:\n\n{:#?}\nactual:\n\n{:#?}\n\n",+ expected_lines, actual_lines+ );+ };+ }+#[test]fn added_repartition_to_single_partition() -> Result<()> {- let optimizer = Repartition {};+ let plan = hash_aggregate(parquet_exec());- let optimized = optimizer.optimize(- hash_aggregate(parquet_exec()),- &ExecutionConfig::new().with_target_partitions(10),- )?;-- let plan = displayable(optimized.as_ref()).indent().to_string();-- let expected = &[+ let expected = ["HashAggregateExec: mode=Final, gby=[], aggr=[]","HashAggregateExec: mode=Partial, gby=[], aggr=[]","RepartitionExec: partitioning=RoundRobinBatch(10)","ParquetExec: limit=None, partitions=[x]",];- assert_eq!(&trim_plan_display(&plan), &expected);+ assert_optimized!(expected, plan);Ok(())}#[test]fn repartition_deepest_node() -> Result<()> {- let optimizer = Repartition {};-- let optimized = optimizer.optimize(- hash_aggregate(filter_exec(parquet_exec())),- &ExecutionConfig::new().with_target_partitions(10),- )?;-- let plan = displayable(optimized.as_ref()).indent().to_string();+ let plan = hash_aggregate(filter_exec(parquet_exec()));let expected = &["HashAggregateExec: mode=Final, gby=[], aggr=[]",@@ -219,20 +384,64 @@ mod tests {"ParquetExec: limit=None, partitions=[x]",];- assert_eq!(&trim_plan_display(&plan), &expected);+ assert_optimized!(expected, plan);Ok(())}#[test]- fn repartition_ignores_limit() -> Result<()> {- let optimizer = Repartition {};+ fn repartition_unsorted_limit() -> Result<()> {+ let plan = limit_exec(filter_exec(parquet_exec()));- let optimized = optimizer.optimize(- hash_aggregate(limit_exec(filter_exec(limit_exec(parquet_exec())))),- &ExecutionConfig::new().with_target_partitions(10),- )?;+ let expected = &[+ "GlobalLimitExec: limit=100",+ "LocalLimitExec: limit=100",+ "FilterExec: c1@0",+ // nothing sorts the data, so the local limit doesn't require sorted data either+ "RepartitionExec: partitioning=RoundRobinBatch(10)",+ "ParquetExec: limit=None, partitions=[x]",+ ];- let plan = displayable(optimized.as_ref()).indent().to_string();+ assert_optimized!(expected, plan);+ Ok(())+ }++ #[test]+ fn repartition_sorted_limit() -> Result<()> {+ let plan = limit_exec(sort_exec(parquet_exec()));++ let expected = &[+ "GlobalLimitExec: limit=100",+ "LocalLimitExec: limit=100",+ // data is sorted so can't repartition here+ "SortExec: [c1@0 ASC]",+ "ParquetExec: limit=None, partitions=[x]",+ ];++ assert_optimized!(expected, plan);+ Ok(())+ }++ #[test]+ fn repartition_sorted_limit_with_filter() -> Result<()> {+ let plan = limit_exec(filter_exec(sort_exec(parquet_exec())));++ let expected = &[+ "GlobalLimitExec: limit=100",+ "LocalLimitExec: limit=100",+ "FilterExec: c1@0",+ // data is sorted so can't repartition here even though+ // filter would benefit from parallelism, the answers might be wrong+ "SortExec: [c1@0 ASC]",+ "ParquetExec: limit=None, partitions=[x]",+ ];++ assert_optimized!(expected, plan);+ Ok(())+ }++ #[test]+ fn repartition_ignores_limit() -> Result<()> {+ let plan = hash_aggregate(limit_exec(filter_exec(limit_exec(parquet_exec()))));let expected = &["HashAggregateExec: mode=Final, gby=[], aggr=[]",@@ -241,6 +450,7 @@ mod tests {"GlobalLimitExec: limit=100","LocalLimitExec: limit=100","FilterExec: c1@0",+ // repartition should happen prior to the filter to maximize parallelism"RepartitionExec: partitioning=RoundRobinBatch(10)","GlobalLimitExec: limit=100","LocalLimitExec: limit=100",@@ -248,20 +458,15 @@ mod tests {"ParquetExec: limit=None, partitions=[x]",];- assert_eq!(&trim_plan_display(&plan), &expected);+ assert_optimized!(expected, plan);Ok(())}+ // repartition works differently for limit when there is a sort below it+#[test]fn repartition_ignores_union() -> Result<()> {- let optimizer = Repartition {};-- let optimized = optimizer.optimize(- Arc::new(UnionExec::new(vec![parquet_exec(); 5])),- &ExecutionConfig::new().with_target_partitions(5),- )?;-- let plan = displayable(optimized.as_ref()).indent().to_string();+ let plan = Arc::new(UnionExec::new(vec![parquet_exec(); 5]));let expected = &["UnionExec",@@ -273,7 +478,92 @@ mod tests {"ParquetExec: limit=None, partitions=[x]",];- assert_eq!(&trim_plan_display(&plan), &expected);+ assert_optimized!(expected, plan);+ Ok(())+ }++ #[test]+ fn repartition_ignores_sort_preserving_merge() -> Result<()> {+ let plan = sort_preserving_merge_exec(parquet_exec());++ let expected = &[+ "SortPreservingMergeExec: [c1@0 ASC]",+ // Expect no repartition of SortPreservingMergeExec+ "ParquetExec: limit=None, partitions=[x]",+ ];++ assert_optimized!(expected, plan);+ Ok(())+ }++ #[test]+ fn repartition_does_not_repartition_transitively() -> Result<()> {+ let plan = sort_preserving_merge_exec(projection_exec(parquet_exec()));++ let expected = &[+ "SortPreservingMergeExec: [c1@0 ASC]",+ // Expect no repartition of SortPreservingMergeExec+ // even though there is a projection exec between it+ "ProjectionExec: expr=[c1@0 as c1]",+ "ParquetExec: limit=None, partitions=[x]",+ ];++ assert_optimized!(expected, plan);+ Ok(())+ }++ #[test]+ fn repartition_transitively_past_sort_with_projection() -> Result<()> {+ let plan = sort_preserving_merge_exec(sort_exec(projection_exec(parquet_exec())));++ let expected = &[+ "SortPreservingMergeExec: [c1@0 ASC]",+ // Expect repartition on the input to the sort (as it can benefit from additional parallelism)+ "SortExec: [c1@0 ASC]",+ "ProjectionExec: expr=[c1@0 as c1]",+ "RepartitionExec: partitioning=RoundRobinBatch(10)",+ "ParquetExec: limit=None, partitions=[x]",+ ];++ assert_optimized!(expected, plan);+ Ok(())+ }++ #[test]+ fn repartition_transitively_past_sort_with_filter() -> Result<()> {+ let plan = sort_preserving_merge_exec(sort_exec(filter_exec(parquet_exec())));++ let expected = &[+ "SortPreservingMergeExec: [c1@0 ASC]",+ // Expect repartition on the input to the sort (as it can benefit from additional parallelism)+ "SortExec: [c1@0 ASC]",+ "FilterExec: c1@0",+ "RepartitionExec: partitioning=RoundRobinBatch(10)",+ "ParquetExec: limit=None, partitions=[x]",+ ];++ assert_optimized!(expected, plan);+ Ok(())+ }++ #[test]+ fn repartition_transitively_past_sort_with_projection_and_filter() -> Result<()> {+ let plan = sort_preserving_merge_exec(sort_exec(projection_exec(filter_exec(+ parquet_exec(),+ ))));++ let expected = &[+ "SortPreservingMergeExec: [c1@0 ASC]",+ // Expect repartition on the input to the sort (as it can benefit from additional parallelism)+ "SortExec: [c1@0 ASC]",+ "ProjectionExec: expr=[c1@0 as c1]",+ "FilterExec: c1@0",+ // repartition is lowest down+ "RepartitionExec: partitioning=RoundRobinBatch(10)",+ "ParquetExec: limit=None, partitions=[x]",+ ];++ assert_optimized!(expected, plan);Ok(())}}diff --git a/datafusion/src/physical_plan/analyze.rs b/datafusion/src/physical_plan/analyze.rsindex 0a810b9159..6857ad5322 100644--- a/datafusion/src/physical_plan/analyze.rs+++ b/datafusion/src/physical_plan/analyze.rs@@ -30,6 +30,7 @@ use crate::{use arrow::{array::StringBuilder, datatypes::SchemaRef, record_batch::RecordBatch};use futures::StreamExt;+use super::expressions::PhysicalSortExpr;use super::{stream::RecordBatchReceiverStream, Distribution, SendableRecordBatchStream};use crate::execution::runtime_env::RuntimeEnv;use async_trait::async_trait;@@ -82,6 +83,14 @@ impl ExecutionPlan for AnalyzeExec {Partitioning::UnknownPartitioning(1)}+ fn output_ordering(&self) -> Option<&[PhysicalSortExpr]> {+ None+ }++ fn relies_on_input_order(&self) -> bool {+ false+ }+fn with_new_children(&self,mut children: Vec<Arc<dyn ExecutionPlan>>,diff --git a/datafusion/src/physical_plan/coalesce_batches.rs b/datafusion/src/physical_plan/coalesce_batches.rsindex ec238ad68c..0d6fe38636 100644--- a/datafusion/src/physical_plan/coalesce_batches.rs+++ b/datafusion/src/physical_plan/coalesce_batches.rs@@ -38,6 +38,7 @@ use async_trait::async_trait;use futures::stream::{Stream, StreamExt};use log::debug;+use super::expressions::PhysicalSortExpr;use super::metrics::{BaselineMetrics, MetricsSet};use super::{metrics::ExecutionPlanMetricsSet, Statistics};@@ -97,6 +98,14 @@ impl ExecutionPlan for CoalesceBatchesExec {self.input.output_partitioning()}+ fn output_ordering(&self) -> Option<&[PhysicalSortExpr]> {+ None+ }++ fn relies_on_input_order(&self) -> bool {+ false+ }+fn with_new_children(&self,children: Vec<Arc<dyn ExecutionPlan>>,diff --git a/datafusion/src/physical_plan/coalesce_partitions.rs b/datafusion/src/physical_plan/coalesce_partitions.rsindex 2e3a5521d6..20b5487337 100644--- a/datafusion/src/physical_plan/coalesce_partitions.rs+++ b/datafusion/src/physical_plan/coalesce_partitions.rs@@ -31,6 +31,7 @@ use arrow::record_batch::RecordBatch;use arrow::{datatypes::SchemaRef, error::Result as ArrowResult};use super::common::AbortOnDropMany;+use super::expressions::PhysicalSortExpr;use super::metrics::{BaselineMetrics, ExecutionPlanMetricsSet, MetricsSet};use super::{RecordBatchStream, Statistics};use crate::error::{DataFusionError, Result};@@ -86,6 +87,14 @@ impl ExecutionPlan for CoalescePartitionsExec {Partitioning::UnknownPartitioning(1)}+ fn output_ordering(&self) -> Option<&[PhysicalSortExpr]> {+ None+ }++ fn relies_on_input_order(&self) -> bool {+ false+ }+fn with_new_children(&self,children: Vec<Arc<dyn ExecutionPlan>>,diff --git a/datafusion/src/physical_plan/cross_join.rs b/datafusion/src/physical_plan/cross_join.rsindex e4369c180c..82ee5618f5 100644--- a/datafusion/src/physical_plan/cross_join.rs+++ b/datafusion/src/physical_plan/cross_join.rs@@ -27,6 +27,7 @@ use arrow::record_batch::RecordBatch;use futures::{Stream, TryStreamExt};+use super::expressions::PhysicalSortExpr;use super::{coalesce_partitions::CoalescePartitionsExec, join_utils::check_join_is_valid,ColumnStatistics, Statistics,@@ -137,6 +138,14 @@ impl ExecutionPlan for CrossJoinExec {self.right.output_partitioning()}+ fn output_ordering(&self) -> Option<&[PhysicalSortExpr]> {+ None+ }++ fn relies_on_input_order(&self) -> bool {+ false+ }+async fn execute(&self,partition: usize,diff --git a/datafusion/src/physical_plan/empty.rs b/datafusion/src/physical_plan/empty.rsindex 33a09d97bb..9b1c71c0e0 100644--- a/datafusion/src/physical_plan/empty.rs+++ b/datafusion/src/physical_plan/empty.rs@@ -28,6 +28,7 @@ use arrow::array::NullArray;use arrow::datatypes::{DataType, Field, Schema, SchemaRef};use arrow::record_batch::RecordBatch;+use super::expressions::PhysicalSortExpr;use super::{common, SendableRecordBatchStream, Statistics};use crate::execution::runtime_env::RuntimeEnv;@@ -98,6 +99,10 @@ impl ExecutionPlan for EmptyExec {Partitioning::UnknownPartitioning(1)}+ fn output_ordering(&self) -> Option<&[PhysicalSortExpr]> {+ None+ }+fn with_new_children(&self,children: Vec<Arc<dyn ExecutionPlan>>,diff --git a/datafusion/src/physical_plan/explain.rs b/datafusion/src/physical_plan/explain.rsindex eb18926f94..0955655a19 100644--- a/datafusion/src/physical_plan/explain.rs+++ b/datafusion/src/physical_plan/explain.rs@@ -30,7 +30,7 @@ use crate::{};use arrow::{array::StringBuilder, datatypes::SchemaRef, record_batch::RecordBatch};-use super::SendableRecordBatchStream;+use super::{expressions::PhysicalSortExpr, SendableRecordBatchStream};use crate::execution::runtime_env::RuntimeEnv;use crate::physical_plan::metrics::{ExecutionPlanMetricsSet, MemTrackingMetrics};use async_trait::async_trait;@@ -89,6 +89,14 @@ impl ExecutionPlan for ExplainExec {Partitioning::UnknownPartitioning(1)}+ fn output_ordering(&self) -> Option<&[PhysicalSortExpr]> {+ None+ }++ fn relies_on_input_order(&self) -> bool {+ false+ }+fn with_new_children(&self,children: Vec<Arc<dyn ExecutionPlan>>,diff --git a/datafusion/src/physical_plan/file_format/avro.rs b/datafusion/src/physical_plan/file_format/avro.rsindex b389686650..ba0873d78b 100644--- a/datafusion/src/physical_plan/file_format/avro.rs+++ b/datafusion/src/physical_plan/file_format/avro.rs@@ -19,6 +19,7 @@#[cfg(feature = "avro")]use crate::avro_to_arrow;use crate::error::{DataFusionError, Result};+use crate::physical_plan::expressions::PhysicalSortExpr;use crate::physical_plan::{DisplayFormatType, ExecutionPlan, Partitioning, SendableRecordBatchStream, Statistics,};@@ -74,6 +75,14 @@ impl ExecutionPlan for AvroExec {Partitioning::UnknownPartitioning(self.base_config.file_groups.len())}+ fn output_ordering(&self) -> Option<&[PhysicalSortExpr]> {+ None+ }++ fn relies_on_input_order(&self) -> bool {+ false+ }+fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {Vec::new()}diff --git a/datafusion/src/physical_plan/file_format/csv.rs b/datafusion/src/physical_plan/file_format/csv.rsindex 4cf70f6e5c..709705b506 100644--- a/datafusion/src/physical_plan/file_format/csv.rs+++ b/datafusion/src/physical_plan/file_format/csv.rs@@ -18,6 +18,7 @@//! Execution plan for reading CSV filesuse crate::error::{DataFusionError, Result};+use crate::physical_plan::expressions::PhysicalSortExpr;use crate::physical_plan::{DisplayFormatType, ExecutionPlan, Partitioning, SendableRecordBatchStream, Statistics,};@@ -88,6 +89,14 @@ impl ExecutionPlan for CsvExec {Partitioning::UnknownPartitioning(self.base_config.file_groups.len())}+ fn relies_on_input_order(&self) -> bool {+ false+ }++ fn output_ordering(&self) -> Option<&[PhysicalSortExpr]> {+ None+ }+fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {// this is a leaf node and has no childrenvec![]diff --git a/datafusion/src/physical_plan/file_format/json.rs b/datafusion/src/physical_plan/file_format/json.rsindex ac413062ca..6c5ffcd99e 100644--- a/datafusion/src/physical_plan/file_format/json.rs+++ b/datafusion/src/physical_plan/file_format/json.rs@@ -20,6 +20,7 @@ use async_trait::async_trait;use crate::error::{DataFusionError, Result};use crate::execution::runtime_env::RuntimeEnv;+use crate::physical_plan::expressions::PhysicalSortExpr;use crate::physical_plan::{DisplayFormatType, ExecutionPlan, Partitioning, SendableRecordBatchStream, Statistics,};@@ -65,6 +66,14 @@ impl ExecutionPlan for NdJsonExec {Partitioning::UnknownPartitioning(self.base_config.file_groups.len())}+ fn output_ordering(&self) -> Option<&[PhysicalSortExpr]> {+ None+ }++ fn relies_on_input_order(&self) -> bool {+ false+ }+fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {Vec::new()}diff --git a/datafusion/src/physical_plan/file_format/parquet.rs b/datafusion/src/physical_plan/file_format/parquet.rsindex 40acf5a51c..539904e583 100644--- a/datafusion/src/physical_plan/file_format/parquet.rs+++ b/datafusion/src/physical_plan/file_format/parquet.rs@@ -24,6 +24,7 @@ use std::{any::Any, convert::TryInto};use crate::datasource::file_format::parquet::ChunkObjectReader;use crate::datasource::object_store::ObjectStore;use crate::datasource::PartitionedFile;+use crate::physical_plan::expressions::PhysicalSortExpr;use crate::{error::{DataFusionError, Result},logical_plan::{Column, Expr},@@ -174,6 +175,14 @@ impl ExecutionPlan for ParquetExec {Partitioning::UnknownPartitioning(self.base_config.file_groups.len())}+ fn output_ordering(&self) -> Option<&[PhysicalSortExpr]> {+ None+ }++ fn relies_on_input_order(&self) -> bool {+ false+ }+fn with_new_children(&self,children: Vec<Arc<dyn ExecutionPlan>>,diff --git a/datafusion/src/physical_plan/filter.rs b/datafusion/src/physical_plan/filter.rsindex a48d11236d..41250582e9 100644--- a/datafusion/src/physical_plan/filter.rs+++ b/datafusion/src/physical_plan/filter.rs@@ -23,6 +23,7 @@ use std::pin::Pin;use std::sync::Arc;use std::task::{Context, Poll};+use super::expressions::PhysicalSortExpr;use super::{RecordBatchStream, SendableRecordBatchStream, Statistics};use crate::error::{DataFusionError, Result};use crate::physical_plan::{@@ -104,6 +105,19 @@ impl ExecutionPlan for FilterExec {self.input.output_partitioning()}+ fn output_ordering(&self) -> Option<&[PhysicalSortExpr]> {+ self.input.output_ordering()+ }++ fn maintains_input_order(&self) -> bool {+ // tell optimizer this operator doesn't reorder its input+ true+ }++ fn relies_on_input_order(&self) -> bool {+ false+ }+fn with_new_children(&self,children: Vec<Arc<dyn ExecutionPlan>>,diff --git a/datafusion/src/physical_plan/hash_aggregate.rs b/datafusion/src/physical_plan/hash_aggregate.rsindex 2b1a59efb6..b727cdd2e9 100644--- a/datafusion/src/physical_plan/hash_aggregate.rs+++ b/datafusion/src/physical_plan/hash_aggregate.rs@@ -52,6 +52,7 @@ use crate::execution::runtime_env::RuntimeEnv;use async_trait::async_trait;use super::common::AbortOnDropSingle;+use super::expressions::PhysicalSortExpr;use super::metrics::{self, BaselineMetrics, ExecutionPlanMetricsSet, MetricsSet, RecordOutput,};@@ -208,6 +209,14 @@ impl ExecutionPlan for HashAggregateExec {self.input.output_partitioning()}+ fn output_ordering(&self) -> Option<&[PhysicalSortExpr]> {+ None+ }++ fn relies_on_input_order(&self) -> bool {+ false+ }+async fn execute(&self,partition: usize,@@ -1148,6 +1157,10 @@ mod tests {Partitioning::UnknownPartitioning(1)}+ fn output_ordering(&self) -> Option<&[PhysicalSortExpr]> {+ None+ }+fn with_new_children(&self,_: Vec<Arc<dyn ExecutionPlan>>,diff --git a/datafusion/src/physical_plan/hash_join.rs b/datafusion/src/physical_plan/hash_join.rsindex 39479f9485..d276ac2e72 100644--- a/datafusion/src/physical_plan/hash_join.rs+++ b/datafusion/src/physical_plan/hash_join.rs@@ -54,6 +54,7 @@ use hashbrown::raw::RawTable;use super::{coalesce_partitions::CoalescePartitionsExec,+ expressions::PhysicalSortExpr,join_utils::{build_join_schema, check_join_is_valid, ColumnIndex, JoinOn, JoinSide},};use super::{@@ -278,6 +279,14 @@ impl ExecutionPlan for HashJoinExec {self.right.output_partitioning()}+ fn output_ordering(&self) -> Option<&[PhysicalSortExpr]> {+ None+ }++ fn relies_on_input_order(&self) -> bool {+ false+ }+async fn execute(&self,partition: usize,diff --git a/datafusion/src/physical_plan/limit.rs b/datafusion/src/physical_plan/limit.rsindex 587780d9de..f150c56012 100644--- a/datafusion/src/physical_plan/limit.rs+++ b/datafusion/src/physical_plan/limit.rs@@ -35,6 +35,7 @@ use arrow::datatypes::SchemaRef;use arrow::error::Result as ArrowResult;use arrow::record_batch::RecordBatch;+use super::expressions::PhysicalSortExpr;use super::{metrics::{BaselineMetrics, ExecutionPlanMetricsSet, MetricsSet},RecordBatchStream, SendableRecordBatchStream, Statistics,@@ -99,6 +100,22 @@ impl ExecutionPlan for GlobalLimitExec {Partitioning::UnknownPartitioning(1)}+ fn relies_on_input_order(&self) -> bool {+ self.input.output_ordering().is_some()+ }++ fn maintains_input_order(&self) -> bool {+ true+ }++ fn benefits_from_input_partitioning(&self) -> bool {+ false+ }++ fn output_ordering(&self) -> Option<&[PhysicalSortExpr]> {+ self.input.output_ordering()+ }+fn with_new_children(&self,children: Vec<Arc<dyn ExecutionPlan>>,@@ -232,6 +249,24 @@ impl ExecutionPlan for LocalLimitExec {self.input.output_partitioning()}+ fn relies_on_input_order(&self) -> bool {+ self.input.output_ordering().is_some()+ }++ fn benefits_from_input_partitioning(&self) -> bool {+ false+ }++ // Local limit does not make any attempt to maintain the input+ // sortedness (if there is more than one partition)+ fn output_ordering(&self) -> Option<&[PhysicalSortExpr]> {+ if self.output_partitioning().partition_count() == 1 {+ self.input.output_ordering()+ } else {+ None+ }+ }+fn with_new_children(&self,children: Vec<Arc<dyn ExecutionPlan>>,@@ -300,11 +335,6 @@ impl ExecutionPlan for LocalLimitExec {_ => Statistics::default(),}}-- fn should_repartition_children(&self) -> bool {- // No reason to repartition children as this node is just limiting each input partition.- false- }}/// Truncate a RecordBatch to maximum of n rowsdiff --git a/datafusion/src/physical_plan/memory.rs b/datafusion/src/physical_plan/memory.rsindex 8e5f37953d..cc82083465 100644--- a/datafusion/src/physical_plan/memory.rs+++ b/datafusion/src/physical_plan/memory.rs@@ -22,6 +22,7 @@ use std::any::Any;use std::sync::Arc;use std::task::{Context, Poll};+use super::expressions::PhysicalSortExpr;use super::{common, project_schema, DisplayFormatType, ExecutionPlan, Partitioning,RecordBatchStream, SendableRecordBatchStream, Statistics,@@ -77,6 +78,14 @@ impl ExecutionPlan for MemoryExec {Partitioning::UnknownPartitioning(self.partitions.len())}+ fn output_ordering(&self) -> Option<&[PhysicalSortExpr]> {+ None+ }++ fn relies_on_input_order(&self) -> bool {+ false+ }+fn with_new_children(&self,_: Vec<Arc<dyn ExecutionPlan>>,diff --git a/datafusion/src/physical_plan/mod.rs b/datafusion/src/physical_plan/mod.rsindex 38a19db134..42fc217f24 100644--- a/datafusion/src/physical_plan/mod.rs+++ b/datafusion/src/physical_plan/mod.rs@@ -144,19 +144,71 @@ pub trait ExecutionPlan: Debug + Send + Sync {/// Specifies the output partitioning scheme of this planfn output_partitioning(&self) -> Partitioning;- /// Specifies the data distribution requirements of all the children for this operator+ /// If the output of this operator is sorted, returns `Some(keys)`+ /// with the description of how it was sorted.+ ///+ /// For example, Sort, (obviously) produces sorted output as does+ /// SortPreservingMergeStream. Less obviously `Projection`+ /// produces sorted output if its input was sorted as it does not+ /// reorder the input rows,+ ///+ /// It is safe to return `None` here if your operator does not+ /// have any particular output order here+ fn output_ordering(&self) -> Option<&[PhysicalSortExpr]>;++ /// Specifies the data distribution requirements of all the+ /// children for this operatorfn required_child_distribution(&self) -> Distribution {Distribution::UnspecifiedDistribution}- /// Returns `true` if the direct children of this `ExecutionPlan` should be repartitioned- /// to introduce greater concurrency to the plan+ /// Returns `true` if this operator relies on its inputs being+ /// produced in a certain order (for example that they are sorted+ /// a particular way) for correctness.+ ///+ /// If `true` is returned, DataFusion will not apply certain+ /// optimizations which might reorder the inputs (such as+ /// repartitioning to increase concurrency).+ ///+ /// The default implementation returns `true`+ ///+ /// WARNING: if you override this default and return `false`, your+ /// operator can not rely on datafusion preserving the input order+ /// as it will likely not.+ fn relies_on_input_order(&self) -> bool {+ true+ }++ /// Returns `false` if this operator's implementation may reorder+ /// rows within or between partitions.+ ///+ /// For example, Projection, Filter, and Limit maintain the order+ /// of inputs -- they may transform values (Projection) or not+ /// produce the same number of rows that went in (Filter and+ /// Limit), but the rows that are produced go in the same way.///- /// The default implementation returns `true` unless `Self::required_child_distribution`- /// returns `Distribution::SinglePartition`+ /// DataFusion uses this metadata to apply certain optimizations+ /// such as automatically repartitioning correctly.///- /// Operators that do not benefit from additional partitioning may want to return `false`- fn should_repartition_children(&self) -> bool {+ /// The default implementation returns `false`+ ///+ /// WARNING: if you override this default, you *MUST* ensure that+ /// the operator's maintains the ordering invariant or else+ /// DataFusion may produce incorrect results.+ fn maintains_input_order(&self) -> bool {+ false+ }++ /// Returns `true` if this operator would benefit from+ /// partitioning its input (and thus from more parallelism). For+ /// operators that do very little work the overhead of extra+ /// parallelism may outweigh any benefits+ ///+ /// The default implementation returns `true` unless this operator+ /// has signalled it requiers a single child input partition.+ fn benefits_from_input_partitioning(&self) -> bool {+ // By default try to maximize parallelism with more CPUs if+ // possible!matches!(self.required_child_distribution(),Distribution::SinglePartition@@ -167,6 +219,7 @@ pub trait ExecutionPlan: Debug + Send + Sync {/// will be empty for leaf nodes, will contain a single value for unary nodes, or two/// values for binary nodes (such as joins).fn children(&self) -> Vec<Arc<dyn ExecutionPlan>>;+/// Returns a new plan where all children were replaced by new plans./// The size of `children` must be equal to the size of `ExecutionPlan::children()`.fn with_new_children(diff --git a/datafusion/src/physical_plan/planner.rs b/datafusion/src/physical_plan/planner.rsindex 838f7454a4..24b8378c7b 100644--- a/datafusion/src/physical_plan/planner.rs+++ b/datafusion/src/physical_plan/planner.rs@@ -1881,6 +1881,14 @@ mod tests {Partitioning::UnknownPartitioning(1)}+ fn output_ordering(&self) -> Option<&[PhysicalSortExpr]> {+ None+ }++ fn relies_on_input_order(&self) -> bool {+ false+ }+fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {vec![]}diff --git a/datafusion/src/physical_plan/projection.rs b/datafusion/src/physical_plan/projection.rsindex 4d0cc61c99..5940b64957 100644--- a/datafusion/src/physical_plan/projection.rs+++ b/datafusion/src/physical_plan/projection.rs@@ -34,7 +34,7 @@ use arrow::datatypes::{Field, Schema, SchemaRef};use arrow::error::Result as ArrowResult;use arrow::record_batch::RecordBatch;-use super::expressions::Column;+use super::expressions::{Column, PhysicalSortExpr};use super::metrics::{BaselineMetrics, ExecutionPlanMetricsSet, MetricsSet};use super::{RecordBatchStream, SendableRecordBatchStream, Statistics};use crate::execution::runtime_env::RuntimeEnv;@@ -122,6 +122,19 @@ impl ExecutionPlan for ProjectionExec {self.input.output_partitioning()}+ fn output_ordering(&self) -> Option<&[PhysicalSortExpr]> {+ self.input.output_ordering()+ }++ fn maintains_input_order(&self) -> bool {+ // tell optimizer this operator doesn't reorder its input+ true+ }++ fn relies_on_input_order(&self) -> bool {+ false+ }+fn with_new_children(&self,children: Vec<Arc<dyn ExecutionPlan>>,diff --git a/datafusion/src/physical_plan/repartition.rs b/datafusion/src/physical_plan/repartition.rsindex 86866728cd..55328c40c9 100644--- a/datafusion/src/physical_plan/repartition.rs+++ b/datafusion/src/physical_plan/repartition.rs@@ -32,6 +32,7 @@ use arrow::{compute::take, datatypes::SchemaRef};use tokio_stream::wrappers::UnboundedReceiverStream;use super::common::{AbortOnDropMany, AbortOnDropSingle};+use super::expressions::PhysicalSortExpr;use super::metrics::{self, ExecutionPlanMetricsSet, MetricBuilder, MetricsSet};use super::{RecordBatchStream, SendableRecordBatchStream};use async_trait::async_trait;@@ -146,6 +147,10 @@ impl ExecutionPlan for RepartitionExec {vec![self.input.clone()]}+ fn relies_on_input_order(&self) -> bool {+ false+ }+fn with_new_children(&self,children: Vec<Arc<dyn ExecutionPlan>>,@@ -165,6 +170,10 @@ impl ExecutionPlan for RepartitionExec {self.partitioning.clone()}+ fn output_ordering(&self) -> Option<&[PhysicalSortExpr]> {+ None+ }+async fn execute(&self,partition: usize,diff --git a/datafusion/src/physical_plan/sorts/sort.rs b/datafusion/src/physical_plan/sorts/sort.rsindex 7f7f58104f..1428e1627d 100644--- a/datafusion/src/physical_plan/sorts/sort.rs+++ b/datafusion/src/physical_plan/sorts/sort.rs@@ -445,6 +445,19 @@ impl ExecutionPlan for SortExec {vec![self.input.clone()]}+ fn relies_on_input_order(&self) -> bool {+ // this operator resorts everything+ false+ }++ fn benefits_from_input_partitioning(&self) -> bool {+ false+ }++ fn output_ordering(&self) -> Option<&[PhysicalSortExpr]> {+ Some(&self.expr)+ }+fn with_new_children(&self,children: Vec<Arc<dyn ExecutionPlan>>,diff --git a/datafusion/src/physical_plan/sorts/sort_preserving_merge.rs b/datafusion/src/physical_plan/sorts/sort_preserving_merge.rsindex ddc9ff1f9e..a948ceb975 100644--- a/datafusion/src/physical_plan/sorts/sort_preserving_merge.rs+++ b/datafusion/src/physical_plan/sorts/sort_preserving_merge.rs@@ -128,6 +128,14 @@ impl ExecutionPlan for SortPreservingMergeExec {Distribution::UnspecifiedDistribution}+ fn relies_on_input_order(&self) -> bool {+ true+ }++ fn output_ordering(&self) -> Option<&[PhysicalSortExpr]> {+ Some(&self.expr)+ }+fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {vec![self.input.clone()]}diff --git a/datafusion/src/physical_plan/union.rs b/datafusion/src/physical_plan/union.rsindex d2c170bc27..03c41f4e1d 100644--- a/datafusion/src/physical_plan/union.rs+++ b/datafusion/src/physical_plan/union.rs@@ -27,6 +27,7 @@ use arrow::{datatypes::SchemaRef, record_batch::RecordBatch};use futures::StreamExt;use super::{+ expressions::PhysicalSortExpr,metrics::{ExecutionPlanMetricsSet, MetricsSet},ColumnStatistics, DisplayFormatType, ExecutionPlan, Partitioning, RecordBatchStream,SendableRecordBatchStream, Statistics,@@ -85,6 +86,14 @@ impl ExecutionPlan for UnionExec {Partitioning::UnknownPartitioning(num_partitions)}+ fn output_ordering(&self) -> Option<&[PhysicalSortExpr]> {+ None+ }++ fn relies_on_input_order(&self) -> bool {+ false+ }+fn with_new_children(&self,children: Vec<Arc<dyn ExecutionPlan>>,@@ -144,7 +153,7 @@ impl ExecutionPlan for UnionExec {.unwrap_or_default()}- fn should_repartition_children(&self) -> bool {+ fn benefits_from_input_partitioning(&self) -> bool {false}}diff --git a/datafusion/src/physical_plan/values.rs b/datafusion/src/physical_plan/values.rsindex c3a7ea5c16..da39b3eb4b 100644--- a/datafusion/src/physical_plan/values.rs+++ b/datafusion/src/physical_plan/values.rs@@ -17,6 +17,7 @@//! Values execution plan+use super::expressions::PhysicalSortExpr;use super::{common, SendableRecordBatchStream, Statistics};use crate::error::{DataFusionError, Result};use crate::execution::runtime_env::RuntimeEnv;@@ -119,6 +120,14 @@ impl ExecutionPlan for ValuesExec {Partitioning::UnknownPartitioning(1)}+ fn output_ordering(&self) -> Option<&[PhysicalSortExpr]> {+ None+ }++ fn relies_on_input_order(&self) -> bool {+ false+ }+fn with_new_children(&self,children: Vec<Arc<dyn ExecutionPlan>>,diff --git a/datafusion/src/physical_plan/windows/window_agg_exec.rs b/datafusion/src/physical_plan/windows/window_agg_exec.rsindex 491e0ebf45..163868d078 100644--- a/datafusion/src/physical_plan/windows/window_agg_exec.rs+++ b/datafusion/src/physical_plan/windows/window_agg_exec.rs@@ -20,6 +20,7 @@use crate::error::{DataFusionError, Result};use crate::execution::runtime_env::RuntimeEnv;use crate::physical_plan::common::AbortOnDropSingle;+use crate::physical_plan::expressions::PhysicalSortExpr;use crate::physical_plan::metrics::{BaselineMetrics, ExecutionPlanMetricsSet, MetricsSet,};@@ -114,6 +115,18 @@ impl ExecutionPlan for WindowAggExec {self.input.output_partitioning()}+ fn output_ordering(&self) -> Option<&[PhysicalSortExpr]> {+ self.input.output_ordering()+ }++ fn maintains_input_order(&self) -> bool {+ true+ }++ fn relies_on_input_order(&self) -> bool {+ true+ }+fn required_child_distribution(&self) -> Distribution {if self.window_expr()diff --git a/datafusion/src/test/exec.rs b/datafusion/src/test/exec.rsindex 39b8e5c11f..5a6b27865d 100644--- a/datafusion/src/test/exec.rs+++ b/datafusion/src/test/exec.rs@@ -33,7 +33,6 @@ use arrow::{};use futures::Stream;-use crate::execution::runtime_env::RuntimeEnv;use crate::physical_plan::{common, DisplayFormatType, ExecutionPlan, Partitioning, RecordBatchStream,SendableRecordBatchStream, Statistics,@@ -42,6 +41,9 @@ use crate::{error::{DataFusionError, Result},physical_plan::stream::RecordBatchReceiverStream,};+use crate::{+ execution::runtime_env::RuntimeEnv, physical_plan::expressions::PhysicalSortExpr,+};/// Index into the data that has been returned so far#[derive(Debug, Default, Clone)]@@ -151,6 +153,10 @@ impl ExecutionPlan for MockExec {Partitioning::UnknownPartitioning(1)}+ fn output_ordering(&self) -> Option<&[PhysicalSortExpr]> {+ None+ }+fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {unimplemented!()}@@ -286,6 +292,10 @@ impl ExecutionPlan for BarrierExec {Partitioning::UnknownPartitioning(self.data.len())}+ fn output_ordering(&self) -> Option<&[PhysicalSortExpr]> {+ None+ }+fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {unimplemented!()}@@ -383,6 +393,10 @@ impl ExecutionPlan for ErrorExec {Partitioning::UnknownPartitioning(1)}+ fn output_ordering(&self) -> Option<&[PhysicalSortExpr]> {+ None+ }+fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {unimplemented!()}@@ -459,6 +473,10 @@ impl ExecutionPlan for StatisticsExec {Partitioning::UnknownPartitioning(2)}+ fn output_ordering(&self) -> Option<&[PhysicalSortExpr]> {+ None+ }+fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {vec![]}@@ -560,6 +578,10 @@ impl ExecutionPlan for BlockingExec {Partitioning::UnknownPartitioning(self.n_partitions)}+ fn output_ordering(&self) -> Option<&[PhysicalSortExpr]> {+ None+ }+fn with_new_children(&self,_: Vec<Arc<dyn ExecutionPlan>>,diff --git a/datafusion/tests/custom_sources.rs b/datafusion/tests/custom_sources.rsindex 0e7f733232..926a017f14 100644--- a/datafusion/tests/custom_sources.rs+++ b/datafusion/tests/custom_sources.rs@@ -22,6 +22,7 @@ use arrow::error::Result as ArrowResult;use arrow::record_batch::RecordBatch;use datafusion::from_slice::FromSlice;use datafusion::physical_plan::empty::EmptyExec;+use datafusion::physical_plan::expressions::PhysicalSortExpr;use datafusion::scalar::ScalarValue;use datafusion::{datasource::TableProvider, physical_plan::collect};use datafusion::{@@ -113,6 +114,9 @@ impl ExecutionPlan for CustomExecutionPlan {fn output_partitioning(&self) -> Partitioning {Partitioning::UnknownPartitioning(1)}+ fn output_ordering(&self) -> Option<&[PhysicalSortExpr]> {+ None+ }fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {vec![]}diff --git a/datafusion/tests/provider_filter_pushdown.rs b/datafusion/tests/provider_filter_pushdown.rsindex 3aac5a8f36..203fb7ce56 100644--- a/datafusion/tests/provider_filter_pushdown.rs+++ b/datafusion/tests/provider_filter_pushdown.rs@@ -25,6 +25,7 @@ use datafusion::execution::context::ExecutionContext;use datafusion::execution::runtime_env::RuntimeEnv;use datafusion::logical_plan::Expr;use datafusion::physical_plan::common::SizedRecordBatchStream;+use datafusion::physical_plan::expressions::PhysicalSortExpr;use datafusion::physical_plan::metrics::{ExecutionPlanMetricsSet, MemTrackingMetrics};use datafusion::physical_plan::{DisplayFormatType, ExecutionPlan, Partitioning, SendableRecordBatchStream, Statistics,@@ -69,6 +70,10 @@ impl ExecutionPlan for CustomPlan {Partitioning::UnknownPartitioning(1)}+ fn output_ordering(&self) -> Option<&[PhysicalSortExpr]> {+ None+ }+fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {vec![]}diff --git a/datafusion/tests/statistics.rs b/datafusion/tests/statistics.rsindex 3bc3720c67..c5fba894e6 100644--- a/datafusion/tests/statistics.rs+++ b/datafusion/tests/statistics.rs@@ -25,8 +25,9 @@ use datafusion::{error::{DataFusionError, Result},logical_plan::Expr,physical_plan::{- project_schema, ColumnStatistics, DisplayFormatType, ExecutionPlan, Partitioning,- SendableRecordBatchStream, Statistics,+ expressions::PhysicalSortExpr, project_schema, ColumnStatistics,+ DisplayFormatType, ExecutionPlan, Partitioning, SendableRecordBatchStream,+ Statistics,},prelude::ExecutionContext,scalar::ScalarValue,@@ -119,6 +120,10 @@ impl ExecutionPlan for StatisticsValidation {Partitioning::UnknownPartitioning(2)}+ fn output_ordering(&self) -> Option<&[PhysicalSortExpr]> {+ None+ }+fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {vec![]}diff --git a/datafusion/tests/user_defined_plan.rs b/datafusion/tests/user_defined_plan.rsindex a4d9e97b1c..1757804737 100644--- a/datafusion/tests/user_defined_plan.rs+++ b/datafusion/tests/user_defined_plan.rs@@ -74,6 +74,7 @@ use datafusion::{logical_plan::{Expr, LogicalPlan, UserDefinedLogicalNode},optimizer::{optimizer::OptimizerRule, utils::optimize_children},physical_plan::{+ expressions::PhysicalSortExpr,planner::{DefaultPhysicalPlanner, ExtensionPlanner},DisplayFormatType, Distribution, ExecutionPlan, Partitioning, PhysicalPlanner,RecordBatchStream, SendableRecordBatchStream, Statistics,@@ -432,6 +433,14 @@ impl ExecutionPlan for TopKExec {Partitioning::UnknownPartitioning(1)}+ fn output_ordering(&self) -> Option<&[PhysicalSortExpr]> {+ None+ }++ fn relies_on_input_order(&self) -> bool {+ false+ }+fn required_child_distribution(&self) -> Distribution {Distribution::SinglePartition}