Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
141 changes: 141 additions & 0 deletions datafusion/core/tests/physical_optimizer/pushdown_sort.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<dyn ExecutionPlan> {
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
"
);
}
15 changes: 14 additions & 1 deletion datafusion/core/tests/physical_optimizer/test_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -943,6 +943,9 @@ pub struct TestScan {
supports_fetch: bool,
/// The fetch (LIMIT) value pushed into this scan via `with_fetch()`.
fetch: Option<usize>,
/// 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<usize>,
}

impl TestScan {
Expand Down Expand Up @@ -979,6 +982,7 @@ impl TestScan {
exact_pushdown: false,
supports_fetch: false,
fetch: None,
pushdown_partition_count: None,
}
}

Expand All @@ -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();
Expand Down Expand Up @@ -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
Expand All @@ -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,
));
Expand Down
39 changes: 39 additions & 0 deletions datafusion/physical-optimizer/src/pushdown_sort.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<dyn ExecutionPlan> =
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.
//
Expand All @@ -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
Expand Down
5 changes: 5 additions & 0 deletions datafusion/physical-plan/src/execution_plan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
7 changes: 5 additions & 2 deletions datafusion/physical-plan/src/sort_pushdown.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@ pub enum SortOrderPushdownResult<T> {
/// 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,
Expand All @@ -28,7 +30,8 @@ pub enum SortOrderPushdownResult<T> {
/// 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,
Expand Down