From 090e8b92d4173a759ef85ff9f536d548ecc977f4 Mon Sep 17 00:00:00 2001 From: Qi Zhu Date: Thu, 3 Dec 2026 15:00:44 +0800 Subject: [PATCH] Let a sort pushdown Exact answer split into more partitions A source that can only serve an ordering by splitting into more sorted partitions may now answer Exact with more partitions. PushdownSort turns a single-partition sort above it into a SortPreservingMergeExec with the sort's fetch, sharing the buffer budget across the partitions. A per-partition sort, or an Inexact answer that changes the partitioning, is left alone. --- .../tests/physical_optimizer/pushdown_sort.rs | 141 ++++++++++++++++++ .../tests/physical_optimizer/test_utils.rs | 15 +- .../physical-optimizer/src/pushdown_sort.rs | 39 +++++ .../physical-plan/src/execution_plan.rs | 5 + datafusion/physical-plan/src/sort_pushdown.rs | 7 +- 5 files changed, 204 insertions(+), 3 deletions(-) diff --git a/datafusion/core/tests/physical_optimizer/pushdown_sort.rs b/datafusion/core/tests/physical_optimizer/pushdown_sort.rs index fbcb1e619d9eb..daa222f596771 100644 --- a/datafusion/core/tests/physical_optimizer/pushdown_sort.rs +++ b/datafusion/core/tests/physical_optimizer/pushdown_sort.rs @@ -1555,3 +1555,144 @@ async fn test_sort_pushdown_exact_partitioned_fetch_through_projection_returns_t assert_batches_eq!(expected, &batches); Ok(()) } + +// ============================================================================ +// EXACT WITH MORE PARTITIONS +// ============================================================================ + +/// A scan with one partition that answers `Exact` for any ordering by splitting into +/// `partitions` partitions, each in the requested order. +fn splitting_scan(exact: bool, partitions: usize) -> Arc { + Arc::new( + TestScan::new(schema(), vec![]) + .with_exact_pushdown(exact) + .with_pushdown_partition_count(partitions), + ) +} + +#[test] +fn test_sort_pushdown_exact_more_partitions_becomes_merge() { + // The sort needed one partition; the source now has three sorted ones, so the + // sort becomes a merge with the fetch applied per partition and to the merge. + let a = sort_expr("a", &schema()); + let ordering = LexOrdering::new(vec![a]).unwrap(); + let plan = sort_exec_with_fetch(ordering, Some(10), splitting_scan(true, 3)); + + insta::assert_snapshot!( + OptimizationTest::new(plan, PushdownSort::new(), true), + @r" + OptimizationTest: + input: + - SortExec: TopK(fetch=10), expr=[a@0 ASC], preserve_partitioning=[false] + - TestScan + output: + Ok: + - SortPreservingMergeExec: [a@0 ASC], fetch=10 + - BufferExec: capacity=357913941 + - LocalLimitExec: fetch=10 + - TestScan: requested_ordering=[a@0 ASC] + " + ); +} + +#[test] +fn test_sort_pushdown_exact_more_partitions_without_fetch() { + let a = sort_expr("a", &schema()); + let ordering = LexOrdering::new(vec![a]).unwrap(); + let plan = sort_exec(ordering, splitting_scan(true, 3)); + + insta::assert_snapshot!( + OptimizationTest::new(plan, PushdownSort::new(), true), + @r" + OptimizationTest: + input: + - SortExec: expr=[a@0 ASC], preserve_partitioning=[false] + - TestScan + output: + Ok: + - SortPreservingMergeExec: [a@0 ASC] + - BufferExec: capacity=357913941 + - TestScan: requested_ordering=[a@0 ASC] + " + ); +} + +#[test] +fn test_sort_pushdown_exact_more_partitions_under_merge() { + // A per-partition sort under a merge: the merge already combines every + // partition, so the extra partitions need nothing new. + let a = sort_expr("a", &schema()); + let ordering = LexOrdering::new(vec![a]).unwrap(); + let sort = sort_exec_with_fetch_and_preserve_partitioning( + ordering.clone(), + Some(10), + splitting_scan(true, 3), + ); + let plan = sort_preserving_merge_exec_with_fetch(ordering, sort, 10); + + insta::assert_snapshot!( + OptimizationTest::new(plan, PushdownSort::new(), true), + @r" + OptimizationTest: + input: + - SortPreservingMergeExec: [a@0 ASC], fetch=10 + - SortExec: TopK(fetch=10), expr=[a@0 ASC], preserve_partitioning=[true] + - TestScan + output: + Ok: + - SortPreservingMergeExec: [a@0 ASC], fetch=10 + - BufferExec: capacity=1073741824 + - LocalLimitExec: fetch=10 + - TestScan: requested_ordering=[a@0 ASC] + " + ); +} + +#[test] +fn test_sort_pushdown_exact_more_partitions_keeps_partition_local_sort() { + // A per-partition sort without a merge above: its parent relies on the + // partitioning, so the plan is left alone. + let a = sort_expr("a", &schema()); + let ordering = LexOrdering::new(vec![a]).unwrap(); + let plan = sort_exec_with_fetch_and_preserve_partitioning( + ordering, + None, + splitting_scan(true, 3), + ); + + insta::assert_snapshot!( + OptimizationTest::new(plan, PushdownSort::new(), true), + @r" + OptimizationTest: + input: + - SortExec: expr=[a@0 ASC], preserve_partitioning=[true] + - TestScan + output: + Ok: + - SortExec: expr=[a@0 ASC], preserve_partitioning=[true] + - TestScan + " + ); +} + +#[test] +fn test_sort_pushdown_inexact_more_partitions_unchanged() { + // `Inexact` must keep the partitioning; an answer that does not is ignored. + let a = sort_expr("a", &schema()); + let ordering = LexOrdering::new(vec![a]).unwrap(); + let plan = sort_exec_with_fetch(ordering, Some(10), splitting_scan(false, 3)); + + insta::assert_snapshot!( + OptimizationTest::new(plan, PushdownSort::new(), true), + @r" + OptimizationTest: + input: + - SortExec: TopK(fetch=10), expr=[a@0 ASC], preserve_partitioning=[false] + - TestScan + output: + Ok: + - SortExec: TopK(fetch=10), expr=[a@0 ASC], preserve_partitioning=[false] + - TestScan + " + ); +} diff --git a/datafusion/core/tests/physical_optimizer/test_utils.rs b/datafusion/core/tests/physical_optimizer/test_utils.rs index 441d1b10a5b30..f41d4909df039 100644 --- a/datafusion/core/tests/physical_optimizer/test_utils.rs +++ b/datafusion/core/tests/physical_optimizer/test_utils.rs @@ -943,6 +943,9 @@ pub struct TestScan { supports_fetch: bool, /// The fetch (LIMIT) value pushed into this scan via `with_fetch()`. fetch: Option, + /// If set, the scan returned by `try_pushdown_sort` has this many partitions, as a + /// source that splits a group to serve the ordering would. + pushdown_partition_count: Option, } impl TestScan { @@ -979,6 +982,7 @@ impl TestScan { exact_pushdown: false, supports_fetch: false, fetch: None, + pushdown_partition_count: None, } } @@ -999,6 +1003,12 @@ impl TestScan { self } + /// Set the number of partitions the scan has after `try_pushdown_sort`. + pub fn with_pushdown_partition_count(mut self, partition_count: usize) -> Self { + self.pushdown_partition_count = Some(partition_count); + self + } + /// Set the number of output partitions reported by this scan. pub fn with_partition_count(mut self, partition_count: usize) -> Self { let eq_properties = self.plan_properties.equivalence_properties().clone(); @@ -1128,6 +1138,9 @@ impl ExecutionPlan for TestScan { let mut new_scan = self.clone(); new_scan.requested_ordering = requested_ordering; + if let Some(partition_count) = self.pushdown_partition_count { + new_scan = new_scan.with_partition_count(partition_count); + } if self.exact_pushdown { // Update plan properties to reflect the guaranteed ordering @@ -1138,7 +1151,7 @@ impl ExecutionPlan for TestScan { ); new_scan.plan_properties = Arc::new(PlanProperties::new( eq_properties, - self.plan_properties.output_partitioning().clone(), + new_scan.plan_properties.output_partitioning().clone(), EmissionType::Incremental, Boundedness::Bounded, )); diff --git a/datafusion/physical-optimizer/src/pushdown_sort.rs b/datafusion/physical-optimizer/src/pushdown_sort.rs index d1d7e0b1b9c3a..0cedc3a52ee7c 100644 --- a/datafusion/physical-optimizer/src/pushdown_sort.rs +++ b/datafusion/physical-optimizer/src/pushdown_sort.rs @@ -190,7 +190,40 @@ fn pushdown_sorts( // Try to push the sort requirement down through the plan tree // Each node type defines its own pushdown behavior via try_pushdown_sort() + let input_partitions = sort_input.output_partitioning().partition_count(); match sort_input.try_pushdown_sort(required_ordering)? { + SortOrderPushdownResult::Exact { inner } + if inner.output_partitioning().partition_count() != input_partitions => + { + // The source split into more partitions, each in the requested order. + // A sort that needed a single partition becomes a merge of them, with + // the fetch applied to every partition and to the merge. A sort that + // kept its partitions has a parent that relies on them, so leave it. + if sort_exec.preserve_partitioning() { + return Ok(Transformed::no(plan)); + } + let inner = match sort_exec.fetch() { + Some(fetch) => push_down_limits( + Arc::new(LocalLimitExec::new(inner, fetch)), + stats_ctx, + )?, + None => inner, + }; + // As in the merge pattern above, a buffer takes over the sort's + // buffering so the merge does not stall on I/O. The source chose the + // partition count, which can be large, and a partition whose rows sort + // after another's keeps reading until its buffer is full, so the + // partitions share `buffer_capacity` instead of each taking all of it. + // A partition still buffers at least one batch. + let partitions = inner.output_partitioning().partition_count(); + let per_partition = (buffer_capacity / partitions).max(1); + let buffered: Arc = + Arc::new(BufferExec::new(inner, per_partition)); + let merge = + SortPreservingMergeExec::new(required_ordering.clone(), buffered) + .with_fetch(sort_exec.fetch()); + Ok(Transformed::yes(Arc::new(merge))) + } SortOrderPushdownResult::Exact { inner } => { // Data source guarantees perfect ordering - remove the Sort operator. // @@ -210,6 +243,12 @@ fn pushdown_sorts( Ok(Transformed::yes(inner)) } } + SortOrderPushdownResult::Inexact { inner } + if inner.output_partitioning().partition_count() != input_partitions => + { + // `Inexact` must keep the partitioning; the sort above relies on it. + Ok(Transformed::no(plan)) + } SortOrderPushdownResult::Inexact { inner } => { // Data source is optimized for the ordering but not perfectly sorted // Keep the Sort operator but use the optimized input diff --git a/datafusion/physical-plan/src/execution_plan.rs b/datafusion/physical-plan/src/execution_plan.rs index 0901d41ed66f9..a67504e6a3b11 100644 --- a/datafusion/physical-plan/src/execution_plan.rs +++ b/datafusion/physical-plan/src/execution_plan.rs @@ -1048,6 +1048,11 @@ pub trait ExecutionPlan: Any + Debug + DisplayAs + Send + Sync { /// For transparent nodes (that preserve ordering), implement this to delegate to /// children and wrap the result with a new instance of this node. /// + /// An `Exact` answer may have more output partitions than this node, for example + /// one file per partition, as long as every partition is in the requested order; + /// the optimizer then merges the partitions where a single stream is required. An + /// `Inexact` answer must keep this node's partitioning. + /// /// Default implementation returns `Unsupported`. fn try_pushdown_sort( &self, diff --git a/datafusion/physical-plan/src/sort_pushdown.rs b/datafusion/physical-plan/src/sort_pushdown.rs index 49a9bc2507e99..7f6e91e68fe22 100644 --- a/datafusion/physical-plan/src/sort_pushdown.rs +++ b/datafusion/physical-plan/src/sort_pushdown.rs @@ -18,7 +18,9 @@ pub enum SortOrderPushdownResult { /// The source can guarantee exact ordering (data is perfectly sorted). /// /// When this is returned, the optimizer can safely remove the Sort operator - /// entirely since the data source guarantees the requested ordering. + /// entirely since the data source guarantees the requested ordering. `inner` may + /// have more partitions than the node it replaces, each in the requested order; a + /// sort that needed a single partition then becomes a merge of them. Exact { /// The optimized node that provides exact ordering inner: T, @@ -28,7 +30,8 @@ pub enum SortOrderPushdownResult { /// This indicates the data source has been optimized (e.g., reordered files/row groups /// based on statistics, enabled reverse scanning) but the data may not be perfectly /// sorted. The optimizer should keep the Sort operator but benefits from the - /// optimization (e.g., faster TopK queries due to early termination). + /// optimization (e.g., faster TopK queries due to early termination). `inner` + /// keeps the partitioning of the node it replaces. Inexact { /// The optimized node that provides approximate ordering inner: T,