diff --git a/datafusion/core/tests/physical_optimizer/pushdown_sort.rs b/datafusion/core/tests/physical_optimizer/pushdown_sort.rs index 4a81d11949707..fbcb1e619d9eb 100644 --- a/datafusion/core/tests/physical_optimizer/pushdown_sort.rs +++ b/datafusion/core/tests/physical_optimizer/pushdown_sort.rs @@ -16,6 +16,7 @@ use arrow::datatypes::{DataType, Field, Schema}; use arrow::record_batch::RecordBatch; use datafusion::prelude::SessionContext; use datafusion_common::config::ConfigOptions; +use datafusion_common::tree_node::{TreeNode, TreeNodeRecursion}; use datafusion_common::{Result, assert_batches_eq}; use datafusion_physical_expr::expressions; use datafusion_physical_expr_common::physical_expr::PhysicalExpr; @@ -23,15 +24,18 @@ use datafusion_physical_expr_common::sort_expr::LexOrdering; use datafusion_physical_optimizer::PhysicalOptimizerRule; use datafusion_physical_optimizer::ensure_requirements::EnsureRequirements; use datafusion_physical_optimizer::pushdown_sort::PushdownSort; +use datafusion_physical_plan::coop::CooperativeExec; +use datafusion_physical_plan::limit::GlobalLimitExec; use datafusion_physical_plan::sorts::sort::SortExec; use datafusion_physical_plan::{ExecutionPlan, collect}; use std::sync::Arc; use crate::physical_optimizer::test_utils::{ - OptimizationTest, TestScan, coalesce_partitions_exec, inexact_memory_exec, - parquet_exec, parquet_exec_with_sort, projection_exec, projection_exec_with_alias, - repartition_exec, schema, simple_projection_exec, sort_exec, sort_exec_with_fetch, - sort_exec_with_fetch_and_preserve_partitioning, sort_expr, sort_expr_named, + OptimizationTest, TestScan, coalesce_partitions_exec, exact_memory_exec, + inexact_memory_exec, parquet_exec, parquet_exec_with_sort, projection_exec, + projection_exec_with_alias, repartition_exec, schema, simple_projection_exec, + sort_exec, sort_exec_with_fetch, sort_exec_with_fetch_and_preserve_partitioning, + sort_expr, sort_expr_named, sort_preserving_merge_exec_with_fetch, test_scan_with_ordering, }; @@ -1205,3 +1209,349 @@ fn test_sort_pushdown_exact_preserves_fetch_with_source_support() { " ); } + +/// A scan that answers `Exact` for any ordering, with `partitions` output +/// partitions, that takes a fetch when `supports_fetch`. +fn exact_scan(partitions: usize, supports_fetch: bool) -> Arc { + Arc::new( + TestScan::new(schema(), vec![]) + .with_exact_pushdown(true) + .with_supports_fetch(supports_fetch) + .with_partition_count(partitions), + ) +} + +#[test] +fn test_sort_pushdown_exact_pushes_fetch_through_projection() { + // The limit of the eliminated SortExec passes the projection and goes + // into the source. + let schema = schema(); + let a = sort_expr("a", &schema); + let projection = simple_projection_exec(exact_scan(1, true), vec![0, 1]); + + let ordering = LexOrdering::new(vec![a.reverse()]).unwrap(); + let plan = sort_exec_with_fetch(ordering, Some(10), projection); + + insta::assert_snapshot!( + OptimizationTest::new(plan, PushdownSort::new(), true), + @r" + OptimizationTest: + input: + - SortExec: TopK(fetch=10), expr=[a@0 DESC NULLS LAST], preserve_partitioning=[false] + - ProjectionExec: expr=[a@0 as a, b@1 as b] + - TestScan + output: + Ok: + - ProjectionExec: expr=[a@0 as a, b@1 as b] + - TestScan: requested_ordering=[a@0 DESC NULLS LAST], fetch=10 + " + ); +} + +#[test] +fn test_sort_pushdown_exact_pushes_fetch_through_cooperative_and_projection() { + let schema = schema(); + let a = sort_expr("a", &schema); + let cooperative = Arc::new(CooperativeExec::new(exact_scan(1, true))); + let projection = simple_projection_exec(cooperative, vec![0, 1]); + + let ordering = LexOrdering::new(vec![a.reverse()]).unwrap(); + let plan = sort_exec_with_fetch(ordering, Some(10), projection); + + insta::assert_snapshot!( + OptimizationTest::new(plan, PushdownSort::new(), true), + @r" + OptimizationTest: + input: + - SortExec: TopK(fetch=10), expr=[a@0 DESC NULLS LAST], preserve_partitioning=[false] + - ProjectionExec: expr=[a@0 as a, b@1 as b] + - CooperativeExec + - TestScan + output: + Ok: + - ProjectionExec: expr=[a@0 as a, b@1 as b] + - CooperativeExec + - TestScan: requested_ordering=[a@0 DESC NULLS LAST], fetch=10 + " + ); +} + +#[test] +fn test_sort_pushdown_exact_places_limit_below_projection() { + // The source can't take a fetch: the limit goes right above it, so the + // projection only sees the rows that are kept. + let schema = schema(); + let a = sort_expr("a", &schema); + let projection = simple_projection_exec(exact_scan(1, false), vec![0, 1]); + + let ordering = LexOrdering::new(vec![a.reverse()]).unwrap(); + let plan = sort_exec_with_fetch(ordering, Some(10), projection); + + insta::assert_snapshot!( + OptimizationTest::new(plan, PushdownSort::new(), true), + @r" + OptimizationTest: + input: + - SortExec: TopK(fetch=10), expr=[a@0 DESC NULLS LAST], preserve_partitioning=[false] + - ProjectionExec: expr=[a@0 as a, b@1 as b] + - TestScan + output: + Ok: + - ProjectionExec: expr=[a@0 as a, b@1 as b] + - GlobalLimitExec: skip=0, fetch=10 + - TestScan: requested_ordering=[a@0 DESC NULLS LAST] + " + ); +} + +#[test] +fn test_sort_pushdown_exact_keeps_offset_above_pushed_fetch() { + // `OFFSET 5 LIMIT 10`: the outer limit stays, the sort's fetch of 15 goes + // into the source. + let schema = schema(); + let a = sort_expr("a", &schema); + let projection = simple_projection_exec(exact_scan(1, true), vec![0, 1]); + + let ordering = LexOrdering::new(vec![a.reverse()]).unwrap(); + let sort = sort_exec_with_fetch(ordering, Some(15), projection); + let plan = Arc::new(GlobalLimitExec::new(sort, 5, Some(10))); + + insta::assert_snapshot!( + OptimizationTest::new(plan, PushdownSort::new(), true), + @r" + OptimizationTest: + input: + - GlobalLimitExec: skip=5, fetch=10 + - SortExec: TopK(fetch=15), expr=[a@0 DESC NULLS LAST], preserve_partitioning=[false] + - ProjectionExec: expr=[a@0 as a, b@1 as b] + - TestScan + output: + Ok: + - GlobalLimitExec: skip=5, fetch=10 + - ProjectionExec: expr=[a@0 as a, b@1 as b] + - TestScan: requested_ordering=[a@0 DESC NULLS LAST], fetch=15 + " + ); +} + +#[test] +fn test_sort_pushdown_exact_partitioned_pushes_fetch_through_projection() { + // SPM -> SortExec(preserve_partitioning): each partition keeps its own + // fetch, in the source below the projection. + let schema = schema(); + let a = sort_expr("a", &schema); + let projection = simple_projection_exec(exact_scan(4, true), vec![0, 1]); + + let ordering = LexOrdering::new(vec![a.reverse()]).unwrap(); + let sort = sort_exec_with_fetch_and_preserve_partitioning( + ordering.clone(), + Some(10), + projection, + ); + 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 DESC NULLS LAST], fetch=10 + - SortExec: TopK(fetch=10), expr=[a@0 DESC NULLS LAST], preserve_partitioning=[true] + - ProjectionExec: expr=[a@0 as a, b@1 as b] + - TestScan + output: + Ok: + - SortPreservingMergeExec: [a@0 DESC NULLS LAST], fetch=10 + - BufferExec: capacity=1073741824 + - ProjectionExec: expr=[a@0 as a, b@1 as b] + - TestScan: requested_ordering=[a@0 DESC NULLS LAST], fetch=10 + " + ); +} + +#[test] +fn test_sort_pushdown_exact_partitioned_places_local_limit_below_projection() { + // The source can't take a fetch: a per-partition limit, not a global one, + // goes right above it. + let schema = schema(); + let a = sort_expr("a", &schema); + let projection = simple_projection_exec(exact_scan(4, false), vec![0, 1]); + + let ordering = LexOrdering::new(vec![a.reverse()]).unwrap(); + let sort = sort_exec_with_fetch_and_preserve_partitioning( + ordering.clone(), + Some(10), + projection, + ); + 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 DESC NULLS LAST], fetch=10 + - SortExec: TopK(fetch=10), expr=[a@0 DESC NULLS LAST], preserve_partitioning=[true] + - ProjectionExec: expr=[a@0 as a, b@1 as b] + - TestScan + output: + Ok: + - SortPreservingMergeExec: [a@0 DESC NULLS LAST], fetch=10 + - BufferExec: capacity=1073741824 + - ProjectionExec: expr=[a@0 as a, b@1 as b] + - LocalLimitExec: fetch=10 + - TestScan: requested_ordering=[a@0 DESC NULLS LAST] + " + ); +} + +#[test] +fn test_sort_pushdown_standalone_partitioned_exact_places_local_limit_below_projection() { + // A standalone SortExec(preserve_partitioning) keeps a per-partition fetch. + let schema = schema(); + let a = sort_expr("a", &schema); + let projection = simple_projection_exec(exact_scan(4, false), vec![0, 1]); + + let ordering = LexOrdering::new(vec![a.reverse()]).unwrap(); + let plan = + sort_exec_with_fetch_and_preserve_partitioning(ordering, Some(10), projection); + + insta::assert_snapshot!( + OptimizationTest::new(plan, PushdownSort::new(), true), + @r" + OptimizationTest: + input: + - SortExec: TopK(fetch=10), expr=[a@0 DESC NULLS LAST], preserve_partitioning=[true] + - ProjectionExec: expr=[a@0 as a, b@1 as b] + - TestScan + output: + Ok: + - ProjectionExec: expr=[a@0 as a, b@1 as b] + - LocalLimitExec: fetch=10 + - TestScan: requested_ordering=[a@0 DESC NULLS LAST] + " + ); +} + +#[test] +fn test_sort_pushdown_exact_keeps_limit_above_repartition() { + // A round robin repartition splits one input partition into several, so a + // per-partition limit can't go below it. + let schema = schema(); + let a = sort_expr("a", &schema); + let projection = simple_projection_exec(exact_scan(1, true), vec![0, 1]); + let repartition = repartition_exec(projection); + + let ordering = LexOrdering::new(vec![a.reverse()]).unwrap(); + let sort = sort_exec_with_fetch_and_preserve_partitioning( + ordering.clone(), + Some(10), + repartition, + ); + 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 DESC NULLS LAST], fetch=10 + - SortExec: TopK(fetch=10), expr=[a@0 DESC NULLS LAST], preserve_partitioning=[true] + - RepartitionExec: partitioning=RoundRobinBatch(10), input_partitions=1 + - ProjectionExec: expr=[a@0 as a, b@1 as b] + - TestScan + output: + Ok: + - SortPreservingMergeExec: [a@0 DESC NULLS LAST], fetch=10 + - BufferExec: capacity=1073741824 + - LocalLimitExec: fetch=10 + - RepartitionExec: partitioning=RoundRobinBatch(10), input_partitions=1, maintains_sort_order=true + - ProjectionExec: expr=[a@0 as a, b@1 as b] + - TestScan: requested_ordering=[a@0 DESC NULLS LAST] + " + ); +} + +/// One batch with column `a`. +fn batch_of(schema: &Arc, values: Vec) -> Result { + Ok(RecordBatch::try_new( + Arc::clone(schema), + vec![Arc::new(Int64Array::from(values)) as ArrayRef], + )?) +} + +/// Runs `PushdownSort` on `plan`, checks that a scan below a projection holds +/// `scan_fetch`, and returns the rows of the optimized plan. +async fn optimize_and_collect( + plan: Arc, + scan_fetch: usize, +) -> Result> { + let mut config = ConfigOptions::new(); + config.optimizer.enable_sort_pushdown = true; + let optimized = PushdownSort::new().optimize(plan, &config)?; + + let mut fetch_below_projection = None; + optimized.apply(|node| { + if node.name() == "ProjectionExec" { + fetch_below_projection = node.children()[0].fetch(); + return Ok(TreeNodeRecursion::Stop); + } + Ok(TreeNodeRecursion::Continue) + })?; + assert_eq!(fetch_below_projection, Some(scan_fetch)); + + let ctx = SessionContext::new(); + collect(optimized, ctx.task_ctx()).await +} + +#[tokio::test] +async fn test_sort_pushdown_exact_fetch_through_projection_returns_top_rows() -> Result<()> +{ + let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int64, false)])); + let source = exact_memory_exec( + &[vec![ + batch_of(&schema, vec![9, 8, 7])?, + batch_of(&schema, vec![6, 5, 4])?, + ]], + Arc::clone(&schema), + )?; + let projection = simple_projection_exec(source, vec![0]); + let ordering = LexOrdering::new(vec![sort_expr("a", &schema).reverse()]).unwrap(); + let sort = sort_exec_with_fetch(ordering, Some(4), projection); + let plan = Arc::new(GlobalLimitExec::new(sort, 1, Some(3))); + + let batches = optimize_and_collect(plan, 4).await?; + let expected = [ + "+---+", "| a |", "+---+", "| 8 |", "| 7 |", "| 6 |", "+---+", + ]; + assert_batches_eq!(expected, &batches); + Ok(()) +} + +#[tokio::test] +async fn test_sort_pushdown_exact_partitioned_fetch_through_projection_returns_top_rows() +-> Result<()> { + let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int64, false)])); + let source = exact_memory_exec( + &[ + vec![batch_of(&schema, vec![9, 7, 5, 3])?], + vec![batch_of(&schema, vec![8, 6, 4, 2])?], + ], + Arc::clone(&schema), + )?; + let projection = simple_projection_exec(source, vec![0]); + let ordering = LexOrdering::new(vec![sort_expr("a", &schema).reverse()]).unwrap(); + let sort = sort_exec_with_fetch_and_preserve_partitioning( + ordering.clone(), + Some(3), + projection, + ); + let plan = sort_preserving_merge_exec_with_fetch(ordering, sort, 3); + + let batches = optimize_and_collect(plan, 3).await?; + let expected = [ + "+---+", "| a |", "+---+", "| 9 |", "| 8 |", "| 7 |", "+---+", + ]; + assert_batches_eq!(expected, &batches); + Ok(()) +} diff --git a/datafusion/core/tests/physical_optimizer/test_utils.rs b/datafusion/core/tests/physical_optimizer/test_utils.rs index 146e4a0d7c54a..441d1b10a5b30 100644 --- a/datafusion/core/tests/physical_optimizer/test_utils.rs +++ b/datafusion/core/tests/physical_optimizer/test_utils.rs @@ -226,8 +226,22 @@ pub fn inexact_memory_exec( partitions: &[Vec], schema: SchemaRef, ) -> Result> { - let source = InexactMemorySource { + let source = PushdownMemorySource { inner: MemorySourceConfig::try_new(partitions, schema, None)?, + exact: false, + }; + Ok(Arc::new(DataSourceExec::new(Arc::new(source)))) +} + +/// A memory scan that answers `Exact` to any sort pushdown. The batches +/// must already be in the order the test requests. +pub fn exact_memory_exec( + partitions: &[Vec], + schema: SchemaRef, +) -> Result> { + let source = PushdownMemorySource { + inner: MemorySourceConfig::try_new(partitions, schema, None)?, + exact: true, }; Ok(Arc::new(DataSourceExec::new(Arc::new(source)))) } @@ -1089,10 +1103,6 @@ impl ExecutionPlan for TestScan { Ok(Arc::new(Statistics::new_unknown(&self.schema))) } - fn supports_limit_pushdown(&self) -> bool { - self.supports_fetch - } - fn with_fetch(&self, fetch: Option) -> Option> { if self.supports_fetch { let mut new_scan = self.clone(); @@ -1128,7 +1138,7 @@ impl ExecutionPlan for TestScan { ); new_scan.plan_properties = Arc::new(PlanProperties::new( eq_properties, - Partitioning::UnknownPartitioning(1), + self.plan_properties.output_partitioning().clone(), EmissionType::Incremental, Boundedness::Bounded, )); @@ -1159,11 +1169,13 @@ pub fn test_scan_with_ordering( } #[derive(Debug, Clone)] -struct InexactMemorySource { +struct PushdownMemorySource { inner: MemorySourceConfig, + /// If true, `try_pushdown_sort` returns `Exact` instead of `Inexact`. + exact: bool, } -impl DataSource for InexactMemorySource { +impl DataSource for PushdownMemorySource { fn apply_expressions( &self, f: &mut dyn FnMut(&Arc) -> Result, @@ -1216,8 +1228,11 @@ impl DataSource for InexactMemorySource { &self, _order: &[PhysicalSortExpr], ) -> Result>> { - Ok(SortOrderPushdownResult::Inexact { - inner: Arc::new(self.clone()), - }) + let inner: Arc = Arc::new(self.clone()); + if self.exact { + Ok(SortOrderPushdownResult::Exact { inner }) + } else { + Ok(SortOrderPushdownResult::Inexact { inner }) + } } } diff --git a/datafusion/physical-optimizer/src/limit_pushdown.rs b/datafusion/physical-optimizer/src/limit_pushdown.rs index 740553280d72c..4b924a3e91874 100644 --- a/datafusion/physical-optimizer/src/limit_pushdown.rs +++ b/datafusion/physical-optimizer/src/limit_pushdown.rs @@ -196,6 +196,15 @@ fn combines_partitions(plan: &Arc) -> bool { input_partitions > plan.output_partitioning().partition_count() } +/// Runs [`LimitPushdown`] on `plan`, for rules that add a limit node to a +/// subtree after `LimitPushdown` has run. +pub(crate) fn push_down_limits( + plan: Arc, + stats_ctx: &StatisticsContext, +) -> Result> { + push_limits(plan, Above::Nothing, stats_ctx) +} + /// Pushes the bounds of all limit nodes in `plan` down as far as they pass, /// and writes each one once, at the first node that can enforce it: /// diff --git a/datafusion/physical-optimizer/src/pushdown_sort.rs b/datafusion/physical-optimizer/src/pushdown_sort.rs index 3f2a4f1921fe9..d1d7e0b1b9c3a 100644 --- a/datafusion/physical-optimizer/src/pushdown_sort.rs +++ b/datafusion/physical-optimizer/src/pushdown_sort.rs @@ -26,7 +26,8 @@ //! //! - **Sort elimination**: when a data source's natural ordering satisfies the //! request, return `Exact` and remove the `SortExec` entirely. Preserves -//! `fetch` (LIMIT) from the eliminated `SortExec` for early termination. +//! `fetch` (LIMIT) from the eliminated `SortExec` for early termination, +//! pushed down as far as [`LimitPushdown`] would push it. //! - **Statistics-based file sorting**: sort files within each partition by //! min/max statistics. When files are non-overlapping but listed in wrong //! order (e.g., alphabetical order ≠ sort key order), this fixes the ordering @@ -40,8 +41,14 @@ //! used (`Inexact`, `SortExec` retained) //! //! Related issue: +//! +//! [`LimitPushdown`]: crate::limit_pushdown::LimitPushdown use crate::PhysicalOptimizerRule; +use crate::limit_pushdown::push_down_limits; +use crate::optimizer::{ + ConfigOnlyContext, PhysicalOptimizerContext, with_statistics_context, +}; use datafusion_common::Result; use datafusion_common::config::ConfigOptions; use datafusion_common::tree_node::{ @@ -52,6 +59,7 @@ use datafusion_physical_plan::buffer::BufferExec; use datafusion_physical_plan::limit::{GlobalLimitExec, LocalLimitExec}; use datafusion_physical_plan::sorts::sort::SortExec; use datafusion_physical_plan::sorts::sort_preserving_merge::SortPreservingMergeExec; +use datafusion_physical_plan::statistics::StatisticsContext; use datafusion_physical_plan::{ExecutionPlan, ExecutionPlanProperties}; use std::sync::Arc; @@ -73,158 +81,174 @@ impl PhysicalOptimizerRule for PushdownSort { plan: Arc, config: &ConfigOptions, ) -> Result> { + self.optimize_with_context(plan, &ConfigOnlyContext::new(config)) + } + + fn optimize_with_context( + &self, + plan: Arc, + context: &dyn PhysicalOptimizerContext, + ) -> Result> { + let config = context.config_options(); // Check if sort pushdown optimization is enabled if !config.optimizer.enable_sort_pushdown { return Ok(plan); } let buffer_capacity = config.execution.sort_pushdown_buffer_capacity; + with_statistics_context(context, |stats_ctx| { + pushdown_sorts(plan, buffer_capacity, stats_ctx) + }) + } - // Use transform_down to find and optimize all SortExec nodes (including nested ones) - // Also handles SPM → SortExec pattern to insert BufferExec when sort is eliminated - plan.transform_down(|plan: Arc| { - // Pattern 1: SPM → SortExec(preserve_partitioning) - // When we eliminate the SortExec, SPM loses its memory buffer and reads - // directly from I/O-bound sources. Insert a BufferExec to compensate. - if let Some(spm) = plan.downcast_ref::() - && let Some(sort_child) = spm.input().downcast_ref::() - && sort_child.preserve_partitioning() - { - let sort_input = Arc::clone(sort_child.input()); - if input_has_fetch(&sort_input)? { - return Ok(Transformed::no(plan)); - } - let required_ordering = sort_child.expr(); - match sort_input.try_pushdown_sort(required_ordering)? { - SortOrderPushdownResult::Exact { inner } => { - // Preserve fetch (LIMIT) from the eliminated SortExec. - // Use LocalLimitExec (not Global) since input is multi-partition. - let inner = if let Some(fetch) = sort_child.fetch() { - inner.with_fetch(Some(fetch)).unwrap_or_else(|| { - Arc::new(LocalLimitExec::new(inner, fetch)) - }) - } else { - inner - }; - // Insert BufferExec to replace SortExec's buffering role. - // SortExec buffered all data in memory; BufferExec provides - // bounded buffering so SPM doesn't stall on I/O. - let buffered: Arc = - Arc::new(BufferExec::new(inner, buffer_capacity)); - let new_spm = - SortPreservingMergeExec::new(spm.expr().clone(), buffered) - .with_fetch(spm.fetch()); - return Ok(Transformed::yes(Arc::new(new_spm))); - } - SortOrderPushdownResult::Inexact { inner } => { - let new_sort = SortExec::new(required_ordering.clone(), inner) - .with_fetch(sort_child.fetch()) - .with_preserve_partitioning(true); - let new_spm = SortPreservingMergeExec::new( - spm.expr().clone(), - Arc::new(new_sort), - ) - .with_fetch(spm.fetch()); - // The replacement already has the required - // `SortPreservingMergeExec` parent. Do not descend - // into its `SortExec` child and treat it as a - // standalone TopK. - return Ok(Transformed::new( - Arc::new(new_spm), - true, - TreeNodeRecursion::Jump, - )); - } - SortOrderPushdownResult::Unsupported => { - return Ok(Transformed::no(plan)); - } - } - } + fn name(&self) -> &str { + "PushdownSort" + } - // Pattern 2: Standalone SortExec (no SPM parent) - let Some(sort_exec) = plan.downcast_ref::() else { - return Ok(Transformed::no(plan)); - }; + fn schema_check(&self) -> bool { + true + } +} - let sort_input = Arc::clone(sort_exec.input()); +fn pushdown_sorts( + plan: Arc, + buffer_capacity: usize, + stats_ctx: &StatisticsContext, +) -> Result> { + // Use transform_down to find and optimize all SortExec nodes (including nested ones) + // Also handles SPM → SortExec pattern to insert BufferExec when sort is eliminated + plan.transform_down(|plan: Arc| { + // Pattern 1: SPM → SortExec(preserve_partitioning) + // When we eliminate the SortExec, SPM loses its memory buffer and reads + // directly from I/O-bound sources. Insert a BufferExec to compensate. + if let Some(spm) = plan.downcast_ref::() + && let Some(sort_child) = spm.input().downcast_ref::() + && sort_child.preserve_partitioning() + { + let sort_input = Arc::clone(sort_child.input()); if input_has_fetch(&sort_input)? { return Ok(Transformed::no(plan)); } - let required_ordering = sort_exec.expr(); - - // Try to push the sort requirement down through the plan tree - // Each node type defines its own pushdown behavior via try_pushdown_sort() + let required_ordering = sort_child.expr(); match sort_input.try_pushdown_sort(required_ordering)? { SortOrderPushdownResult::Exact { inner } => { - // Data source guarantees perfect ordering - remove the Sort operator. - // - // If the SortExec carried a fetch (LIMIT), we must preserve it. - // First try pushing the limit into the source via `with_fetch()`. - // If the source doesn't support `with_fetch`, preserve whether - // the limit applies to each partition or to the entire input. - if let Some(fetch) = sort_exec.fetch() { - let inner = inner.with_fetch(Some(fetch)).unwrap_or_else(|| { - if sort_exec.preserve_partitioning() { - Arc::new(LocalLimitExec::new(inner, fetch)) - } else { - Arc::new(GlobalLimitExec::new(inner, 0, Some(fetch))) - } - }); - Ok(Transformed::yes(inner)) + // Preserve fetch (LIMIT) from the eliminated SortExec. + // Use LocalLimitExec (not Global) since input is multi-partition. + let inner = if let Some(fetch) = sort_child.fetch() { + push_down_limits( + Arc::new(LocalLimitExec::new(inner, fetch)), + stats_ctx, + )? } else { - Ok(Transformed::yes(inner)) - } + inner + }; + // Insert BufferExec to replace SortExec's buffering role. + // SortExec buffered all data in memory; BufferExec provides + // bounded buffering so SPM doesn't stall on I/O. + let buffered: Arc = + Arc::new(BufferExec::new(inner, buffer_capacity)); + let new_spm = + SortPreservingMergeExec::new(spm.expr().clone(), buffered) + .with_fetch(spm.fetch()); + return Ok(Transformed::yes(Arc::new(new_spm))); } SortOrderPushdownResult::Inexact { inner } => { - // Data source is optimized for the ordering but not perfectly sorted - // Keep the Sort operator but use the optimized input - // Benefits: TopK queries can terminate early, better cache locality - // A standalone multi-partition TopK still needs a global - // merge; otherwise a later coalesce can concatenate - // locally sorted partitions. - let preserve_partitioning = sort_exec.preserve_partitioning(); - let needs_global_topk = - preserve_partitioning && sort_exec.fetch().is_some(); - let input_partitions = inner.output_partitioning().partition_count(); - let new_sort: Arc = Arc::new( - SortExec::new(required_ordering.clone(), inner) - .with_fetch(sort_exec.fetch()) - .with_preserve_partitioning(preserve_partitioning), - ); - if needs_global_topk && input_partitions > 1 { - let new_spm = SortPreservingMergeExec::new( - required_ordering.clone(), - new_sort, - ) - .with_fetch(sort_exec.fetch()); - // Do not descend into the newly inserted - // `SortExec`, or this standalone branch will wrap it - // in another `SortPreservingMergeExec`. - Ok(Transformed::new( - Arc::new(new_spm), - true, - TreeNodeRecursion::Jump, - )) - } else { - Ok(Transformed::yes(new_sort)) - } + let new_sort = SortExec::new(required_ordering.clone(), inner) + .with_fetch(sort_child.fetch()) + .with_preserve_partitioning(true); + let new_spm = SortPreservingMergeExec::new( + spm.expr().clone(), + Arc::new(new_sort), + ) + .with_fetch(spm.fetch()); + // The replacement already has the required + // `SortPreservingMergeExec` parent. Do not descend + // into its `SortExec` child and treat it as a + // standalone TopK. + return Ok(Transformed::new( + Arc::new(new_spm), + true, + TreeNodeRecursion::Jump, + )); } SortOrderPushdownResult::Unsupported => { - // Cannot optimize for this ordering - no change - Ok(Transformed::no(plan)) + return Ok(Transformed::no(plan)); } } - }) - .data() - } + } - fn name(&self) -> &str { - "PushdownSort" - } + // Pattern 2: Standalone SortExec (no SPM parent) + let Some(sort_exec) = plan.downcast_ref::() else { + return Ok(Transformed::no(plan)); + }; - fn schema_check(&self) -> bool { - true - } + let sort_input = Arc::clone(sort_exec.input()); + if input_has_fetch(&sort_input)? { + return Ok(Transformed::no(plan)); + } + let required_ordering = sort_exec.expr(); + + // Try to push the sort requirement down through the plan tree + // Each node type defines its own pushdown behavior via try_pushdown_sort() + match sort_input.try_pushdown_sort(required_ordering)? { + SortOrderPushdownResult::Exact { inner } => { + // Data source guarantees perfect ordering - remove the Sort operator. + // + // If the SortExec carried a fetch (LIMIT), we must preserve it. + // Keep whether the limit applies to each partition or to the + // entire input, then push it down as far as it goes, e.g. + // through a projection into the source. + if let Some(fetch) = sort_exec.fetch() { + let limit: Arc = + if sort_exec.preserve_partitioning() { + Arc::new(LocalLimitExec::new(inner, fetch)) + } else { + Arc::new(GlobalLimitExec::new(inner, 0, Some(fetch))) + }; + Ok(Transformed::yes(push_down_limits(limit, stats_ctx)?)) + } else { + Ok(Transformed::yes(inner)) + } + } + SortOrderPushdownResult::Inexact { inner } => { + // Data source is optimized for the ordering but not perfectly sorted + // Keep the Sort operator but use the optimized input + // Benefits: TopK queries can terminate early, better cache locality + // A standalone multi-partition TopK still needs a global + // merge; otherwise a later coalesce can concatenate + // locally sorted partitions. + let preserve_partitioning = sort_exec.preserve_partitioning(); + let needs_global_topk = + preserve_partitioning && sort_exec.fetch().is_some(); + let input_partitions = inner.output_partitioning().partition_count(); + let new_sort: Arc = Arc::new( + SortExec::new(required_ordering.clone(), inner) + .with_fetch(sort_exec.fetch()) + .with_preserve_partitioning(preserve_partitioning), + ); + if needs_global_topk && input_partitions > 1 { + let new_spm = + SortPreservingMergeExec::new(required_ordering.clone(), new_sort) + .with_fetch(sort_exec.fetch()); + // Do not descend into the newly inserted + // `SortExec`, or this standalone branch will wrap it + // in another `SortPreservingMergeExec`. + Ok(Transformed::new( + Arc::new(new_spm), + true, + TreeNodeRecursion::Jump, + )) + } else { + Ok(Transformed::yes(new_sort)) + } + } + SortOrderPushdownResult::Unsupported => { + // Cannot optimize for this ordering - no change + Ok(Transformed::no(plan)) + } + } + }) + .data() } /// Whether a node below this sort has a fetch. A fetch keeps the first rows in the diff --git a/datafusion/sqllogictest/src/test_context/exact_sort_pushdown.rs b/datafusion/sqllogictest/src/test_context/exact_sort_pushdown.rs index 85a1639ba5e02..a68ad99c7a9d1 100644 --- a/datafusion/sqllogictest/src/test_context/exact_sort_pushdown.rs +++ b/datafusion/sqllogictest/src/test_context/exact_sort_pushdown.rs @@ -23,6 +23,10 @@ use datafusion::prelude::SessionContext; pub(super) fn register_exact_sort_source(ctx: &SessionContext) -> Result<()> { ctx.register_table("exact_sort_source", Arc::new(exact_sort_source(4)?))?; + ctx.register_table( + "exact_sort_fetch_source", + Arc::new(exact_sort_source(4)?.with_fetch_support()), + )?; Ok(()) } @@ -36,7 +40,10 @@ fn exact_sort_source(partition_count: i32) -> Result { }) .collect::>>()?; let input = TestMemoryExec::try_new(&partitions, partitions[0][0].schema(), None)?; - Ok(ExactSortSource(input)) + Ok(ExactSortSource { + input, + supports_fetch: false, + }) } fn ordering() -> LexOrdering { @@ -47,15 +54,28 @@ fn ordering() -> LexOrdering { .into() } -/// Accepts exact sort pushdown without supporting fetch pushdown. Its rows are -/// already sorted within each partition; the hook makes that ordering explicit. +/// Accepts exact sort pushdown, and a fetch only when `supports_fetch` is set. +/// Its rows are already sorted within each partition; the hook makes that +/// ordering explicit. #[derive(Debug, Clone)] -struct ExactSortSource(TestMemoryExec); +struct ExactSortSource { + input: TestMemoryExec, + supports_fetch: bool, +} + +impl ExactSortSource { + fn with_fetch_support(self) -> Self { + Self { + supports_fetch: true, + ..self + } + } +} #[async_trait] impl TableProvider for ExactSortSource { fn schema(&self) -> SchemaRef { - self.0.schema() + self.input.schema() } fn table_type(&self) -> TableType { @@ -76,7 +96,11 @@ impl TableProvider for ExactSortSource { impl DisplayAs for ExactSortSource { fn fmt_as(&self, _: DisplayFormatType, f: &mut Formatter) -> fmt::Result { - write!(f, "ExactSortSource") + write!(f, "ExactSortSource")?; + if let Some(fetch) = self.fetch() { + write!(f, ": fetch={fetch}")?; + } + Ok(()) } } @@ -86,7 +110,7 @@ impl ExecutionPlan for ExactSortSource { } fn properties(&self) -> &Arc { - self.0.properties() + self.input.properties() } fn children(&self) -> Vec<&Arc> { @@ -113,7 +137,20 @@ impl ExecutionPlan for ExactSortSource { partition: usize, context: Arc, ) -> Result { - self.0.execute(partition, context) + self.input.execute(partition, context) + } + + fn with_fetch(&self, fetch: Option) -> Option> { + self.supports_fetch.then(|| { + Arc::new(Self { + input: self.input.clone().with_limit(fetch), + supports_fetch: true, + }) as _ + }) + } + + fn fetch(&self) -> Option { + self.input.fetch() } fn try_pushdown_sort( @@ -124,9 +161,13 @@ impl ExecutionPlan for ExactSortSource { return Ok(SortOrderPushdownResult::Unsupported); } Ok(SortOrderPushdownResult::Exact { - inner: Arc::new(Self( - self.0.clone().try_with_sort_information(vec![ordering()])?, - )), + inner: Arc::new(Self { + input: self + .input + .clone() + .try_with_sort_information(vec![ordering()])?, + supports_fetch: self.supports_fetch, + }), }) } } diff --git a/datafusion/sqllogictest/test_files/sort_pushdown.slt b/datafusion/sqllogictest/test_files/sort_pushdown.slt index 25e932c2d35b9..526caaabd4d35 100644 --- a/datafusion/sqllogictest/test_files/sort_pushdown.slt +++ b/datafusion/sqllogictest/test_files/sort_pushdown.slt @@ -198,9 +198,108 @@ physical_plan 06)----------LocalLimitExec: fetch=3 07)------------ExactSortSource +# The custom source keeps a ProjectionExec above it. After the sort is removed, +# its limit must pass the projection: into the source as a fetch when the +# source takes one, or as a LocalLimitExec right above it otherwise. +query TT +EXPLAIN SELECT group_id, value + 1 AS v +FROM exact_sort_fetch_source +ORDER BY group_id, value +LIMIT 3; +---- +physical_plan +01)ProjectionExec: expr=[group_id@0 as group_id, v@1 as v] +02)--SortPreservingMergeExec: [group_id@0 ASC NULLS LAST, value@2 ASC NULLS LAST], fetch=3 +03)----BufferExec: capacity=1073741824 +04)------ProjectionExec: expr=[group_id@0 as group_id, CAST(value@1 AS Int64) + 1 as v, value@1 as value] +05)--------ExactSortSource: fetch=3 + +query TT +EXPLAIN SELECT group_id, value + 1 AS v +FROM exact_sort_source +ORDER BY group_id, value +LIMIT 3; +---- +physical_plan +01)ProjectionExec: expr=[group_id@0 as group_id, v@1 as v] +02)--SortPreservingMergeExec: [group_id@0 ASC NULLS LAST, value@2 ASC NULLS LAST], fetch=3 +03)----BufferExec: capacity=1073741824 +04)------ProjectionExec: expr=[group_id@0 as group_id, CAST(value@1 AS Int64) + 1 as v, value@1 as value] +05)--------LocalLimitExec: fetch=3 +06)----------ExactSortSource + +query TT +EXPLAIN SELECT group_id, value + 1 AS v +FROM exact_sort_fetch_source +ORDER BY group_id, value +LIMIT 3 OFFSET 2; +---- +physical_plan +01)ProjectionExec: expr=[group_id@0 as group_id, v@1 as v] +02)--GlobalLimitExec: skip=2, fetch=3 +03)----SortPreservingMergeExec: [group_id@0 ASC NULLS LAST, value@2 ASC NULLS LAST], fetch=5 +04)------BufferExec: capacity=1073741824 +05)--------ProjectionExec: expr=[group_id@0 as group_id, CAST(value@1 AS Int64) + 1 as v, value@1 as value] +06)----------ExactSortSource: fetch=5 + +query TT +EXPLAIN SELECT group_id, value + 1 AS v +FROM exact_sort_source +ORDER BY group_id, value +LIMIT 3 OFFSET 2; +---- +physical_plan +01)ProjectionExec: expr=[group_id@0 as group_id, v@1 as v] +02)--GlobalLimitExec: skip=2, fetch=3 +03)----SortPreservingMergeExec: [group_id@0 ASC NULLS LAST, value@2 ASC NULLS LAST], fetch=5 +04)------BufferExec: capacity=1073741824 +05)--------ProjectionExec: expr=[group_id@0 as group_id, CAST(value@1 AS Int64) + 1 as v, value@1 as value] +06)----------LocalLimitExec: fetch=5 +07)------------ExactSortSource + statement ok RESET datafusion.explain.physical_plan_only; +query II +SELECT group_id, value + 1 AS v +FROM exact_sort_fetch_source +ORDER BY group_id, value +LIMIT 3; +---- +0 1 +0 2 +0 3 + +query II +SELECT group_id, value + 1 AS v +FROM exact_sort_fetch_source +ORDER BY group_id, value +LIMIT 3 OFFSET 2; +---- +0 3 +0 4 +0 5 + +query II +SELECT group_id, value + 1 AS v +FROM exact_sort_source +ORDER BY group_id, value +LIMIT 3; +---- +0 1 +0 2 +0 3 + +query II +SELECT group_id, value + 1 AS v +FROM exact_sort_source +ORDER BY group_id, value +LIMIT 3 OFFSET 2; +---- +0 3 +0 4 +0 5 + # Test 1: Sort Pushdown for ordered Parquet files # Create a sorted dataset statement ok @@ -1322,6 +1421,47 @@ SELECT * FROM reversed_parquet ORDER BY id ASC; 8 800 9 900 +# Test 4.3: A repeated expression leaves a ProjectionExec above the scan. The +# scan absorbs the common subexpression, but not the projection that uses it +# twice, since that would compute it twice. After the sort is removed, its +# limit must pass the projection and reach the scan. +statement ok +SET datafusion.explain.physical_plan_only = true; + +query TT +EXPLAIN SELECT id, (value + 1) * 2 AS a, (value + 1) * 3 AS b +FROM reversed_parquet ORDER BY id ASC LIMIT 2; +---- +physical_plan +01)ProjectionExec: expr=[id@1 as id, __common_expr_1@0 * 2 as a, __common_expr_1@0 * 3 as b] +02)--DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/sort_pushdown/reversed/c_low.parquet, WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/sort_pushdown/reversed/b_mid.parquet, WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/sort_pushdown/reversed/a_high.parquet]]}, projection=[CAST(value@1 AS Int64) + 1 as __common_expr_1, id], limit=2, file_type=parquet + +query TT +EXPLAIN SELECT id, (value + 1) * 2 AS a, (value + 1) * 3 AS b +FROM reversed_parquet ORDER BY id ASC LIMIT 2 OFFSET 3; +---- +physical_plan +01)GlobalLimitExec: skip=3, fetch=2 +02)--ProjectionExec: expr=[id@1 as id, __common_expr_1@0 * 2 as a, __common_expr_1@0 * 3 as b] +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/sort_pushdown/reversed/c_low.parquet, WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/sort_pushdown/reversed/b_mid.parquet, WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/sort_pushdown/reversed/a_high.parquet]]}, projection=[CAST(value@1 AS Int64) + 1 as __common_expr_1, id], limit=5, file_type=parquet + +statement ok +RESET datafusion.explain.physical_plan_only; + +query III +SELECT id, (value + 1) * 2 AS a, (value + 1) * 3 AS b +FROM reversed_parquet ORDER BY id ASC LIMIT 2; +---- +1 202 303 +2 402 603 + +query III +SELECT id, (value + 1) * 2 AS a, (value + 1) * 3 AS b +FROM reversed_parquet ORDER BY id ASC LIMIT 2 OFFSET 3; +---- +4 802 1203 +5 1002 1503 + # Test 5: Overlapping files with inferred ordering # Create files with overlapping id ranges