From b4a57cd0c8ba3625d03781567cc90d2048b6e10b Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Tue, 1 Dec 2026 12:15:14 -0800 Subject: [PATCH 1/7] refactor: extract the two halves of a leaf split A check of the split needs to build one before the lower half moves down. No behavior change. Co-Authored-By: Claude Opus 5.5 --- .../src/projection_pushdown.rs | 55 +++++++++++++------ 1 file changed, 38 insertions(+), 17 deletions(-) diff --git a/datafusion/physical-optimizer/src/projection_pushdown.rs b/datafusion/physical-optimizer/src/projection_pushdown.rs index a792b4131d43e..c421dea4b0e19 100644 --- a/datafusion/physical-optimizer/src/projection_pushdown.rs +++ b/datafusion/physical-optimizer/src/projection_pushdown.rs @@ -541,8 +541,26 @@ fn try_split_leaf_projection( // source keeps reading it: for `s['a'] + 1` that would read the whole struct // alongside the extracted field, which is worse than not splitting at all. let child = repartition.input(); - let child_schema = child.schema(); let passthrough_indices = collect_outer_columns(projection.expr(), &leaves)?; + let lower_projection = lower_projection(child, &leaves, &passthrough_indices)?; + + // Only commit the split if the child really absorbs the leaf projection. + // Otherwise this would just add a projection that helps nobody. + let Some(new_child) = child.try_swapping_with_projection(&lower_projection)? else { + return Ok(None); + }; + + rebuild_split(projection, &leaves, &passthrough_indices, child, new_child).map(Some) +} + +/// Returns the lower part of a split, which outputs the `child` columns at +/// `passthrough_indices` and then `leaves`. +fn lower_projection( + child: &Arc, + leaves: &[Arc], + passthrough_indices: &[usize], +) -> Result { + let child_schema = child.schema(); let mut lower_exprs = passthrough_indices .iter() .map(|&idx| { @@ -559,14 +577,19 @@ fn try_split_leaf_projection( alias: leaf_column_name(index), }); } - let lower_projection = ProjectionExec::try_new(lower_exprs, Arc::clone(child))?; - - // Only commit the split if the child really absorbs the leaf projection. - // Otherwise this would just add a projection that helps nobody. - let Some(new_child) = child.try_swapping_with_projection(&lower_projection)? else { - return Ok(None); - }; + ProjectionExec::try_new(lower_exprs, Arc::clone(child)) +} +/// Returns `projection` over its repartition of `new_child`, which outputs what +/// [`lower_projection`] of `child` does. +fn rebuild_split( + projection: &ProjectionExec, + leaves: &[Arc], + passthrough_indices: &[usize], + child: &Arc, + new_child: Arc, +) -> Result> { + let child_schema = child.schema(); let new_exprs = projection .expr() .iter() @@ -574,8 +597,8 @@ fn try_split_leaf_projection( Ok(ProjectionExpr { expr: rewrite_outer_expr( Arc::clone(&proj_expr.expr), - &leaves, - &passthrough_indices, + leaves, + passthrough_indices, child_schema.fields().len(), )?, alias: proj_expr.alias.clone(), @@ -591,13 +614,11 @@ fn try_split_leaf_projection( )?; // `try_new` would derive the output schema from the expressions alone and // drop the metadata the planner set, which `schema_check` then rejects. - Ok(Some(Arc::new( - ProjectionExec::try_new_with_schema_metadata( - new_exprs, - new_repartition, - projection.schema().as_ref(), - )?, - ))) + Ok(Arc::new(ProjectionExec::try_new_with_schema_metadata( + new_exprs, + new_repartition, + projection.schema().as_ref(), + )?)) } /// Collects the distinct outermost [`ExpressionPlacement::MoveTowardsLeafNodes`] From 2cb20108b92783b20a07d4128876825c7b539353 Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Tue, 1 Dec 2026 12:15:17 -0800 Subject: [PATCH 2/7] test: cover the properties that a leaf split loses Three of these queries fail to plan. The split drops a column that gives the output its order, or makes it constant, and an ancestor relies on that. Co-Authored-By: Claude Opus 5.5 --- .../test_files/projection_pushdown.slt | 98 +++++++++++++++++++ 1 file changed, 98 insertions(+) diff --git a/datafusion/sqllogictest/test_files/projection_pushdown.slt b/datafusion/sqllogictest/test_files/projection_pushdown.slt index 2d5a554430b94..ca5b66e1368fe 100644 --- a/datafusion/sqllogictest/test_files/projection_pushdown.slt +++ b/datafusion/sqllogictest/test_files/projection_pushdown.slt @@ -2864,6 +2864,104 @@ physical_plan statement ok DROP TABLE leaf_split_mem; +# A split that extracts a leaf must keep the orderings, constants and equalities +# that an ancestor relies on. The logical rewrite would extract the leaf earlier, +# so these queries disable it. +statement ok +SET datafusion.optimizer.enable_leaf_expression_pushdown = false; + +query I +COPY (SELECT value * 2 AS c, value AS a, value AS b, named_struct('v', value) AS s + FROM range(0, 6) ORDER BY c) +TO 'test_files/scratch/projection_pushdown/leaf_ordered.parquet' STORED AS PARQUET; +---- +6 + +statement ok +CREATE EXTERNAL TABLE leaf_ordered (c BIGINT, a BIGINT, b BIGINT, s STRUCT) +STORED AS PARQUET LOCATION 'test_files/scratch/projection_pushdown/leaf_ordered.parquet' +WITH ORDER (c ASC); + +# `c = a + b` makes the order of `c` the order of `k`, which the merge needs. +query TT +EXPLAIN SELECT s['v'] + 1 AS l, a + b AS k FROM leaf_ordered WHERE c = a + b ORDER BY k LIMIT 2; +---- +logical_plan +01)Sort: k ASC NULLS LAST, fetch=2 +02)--Projection: get_field(leaf_ordered.s, Utf8("v")) + Int64(1) AS l, leaf_ordered.a + leaf_ordered.b AS k +03)----Filter: leaf_ordered.c = leaf_ordered.a + leaf_ordered.b +04)------TableScan: leaf_ordered projection=[c, a, b, s], partial_filters=[leaf_ordered.c = leaf_ordered.a + leaf_ordered.b] + +query error SanityCheckPlan: order and distribution requirements stopped holding after physical optimizer rule 'ProjectionPushdown' +SELECT s['v'] + 1 AS l, a + b AS k FROM leaf_ordered WHERE c = a + b ORDER BY k LIMIT 2; + +# The same for an aggregate that the order reaches through. +query error SanityCheckPlan: order and distribution requirements stopped holding after physical optimizer rule 'ProjectionPushdown' +SELECT k, sum(l) FROM (SELECT s['v'] + 1 AS l, a + b AS k FROM leaf_ordered WHERE c = a + b) +GROUP BY k ORDER BY k; + +# Nothing needs the order of `k`, so the scan does not read `c`. +query TT +EXPLAIN SELECT s['v'] + 1 AS l, a + b AS k FROM leaf_ordered WHERE c = a + b; +---- +logical_plan +01)Projection: get_field(leaf_ordered.s, Utf8("v")) + Int64(1) AS l, leaf_ordered.a + leaf_ordered.b AS k +02)--Filter: leaf_ordered.c = leaf_ordered.a + leaf_ordered.b +03)----TableScan: leaf_ordered projection=[c, a, b, s], partial_filters=[leaf_ordered.c = leaf_ordered.a + leaf_ordered.b] +physical_plan +01)ProjectionExec: expr=[__datafusion_leaf_0@2 + 1 as l, a@0 + b@1 as k] +02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1 +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/leaf_ordered.parquet]]}, projection=[a, b, get_field(s@3, v) as __datafusion_leaf_0], file_type=parquet, predicate=c@0 = a@1 + b@2 + +# The same for a sort by another key, which does not need the order of its input. +query TT +EXPLAIN SELECT s['v'] + 1 AS l, a + b AS k FROM leaf_ordered WHERE c = a + b ORDER BY l; +---- +logical_plan +01)Sort: l ASC NULLS LAST +02)--Projection: get_field(leaf_ordered.s, Utf8("v")) + Int64(1) AS l, leaf_ordered.a + leaf_ordered.b AS k +03)----Filter: leaf_ordered.c = leaf_ordered.a + leaf_ordered.b +04)------TableScan: leaf_ordered projection=[c, a, b, s], partial_filters=[leaf_ordered.c = leaf_ordered.a + leaf_ordered.b] +physical_plan +01)SortPreservingMergeExec: [l@0 ASC NULLS LAST] +02)--SortExec: expr=[l@0 ASC NULLS LAST], preserve_partitioning=[true] +03)----ProjectionExec: expr=[__datafusion_leaf_0@2 + 1 as l, a@0 + b@1 as k] +04)------RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1 +05)--------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/leaf_ordered.parquet]]}, projection=[a, b, get_field(s@3, v) as __datafusion_leaf_0], file_type=parquet, predicate=c@0 = a@1 + b@2 + +# `c` makes `k` constant, so the plan sorts by `a` alone. +query I +COPY (SELECT column1 AS c, column2 AS a, column3 AS b, named_struct('v', column2) AS s + FROM VALUES (6, 5, 1), (6, 4, 2), (6, -1, 7), (6, 9, -3)) +TO 'test_files/scratch/projection_pushdown/leaf_constant.parquet' STORED AS PARQUET; +---- +4 + +statement ok +CREATE EXTERNAL TABLE leaf_constant STORED AS PARQUET +LOCATION 'test_files/scratch/projection_pushdown/leaf_constant.parquet'; + +query TT +EXPLAIN SELECT s['v'] + 1 AS l, a + b + 1 AS k, a FROM leaf_constant WHERE c = a + b AND c + 1 = 7 ORDER BY k, a; +---- +logical_plan +01)Sort: k ASC NULLS LAST, leaf_constant.a ASC NULLS LAST +02)--Projection: get_field(leaf_constant.s, Utf8("v")) + Int64(1) AS l, leaf_constant.a + leaf_constant.b + Int64(1) AS k, leaf_constant.a +03)----Filter: leaf_constant.c = leaf_constant.a + leaf_constant.b AND leaf_constant.c + Int64(1) = Int64(7) +04)------TableScan: leaf_constant projection=[c, a, b, s], partial_filters=[leaf_constant.c = leaf_constant.a + leaf_constant.b, leaf_constant.c + Int64(1) = Int64(7)] + +query error SanityCheckPlan: order and distribution requirements stopped holding after physical optimizer rule 'ProjectionPushdown' +SELECT s['v'] + 1 AS l, a + b + 1 AS k, a FROM leaf_constant WHERE c = a + b AND c + 1 = 7 ORDER BY k, a; + +statement ok +DROP TABLE leaf_constant; + +statement ok +DROP TABLE leaf_ordered; + +statement ok +RESET datafusion.optimizer.enable_leaf_expression_pushdown; + statement ok SET datafusion.execution.batch_size = 8192; From 61a0666b4848ecdab0c2a478b1069b1decf9a611 Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Tue, 1 Dec 2026 12:18:50 -0800 Subject: [PATCH 3/7] fix: keep the output properties of a leaf split The split compares the output with that of a trial split. If the trial loses a constant, an equality or an ordering, the lower half also passes through the columns that it came from. It checks again after the lower half has moved. Co-Authored-By: Claude Opus 5.5 --- .../src/projection_pushdown.rs | 114 ++++++++++++++++-- .../test_files/projection_pushdown.slt | 44 +++++-- 2 files changed, 142 insertions(+), 16 deletions(-) diff --git a/datafusion/physical-optimizer/src/projection_pushdown.rs b/datafusion/physical-optimizer/src/projection_pushdown.rs index c421dea4b0e19..7cc7c79be6596 100644 --- a/datafusion/physical-optimizer/src/projection_pushdown.rs +++ b/datafusion/physical-optimizer/src/projection_pushdown.rs @@ -21,6 +21,7 @@ use datafusion_common::{JoinSide, JoinType, Result, internal_datafusion_err}; use datafusion_expr::ExpressionPlacement; use datafusion_physical_expr::expressions::{Column, LambdaExpr, LambdaVariable}; use datafusion_physical_expr::projection::ProjectionExpr; +use datafusion_physical_expr::utils::collect_columns; use datafusion_physical_expr::{conjunction, split_conjunction}; use datafusion_physical_expr_common::physical_expr::{PhysicalExpr, is_volatile}; use datafusion_physical_plan::joins::NestedLoopJoinExec; @@ -30,7 +31,8 @@ use datafusion_physical_plan::projection::{ }; use datafusion_physical_plan::repartition::RepartitionExec; use datafusion_physical_plan::{ - ChildrenPropertiesMode, ExecutionPlan, Partitioning, ReplaceChildrenOptions, + ChildrenPropertiesMode, ExecutionPlan, ExecutionPlanProperties, Partitioning, + ReplaceChildrenOptions, }; /// This rule inspects `ProjectionExec`'s in the given physical plan and tries to @@ -536,12 +538,8 @@ fn try_split_leaf_projection( return Ok(None); } - // Pass through only the child columns the outer expressions still need. A - // column used *only* inside an extracted leaf must be dropped, otherwise the - // source keeps reading it: for `s['a'] + 1` that would read the whole struct - // alongside the extracted field, which is worse than not splitting at all. let child = repartition.input(); - let passthrough_indices = collect_outer_columns(projection.expr(), &leaves)?; + let passthrough_indices = choose_passthrough(plan, projection, child, &leaves)?; let lower_projection = lower_projection(child, &leaves, &passthrough_indices)?; // Only commit the split if the child really absorbs the leaf projection. @@ -550,7 +548,58 @@ fn try_split_leaf_projection( return Ok(None); }; - rebuild_split(projection, &leaves, &passthrough_indices, child, new_child).map(Some) + let split = + rebuild_split(projection, &leaves, &passthrough_indices, child, new_child)?; + // The columns were chosen before the lower projection moved, and the operator + // that absorbs it recomputes its own properties. + Ok( + (keeps_equivalences(plan, &split)? && keeps_orderings(plan, &split)?) + .then_some(split), + ) +} + +/// Returns the sorted indices of the `child` columns that a split passes through. +fn choose_passthrough( + plan: &Arc, + projection: &ProjectionExec, + child: &Arc, + leaves: &[Arc], +) -> Result> { + // Pass through only the child columns the outer expressions still need. A + // column used *only* inside an extracted leaf must be dropped, otherwise the + // source keeps reading it: for `s['a'] + 1` that would read the whole struct + // alongside the extracted field, which is worse than not splitting at all. + let mut indices = collect_outer_columns(projection.expr(), leaves)?; + let properties = plan.equivalence_properties(); + if properties.oeq_class().is_empty() && properties.eq_group().is_empty() { + return Ok(indices); + } + let lower_projection = Arc::new(lower_projection(child, leaves, &indices)?); + let split = rebuild_split(projection, leaves, &indices, child, lower_projection)?; + + // A property of the output can depend on a column that no expression reads. + // With `c = a + b`, input sorted by `c` sorts `a + b`, and a constant `c` makes + // `a + b` constant. An ancestor may rely on either, so also pass through the + // columns that the lost property can come from. + let child_properties = child.equivalence_properties(); + let mut add_columns = |expr: &Arc| { + indices.extend(collect_columns(expr).iter().map(|column| column.index())); + }; + if !keeps_equivalences(plan, &split)? { + for class in child_properties.eq_group().iter() { + class.iter().for_each(&mut add_columns); + } + } + if !keeps_orderings(plan, &split)? { + for ordering in child_properties.oeq_class().iter() { + for sort_expr in ordering.iter() { + add_columns(&sort_expr.expr); + } + } + } + indices.sort_unstable(); + indices.dedup(); + Ok(indices) } /// Returns the lower part of a split, which outputs the `child` columns at @@ -621,6 +670,57 @@ fn rebuild_split( )?)) } +/// Returns true if every constant and every equality that `old_plan` knows about +/// its output also holds for `new_plan`. +/// +/// Sorts and repartitions keep both, so an ancestor can rely on them even across +/// an operator that destroys the ordering. Expressions that hold a leaf are not +/// compared: `s['v'] + 1 AS v, s` equates `v` with `s['v'] + 1`, and no split that +/// extracts `s['v']` can keep that. +fn keeps_equivalences( + old_plan: &Arc, + new_plan: &Arc, +) -> Result { + let old_group = old_plan.equivalence_properties().eq_group(); + let new_group = new_plan.equivalence_properties().eq_group(); + for class in old_group.iter() { + let mut first = None; + for expr in class.iter() { + let holds_leaf = expr.exists(|node| { + Ok(node.placement() == ExpressionPlacement::MoveTowardsLeafNodes) + })?; + if holds_leaf { + continue; + } + let first = first.get_or_insert(expr); + let constant = old_group.is_expr_constant(expr); + if !new_group.exprs_equal(first, expr) + || (constant.is_some() && new_group.is_expr_constant(expr) != constant) + { + return Ok(false); + } + } + } + Ok(true) +} + +/// Returns true if `new_plan` satisfies every output ordering of `old_plan`. +/// +/// `RepartitionExec::preserve_order` is not enough to decide this, because a +/// repartition of a single input partition keeps the order without it. +fn keeps_orderings( + old_plan: &Arc, + new_plan: &Arc, +) -> Result { + let new_properties = new_plan.equivalence_properties(); + for ordering in old_plan.equivalence_properties().oeq_class().iter() { + if !new_properties.ordering_satisfy(ordering.iter().cloned())? { + return Ok(false); + } + } + Ok(true) +} + /// Collects the distinct outermost [`ExpressionPlacement::MoveTowardsLeafNodes`] /// sub-expressions of `exprs`. /// diff --git a/datafusion/sqllogictest/test_files/projection_pushdown.slt b/datafusion/sqllogictest/test_files/projection_pushdown.slt index ca5b66e1368fe..8f4d9f88921ad 100644 --- a/datafusion/sqllogictest/test_files/projection_pushdown.slt +++ b/datafusion/sqllogictest/test_files/projection_pushdown.slt @@ -2891,14 +2891,29 @@ logical_plan 02)--Projection: get_field(leaf_ordered.s, Utf8("v")) + Int64(1) AS l, leaf_ordered.a + leaf_ordered.b AS k 03)----Filter: leaf_ordered.c = leaf_ordered.a + leaf_ordered.b 04)------TableScan: leaf_ordered projection=[c, a, b, s], partial_filters=[leaf_ordered.c = leaf_ordered.a + leaf_ordered.b] +physical_plan +01)SortPreservingMergeExec: [k@1 ASC NULLS LAST], fetch=2 +02)--ProjectionExec: expr=[__datafusion_leaf_0@3 + 1 as l, a@1 + b@2 as k] +03)----RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, maintains_sort_order=true +04)------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/leaf_ordered.parquet]]}, projection=[c, a, b, get_field(s@3, v) as __datafusion_leaf_0], output_ordering=[c@0 ASC NULLS LAST], file_type=parquet, predicate=c@0 = a@1 + b@2 -query error SanityCheckPlan: order and distribution requirements stopped holding after physical optimizer rule 'ProjectionPushdown' +query II SELECT s['v'] + 1 AS l, a + b AS k FROM leaf_ordered WHERE c = a + b ORDER BY k LIMIT 2; +---- +1 0 +2 2 # The same for an aggregate that the order reaches through. -query error SanityCheckPlan: order and distribution requirements stopped holding after physical optimizer rule 'ProjectionPushdown' +query II SELECT k, sum(l) FROM (SELECT s['v'] + 1 AS l, a + b AS k FROM leaf_ordered WHERE c = a + b) GROUP BY k ORDER BY k; +---- +0 1 +2 2 +4 3 +6 4 +8 5 +10 6 # Nothing needs the order of `k`, so the scan does not read `c`. query TT @@ -2909,9 +2924,9 @@ logical_plan 02)--Filter: leaf_ordered.c = leaf_ordered.a + leaf_ordered.b 03)----TableScan: leaf_ordered projection=[c, a, b, s], partial_filters=[leaf_ordered.c = leaf_ordered.a + leaf_ordered.b] physical_plan -01)ProjectionExec: expr=[__datafusion_leaf_0@2 + 1 as l, a@0 + b@1 as k] -02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1 -03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/leaf_ordered.parquet]]}, projection=[a, b, get_field(s@3, v) as __datafusion_leaf_0], file_type=parquet, predicate=c@0 = a@1 + b@2 +01)ProjectionExec: expr=[__datafusion_leaf_0@3 + 1 as l, a@1 + b@2 as k] +02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, maintains_sort_order=true +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/leaf_ordered.parquet]]}, projection=[c, a, b, get_field(s@3, v) as __datafusion_leaf_0], output_ordering=[c@0 ASC NULLS LAST], file_type=parquet, predicate=c@0 = a@1 + b@2 # The same for a sort by another key, which does not need the order of its input. query TT @@ -2925,9 +2940,9 @@ logical_plan physical_plan 01)SortPreservingMergeExec: [l@0 ASC NULLS LAST] 02)--SortExec: expr=[l@0 ASC NULLS LAST], preserve_partitioning=[true] -03)----ProjectionExec: expr=[__datafusion_leaf_0@2 + 1 as l, a@0 + b@1 as k] -04)------RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1 -05)--------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/leaf_ordered.parquet]]}, projection=[a, b, get_field(s@3, v) as __datafusion_leaf_0], file_type=parquet, predicate=c@0 = a@1 + b@2 +03)----ProjectionExec: expr=[__datafusion_leaf_0@3 + 1 as l, a@1 + b@2 as k] +04)------RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, maintains_sort_order=true +05)--------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/leaf_ordered.parquet]]}, projection=[c, a, b, get_field(s@3, v) as __datafusion_leaf_0], output_ordering=[c@0 ASC NULLS LAST], file_type=parquet, predicate=c@0 = a@1 + b@2 # `c` makes `k` constant, so the plan sorts by `a` alone. query I @@ -2949,9 +2964,20 @@ logical_plan 02)--Projection: get_field(leaf_constant.s, Utf8("v")) + Int64(1) AS l, leaf_constant.a + leaf_constant.b + Int64(1) AS k, leaf_constant.a 03)----Filter: leaf_constant.c = leaf_constant.a + leaf_constant.b AND leaf_constant.c + Int64(1) = Int64(7) 04)------TableScan: leaf_constant projection=[c, a, b, s], partial_filters=[leaf_constant.c = leaf_constant.a + leaf_constant.b, leaf_constant.c + Int64(1) = Int64(7)] +physical_plan +01)SortPreservingMergeExec: [k@1 ASC NULLS LAST, a@2 ASC NULLS LAST] +02)--SortExec: expr=[a@2 ASC NULLS LAST], preserve_partitioning=[true] +03)----ProjectionExec: expr=[__datafusion_leaf_0@3 + 1 as l, a@1 + b@2 + 1 as k, a@1 as a] +04)------RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1 +05)--------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/leaf_constant.parquet]]}, projection=[c, a, b, get_field(s@3, v) as __datafusion_leaf_0], file_type=parquet, predicate=c@0 = a@1 + b@2 AND c@0 + 1 = 7, sort_order_for_reorder=[a@1 ASC NULLS LAST] -query error SanityCheckPlan: order and distribution requirements stopped holding after physical optimizer rule 'ProjectionPushdown' +query III SELECT s['v'] + 1 AS l, a + b + 1 AS k, a FROM leaf_constant WHERE c = a + b AND c + 1 = 7 ORDER BY k, a; +---- +0 7 -1 +5 7 4 +6 7 5 +10 7 9 statement ok DROP TABLE leaf_constant; From e0bd9c81f49e3075eb20c7c47b4eb749648f668c Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Tue, 1 Dec 2026 12:21:15 -0800 Subject: [PATCH 4/7] perf: check the orderings of a split only if an ancestor can rely on them Otherwise the split reads a sort column, and builds a trial split, for an ordering that nothing needs. A sort replaces the ordering of its input, and `OutputRequirementExec` declares the one that the query needs. An operator that is not known to declare every ordering it relies on keeps the check. Co-Authored-By: Claude Opus 5.5 --- .../src/projection_pushdown.rs | 166 ++++++++++++++++-- .../test_files/projection_pushdown.slt | 12 +- 2 files changed, 156 insertions(+), 22 deletions(-) diff --git a/datafusion/physical-optimizer/src/projection_pushdown.rs b/datafusion/physical-optimizer/src/projection_pushdown.rs index 7cc7c79be6596..b5cb8515d793c 100644 --- a/datafusion/physical-optimizer/src/projection_pushdown.rs +++ b/datafusion/physical-optimizer/src/projection_pushdown.rs @@ -8,6 +8,7 @@ //! projection reaches a source, it can even disappear from the plan entirely. use crate::PhysicalOptimizerRule; +use crate::output_requirements::OutputRequirementExec; use arrow::datatypes::{Fields, Schema, SchemaRef}; use datafusion_common::alias::AliasGenerator; use std::collections::HashSet; @@ -24,12 +25,18 @@ use datafusion_physical_expr::projection::ProjectionExpr; use datafusion_physical_expr::utils::collect_columns; use datafusion_physical_expr::{conjunction, split_conjunction}; use datafusion_physical_expr_common::physical_expr::{PhysicalExpr, is_volatile}; -use datafusion_physical_plan::joins::NestedLoopJoinExec; +use datafusion_physical_plan::coalesce_partitions::CoalescePartitionsExec; +use datafusion_physical_plan::filter::FilterExec; use datafusion_physical_plan::joins::utils::{ColumnIndex, JoinFilter}; +use datafusion_physical_plan::joins::{HashJoinExec, NestedLoopJoinExec}; +use datafusion_physical_plan::limit::{GlobalLimitExec, LocalLimitExec}; use datafusion_physical_plan::projection::{ ProjectionExec, remove_unnecessary_projections, }; use datafusion_physical_plan::repartition::RepartitionExec; +use datafusion_physical_plan::sorts::sort::SortExec; +use datafusion_physical_plan::sorts::sort_preserving_merge::SortPreservingMergeExec; +use datafusion_physical_plan::union::UnionExec; use datafusion_physical_plan::{ ChildrenPropertiesMode, ExecutionPlan, ExecutionPlanProperties, Partitioning, ReplaceChildrenOptions, @@ -76,13 +83,10 @@ impl PhysicalOptimizerRule for ProjectionPushdown { // narrows and holds a computed one. `RepartitionExec` declines both, it // is not removable because it renames, and nothing else moved. let plan = plan.transform_down(remove_unnecessary_projections).data()?; - plan.transform_down(|plan| { - Ok(match try_split_leaf_projection(&plan)? { - Some(new_plan) => Transformed::yes(new_plan), - None => Transformed::no(plan), - }) - }) - .data() + // `OutputRequirementExec` declares the ordering that the query needs. Without + // one at the root, the caller may rely on any ordering of the output. + let order_matters = !plan.is::(); + split_projections(plan, order_matters) } fn name(&self) -> &str { @@ -509,6 +513,66 @@ fn leaf_column_name(index: usize) -> String { format!("{LEAF_COLUMN_PREFIX}_{index}") } +/// Calls [`try_split_leaf_projection`] on each node of `plan`, from the root down. +/// +/// `order_matters` is true if something above `plan` can rely on its ordering. +#[cfg_attr(feature = "recursive_protection", recursive::recursive)] +fn split_projections( + plan: Arc, + order_matters: bool, +) -> Result> { + let plan = try_split_leaf_projection(&plan, order_matters)?.unwrap_or(plan); + + let required = plan.required_input_ordering(); + let only_declared = relies_only_on_declared_ordering(&plan); + let mut changed = false; + let mut children = vec![]; + for (child, required) in plan.children().into_iter().zip(required) { + let order_matters = order_matters || required.is_some() || !only_declared; + // A sort replaces the ordering of its input, unless the input is sorted. + let order_matters = match plan.downcast_ref::() { + Some(sort) => { + order_matters + && child + .equivalence_properties() + .ordering_satisfy(sort.expr().clone())? + } + None => order_matters, + }; + let new_child = split_projections(Arc::clone(child), order_matters)?; + changed |= !Arc::ptr_eq(child, &new_child); + children.push(new_child); + } + if !changed { + return Ok(plan); + } + plan.replace_children( + children, + ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute), + ) +} + +/// Returns true for operators known to need no ordering of their input beyond +/// `required_input_ordering`. +/// +/// Any other operator can need one that it does not declare. `PartialSortExec` +/// does, and `AggregateExec` chooses its mode from the ordering of its input. +/// Nothing detects the wrong rows that a lost ordering then gives. +fn relies_only_on_declared_ordering(plan: &Arc) -> bool { + plan.is::() + || plan.is::() + || plan.is::() + || plan.is::() + || plan.is::() + || plan.is::() + || plan.is::() + || plan.is::() + || plan.is::() + || plan.is::() + || plan.is::() + || plan.is::() +} + /// Splits a `ProjectionExec` that mixes leaf expressions with ones that must /// stay in place, moving the leaves into a projection the source absorbs. /// @@ -519,6 +583,7 @@ fn leaf_column_name(index: usize) -> String { /// computation above the repartition, still parallelised. fn try_split_leaf_projection( plan: &Arc, + order_matters: bool, ) -> Result>> { let Some(projection) = plan.downcast_ref::() else { return Ok(None); @@ -539,7 +604,8 @@ fn try_split_leaf_projection( } let child = repartition.input(); - let passthrough_indices = choose_passthrough(plan, projection, child, &leaves)?; + let passthrough_indices = + choose_passthrough(plan, projection, child, &leaves, order_matters)?; let lower_projection = lower_projection(child, &leaves, &passthrough_indices)?; // Only commit the split if the child really absorbs the leaf projection. @@ -552,10 +618,9 @@ fn try_split_leaf_projection( rebuild_split(projection, &leaves, &passthrough_indices, child, new_child)?; // The columns were chosen before the lower projection moved, and the operator // that absorbs it recomputes its own properties. - Ok( - (keeps_equivalences(plan, &split)? && keeps_orderings(plan, &split)?) - .then_some(split), - ) + Ok((keeps_equivalences(plan, &split)? + && (!order_matters || keeps_orderings(plan, &split)?)) + .then_some(split)) } /// Returns the sorted indices of the `child` columns that a split passes through. @@ -564,6 +629,7 @@ fn choose_passthrough( projection: &ProjectionExec, child: &Arc, leaves: &[Arc], + order_matters: bool, ) -> Result> { // Pass through only the child columns the outer expressions still need. A // column used *only* inside an extracted leaf must be dropped, otherwise the @@ -571,7 +637,8 @@ fn choose_passthrough( // alongside the extracted field, which is worse than not splitting at all. let mut indices = collect_outer_columns(projection.expr(), leaves)?; let properties = plan.equivalence_properties(); - if properties.oeq_class().is_empty() && properties.eq_group().is_empty() { + let has_ordering = order_matters && !properties.oeq_class().is_empty(); + if !has_ordering && properties.eq_group().is_empty() { return Ok(indices); } let lower_projection = Arc::new(lower_projection(child, leaves, &indices)?); @@ -590,7 +657,7 @@ fn choose_passthrough( class.iter().for_each(&mut add_columns); } } - if !keeps_orderings(plan, &split)? { + if order_matters && !keeps_orderings(plan, &split)? { for ordering in child_properties.oeq_class().iter() { for sort_expr in ordering.iter() { add_columns(&sort_expr.expr); @@ -825,15 +892,82 @@ mod test { use super::*; use arrow::datatypes::{DataType, Field, FieldRef, Schema}; use datafusion_expr_common::operator::Operator; + use datafusion_functions::core::get_field; use datafusion_functions::math::random; - use datafusion_physical_expr::ScalarFunctionExpr; use datafusion_physical_expr::expressions::{binary, lit}; + use datafusion_physical_expr::{Distribution, ScalarFunctionExpr}; use datafusion_physical_expr_common::physical_expr::PhysicalExpr; + use datafusion_physical_expr_common::sort_expr::PhysicalSortExpr; use datafusion_physical_plan::displayable; use datafusion_physical_plan::empty::EmptyExec; + use datafusion_physical_plan::sorts::partial_sort::PartialSortExec; use insta::assert_snapshot; use std::sync::Arc; + /// `PartialSortExec` relies on the order of its input, but does not declare it. + #[test] + fn split_keeps_undeclared_ordering() -> Result<()> { + let v = Field::new("v", DataType::Int32, false); + let schema = Arc::new(Schema::new(vec![ + Field::new("c", DataType::Int32, false), + Field::new("a", DataType::Int32, false), + Field::new("b", DataType::Int32, false), + Field::new_struct("s", vec![v], false), + ])); + let column = |name: &str, index| -> Arc { + Arc::new(Column::new(name, index)) + }; + let sum = binary(column("a", 1), Operator::Plus, column("b", 2), &schema)?; + let predicate = binary(column("c", 0), Operator::Eq, Arc::clone(&sum), &schema)?; + let get_v = Arc::new(ScalarFunctionExpr::try_new( + get_field(), + vec![column("s", 3), lit("v")], + &schema, + Arc::new(ConfigOptions::default()), + )?); + let leaf = binary(get_v, Operator::Plus, lit(1), &schema)?; + + let sort_c = [PhysicalSortExpr::new_default(column("c", 0))].into(); + let plan = Arc::new(SortExec::new(sort_c, Arc::new(EmptyExec::new(schema)))); + let plan = Arc::new(FilterExec::try_new(predicate, plan)?); + // Absorbs the lower part of the split. The rename keeps it from being removed. + let exprs = [("c", "c2"), ("a", "a"), ("b", "b"), ("s", "s")] + .into_iter() + .enumerate() + .map(|(index, (name, alias))| (column(name, index), alias.to_string())); + let plan = Arc::new(ProjectionExec::try_new(exprs, plan)?); + let partitioning = Partitioning::RoundRobinBatch(4); + let plan = Arc::new(RepartitionExec::try_new(plan, partitioning)?); + let exprs = [(sum, "k"), (column("a", 1), "a"), (leaf, "v")] + .map(|(expr, alias)| (expr, alias.to_string())); + let plan = Arc::new(ProjectionExec::try_new(exprs, plan)?); + let sort_k = [("k", 0), ("a", 1)] + .map(|(name, index)| PhysicalSortExpr::new_default(column(name, index))); + let plan = + PartialSortExec::new(sort_k.into(), plan, 1).with_preserve_partitioning(true); + + // The query needs no ordering, so only the `PartialSortExec` can protect it. + let plan = OutputRequirementExec::new( + Arc::new(plan), + None, + Distribution::UnspecifiedDistribution, + None, + ); + let plan = ProjectionPushdown::new() + .optimize(Arc::new(plan), &ConfigOptions::default())?; + assert_snapshot!(displayable(plan.as_ref()).indent(false), @r" + OutputRequirementExec: order_by=[], dist_by=Unspecified + PartialSortExec: expr=[k@0 ASC, a@1 ASC], common_prefix_length=[1] + ProjectionExec: expr=[a@1 + b@2 as k, a@1 as a, __datafusion_leaf_0@3 + 1 as v] + RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, maintains_sort_order=true + ProjectionExec: expr=[c@0 as c2, a@1 as a, b@2 as b, get_field(s@3, v) as __datafusion_leaf_0] + FilterExec: c@0 = a@1 + b@2 + SortExec: expr=[c@0 ASC], preserve_partitioning=[false] + EmptyExec + "); + Ok(()) + } + #[tokio::test] async fn no_computation_does_not_project() -> Result<()> { let (left_schema, right_schema) = create_simple_schemas(); diff --git a/datafusion/sqllogictest/test_files/projection_pushdown.slt b/datafusion/sqllogictest/test_files/projection_pushdown.slt index 8f4d9f88921ad..f45e94125d204 100644 --- a/datafusion/sqllogictest/test_files/projection_pushdown.slt +++ b/datafusion/sqllogictest/test_files/projection_pushdown.slt @@ -2924,9 +2924,9 @@ logical_plan 02)--Filter: leaf_ordered.c = leaf_ordered.a + leaf_ordered.b 03)----TableScan: leaf_ordered projection=[c, a, b, s], partial_filters=[leaf_ordered.c = leaf_ordered.a + leaf_ordered.b] physical_plan -01)ProjectionExec: expr=[__datafusion_leaf_0@3 + 1 as l, a@1 + b@2 as k] -02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, maintains_sort_order=true -03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/leaf_ordered.parquet]]}, projection=[c, a, b, get_field(s@3, v) as __datafusion_leaf_0], output_ordering=[c@0 ASC NULLS LAST], file_type=parquet, predicate=c@0 = a@1 + b@2 +01)ProjectionExec: expr=[__datafusion_leaf_0@2 + 1 as l, a@0 + b@1 as k] +02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1 +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/leaf_ordered.parquet]]}, projection=[a, b, get_field(s@3, v) as __datafusion_leaf_0], file_type=parquet, predicate=c@0 = a@1 + b@2 # The same for a sort by another key, which does not need the order of its input. query TT @@ -2940,9 +2940,9 @@ logical_plan physical_plan 01)SortPreservingMergeExec: [l@0 ASC NULLS LAST] 02)--SortExec: expr=[l@0 ASC NULLS LAST], preserve_partitioning=[true] -03)----ProjectionExec: expr=[__datafusion_leaf_0@3 + 1 as l, a@1 + b@2 as k] -04)------RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, maintains_sort_order=true -05)--------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/leaf_ordered.parquet]]}, projection=[c, a, b, get_field(s@3, v) as __datafusion_leaf_0], output_ordering=[c@0 ASC NULLS LAST], file_type=parquet, predicate=c@0 = a@1 + b@2 +03)----ProjectionExec: expr=[__datafusion_leaf_0@2 + 1 as l, a@0 + b@1 as k] +04)------RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1 +05)--------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/leaf_ordered.parquet]]}, projection=[a, b, get_field(s@3, v) as __datafusion_leaf_0], file_type=parquet, predicate=c@0 = a@1 + b@2 # `c` makes `k` constant, so the plan sorts by `a` alone. query I From ababa7c5fb296098486f330aabfb35ea501e060f Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Tue, 1 Dec 2026 15:20:06 -0800 Subject: [PATCH 5/7] fix: declare the input ordering that PartialSortExec requires The operator sorts each run of equal prefix values, so it returns wrong rows if its input is not sorted by the prefix. Without the declaration, the optimizer rules and SanityCheckPlan cannot see that. Co-Authored-By: Claude Opus 5.5 --- .../physical-plan/src/sorts/partial_sort.rs | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/datafusion/physical-plan/src/sorts/partial_sort.rs b/datafusion/physical-plan/src/sorts/partial_sort.rs index 86b4b771162c0..5eef56c6926ac 100644 --- a/datafusion/physical-plan/src/sorts/partial_sort.rs +++ b/datafusion/physical-plan/src/sorts/partial_sort.rs @@ -65,6 +65,7 @@ use datafusion_common::tree_node::TreeNodeRecursion; use datafusion_common::utils::evaluate_partition_ranges; use datafusion_execution::{RecordBatchStream, TaskContext}; use datafusion_physical_expr::{LexOrdering, PhysicalExpr}; +use datafusion_physical_expr_common::sort_expr::OrderingRequirements; use futures::{Stream, StreamExt, ready}; use log::trace; @@ -358,6 +359,11 @@ impl ExecutionPlan for PartialSortExec { }) } + fn required_input_ordering(&self) -> Vec> { + let prefix = self.expr[..self.common_prefix_length].to_vec(); + vec![LexOrdering::new(prefix).map(OrderingRequirements::from)] + } + fn benefits_from_input_partitioning(&self) -> Vec { vec![false] } @@ -1188,6 +1194,21 @@ mod tests { .unwrap() as Arc } + #[test] + fn requires_common_prefix_ordering() { + let expr = [("a", 0), ("b", 1)].map(|(name, i)| { + PhysicalSortExpr::new_default(Arc::new(crate::expressions::Column::new( + name, i, + )) as _) + }); + let first = LexOrdering::from([expr[0].clone()]); + let plan = PartialSortExec::new(expr.into(), prepare_partitioned_input(), 1); + assert_eq!( + plan.required_input_ordering(), + vec![Some(OrderingRequirements::from(first))] + ); + } + #[tokio::test] async fn test_partitioned_input_partial_sort() -> Result<()> { let task_ctx = Arc::new(TaskContext::default()); From 03a3bdd1cb291e534fc22d63e4e45f8883726c5a Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Tue, 1 Dec 2026 15:20:06 -0800 Subject: [PATCH 6/7] refactor: derive which orderings matter from the ExecutionPlan API The list of known operators excludes extension nodes. The ordering of a child matters if its parent requires one, or maintains one that matters. The ordering of the root always matters. A query without ORDER BY can thus read a sort column more than before. Co-Authored-By: Claude Opus 5.5 --- .../src/projection_pushdown.rs | 65 +++++-------------- .../test_files/projection_pushdown.slt | 10 +-- 2 files changed, 21 insertions(+), 54 deletions(-) diff --git a/datafusion/physical-optimizer/src/projection_pushdown.rs b/datafusion/physical-optimizer/src/projection_pushdown.rs index b5cb8515d793c..e9c7ff1d4e7a8 100644 --- a/datafusion/physical-optimizer/src/projection_pushdown.rs +++ b/datafusion/physical-optimizer/src/projection_pushdown.rs @@ -8,7 +8,6 @@ //! projection reaches a source, it can even disappear from the plan entirely. use crate::PhysicalOptimizerRule; -use crate::output_requirements::OutputRequirementExec; use arrow::datatypes::{Fields, Schema, SchemaRef}; use datafusion_common::alias::AliasGenerator; use std::collections::HashSet; @@ -25,18 +24,12 @@ use datafusion_physical_expr::projection::ProjectionExpr; use datafusion_physical_expr::utils::collect_columns; use datafusion_physical_expr::{conjunction, split_conjunction}; use datafusion_physical_expr_common::physical_expr::{PhysicalExpr, is_volatile}; -use datafusion_physical_plan::coalesce_partitions::CoalescePartitionsExec; -use datafusion_physical_plan::filter::FilterExec; +use datafusion_physical_plan::joins::NestedLoopJoinExec; use datafusion_physical_plan::joins::utils::{ColumnIndex, JoinFilter}; -use datafusion_physical_plan::joins::{HashJoinExec, NestedLoopJoinExec}; -use datafusion_physical_plan::limit::{GlobalLimitExec, LocalLimitExec}; use datafusion_physical_plan::projection::{ ProjectionExec, remove_unnecessary_projections, }; use datafusion_physical_plan::repartition::RepartitionExec; -use datafusion_physical_plan::sorts::sort::SortExec; -use datafusion_physical_plan::sorts::sort_preserving_merge::SortPreservingMergeExec; -use datafusion_physical_plan::union::UnionExec; use datafusion_physical_plan::{ ChildrenPropertiesMode, ExecutionPlan, ExecutionPlanProperties, Partitioning, ReplaceChildrenOptions, @@ -83,10 +76,9 @@ impl PhysicalOptimizerRule for ProjectionPushdown { // narrows and holds a computed one. `RepartitionExec` declines both, it // is not removable because it renames, and nothing else moved. let plan = plan.transform_down(remove_unnecessary_projections).data()?; - // `OutputRequirementExec` declares the ordering that the query needs. Without - // one at the root, the caller may rely on any ordering of the output. - let order_matters = !plan.is::(); - split_projections(plan, order_matters) + // The rule also runs after `OutputRequirementExec` is removed, where nothing + // declares the ordering of the query, so the ordering of the root matters. + split_projections(plan, true) } fn name(&self) -> &str { @@ -515,7 +507,8 @@ fn leaf_column_name(index: usize) -> String { /// Calls [`try_split_leaf_projection`] on each node of `plan`, from the root down. /// -/// `order_matters` is true if something above `plan` can rely on its ordering. +/// `order_matters` is true if something above `plan` can rely on its ordering: +/// an ancestor requires one, and every operator in between maintains it. #[cfg_attr(feature = "recursive_protection", recursive::recursive)] fn split_projections( plan: Arc, @@ -524,21 +517,13 @@ fn split_projections( let plan = try_split_leaf_projection(&plan, order_matters)?.unwrap_or(plan); let required = plan.required_input_ordering(); - let only_declared = relies_only_on_declared_ordering(&plan); + let maintains = plan.maintains_input_order(); let mut changed = false; let mut children = vec![]; - for (child, required) in plan.children().into_iter().zip(required) { - let order_matters = order_matters || required.is_some() || !only_declared; - // A sort replaces the ordering of its input, unless the input is sorted. - let order_matters = match plan.downcast_ref::() { - Some(sort) => { - order_matters - && child - .equivalence_properties() - .ordering_satisfy(sort.expr().clone())? - } - None => order_matters, - }; + for ((child, required), maintains) in + plan.children().into_iter().zip(required).zip(maintains) + { + let order_matters = required.is_some() || (maintains && order_matters); let new_child = split_projections(Arc::clone(child), order_matters)?; changed |= !Arc::ptr_eq(child, &new_child); children.push(new_child); @@ -552,27 +537,6 @@ fn split_projections( ) } -/// Returns true for operators known to need no ordering of their input beyond -/// `required_input_ordering`. -/// -/// Any other operator can need one that it does not declare. `PartialSortExec` -/// does, and `AggregateExec` chooses its mode from the ordering of its input. -/// Nothing detects the wrong rows that a lost ordering then gives. -fn relies_only_on_declared_ordering(plan: &Arc) -> bool { - plan.is::() - || plan.is::() - || plan.is::() - || plan.is::() - || plan.is::() - || plan.is::() - || plan.is::() - || plan.is::() - || plan.is::() - || plan.is::() - || plan.is::() - || plan.is::() -} - /// Splits a `ProjectionExec` that mixes leaf expressions with ones that must /// stay in place, moving the leaves into a projection the source absorbs. /// @@ -890,6 +854,7 @@ fn rewrite_outer_expr( #[cfg(test)] mod test { use super::*; + use crate::output_requirements::OutputRequirementExec; use arrow::datatypes::{DataType, Field, FieldRef, Schema}; use datafusion_expr_common::operator::Operator; use datafusion_functions::core::get_field; @@ -900,13 +865,15 @@ mod test { use datafusion_physical_expr_common::sort_expr::PhysicalSortExpr; use datafusion_physical_plan::displayable; use datafusion_physical_plan::empty::EmptyExec; + use datafusion_physical_plan::filter::FilterExec; use datafusion_physical_plan::sorts::partial_sort::PartialSortExec; + use datafusion_physical_plan::sorts::sort::SortExec; use insta::assert_snapshot; use std::sync::Arc; - /// `PartialSortExec` relies on the order of its input, but does not declare it. + /// `PartialSortExec` requires that its input is sorted by the common prefix. #[test] - fn split_keeps_undeclared_ordering() -> Result<()> { + fn split_keeps_partial_sort_prefix() -> Result<()> { let v = Field::new("v", DataType::Int32, false); let schema = Arc::new(Schema::new(vec![ Field::new("c", DataType::Int32, false), diff --git a/datafusion/sqllogictest/test_files/projection_pushdown.slt b/datafusion/sqllogictest/test_files/projection_pushdown.slt index f45e94125d204..bf708a3e928c2 100644 --- a/datafusion/sqllogictest/test_files/projection_pushdown.slt +++ b/datafusion/sqllogictest/test_files/projection_pushdown.slt @@ -2915,7 +2915,7 @@ GROUP BY k ORDER BY k; 8 5 10 6 -# Nothing needs the order of `k`, so the scan does not read `c`. +# The output of the plan keeps the order of `k`, so the scan reads `c`. query TT EXPLAIN SELECT s['v'] + 1 AS l, a + b AS k FROM leaf_ordered WHERE c = a + b; ---- @@ -2924,11 +2924,11 @@ logical_plan 02)--Filter: leaf_ordered.c = leaf_ordered.a + leaf_ordered.b 03)----TableScan: leaf_ordered projection=[c, a, b, s], partial_filters=[leaf_ordered.c = leaf_ordered.a + leaf_ordered.b] physical_plan -01)ProjectionExec: expr=[__datafusion_leaf_0@2 + 1 as l, a@0 + b@1 as k] -02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1 -03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/leaf_ordered.parquet]]}, projection=[a, b, get_field(s@3, v) as __datafusion_leaf_0], file_type=parquet, predicate=c@0 = a@1 + b@2 +01)ProjectionExec: expr=[__datafusion_leaf_0@3 + 1 as l, a@1 + b@2 as k] +02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, maintains_sort_order=true +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/leaf_ordered.parquet]]}, projection=[c, a, b, get_field(s@3, v) as __datafusion_leaf_0], output_ordering=[c@0 ASC NULLS LAST], file_type=parquet, predicate=c@0 = a@1 + b@2 -# The same for a sort by another key, which does not need the order of its input. +# A sort by another key does not need the order of `k`, so the scan does not read `c`. query TT EXPLAIN SELECT s['v'] + 1 AS l, a + b AS k FROM leaf_ordered WHERE c = a + b ORDER BY l; ---- From 8ddb27ddeceba17d0ec38644612ffd2d5b0eea49 Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Tue, 1 Dec 2026 17:00:14 -0800 Subject: [PATCH 7/7] perf: start with no ordering requirement at the root of a leaf split Before OutputRequirementExec is removed, it declares the ordering of the query. After, the round robin repartition loses any global ordering, so an operator above it that needs one declares it. A query without ORDER BY then no longer reads a sort column that nothing needs. Co-Authored-By: Claude Opus 5.5 --- datafusion/physical-optimizer/src/projection_pushdown.rs | 7 ++++--- .../sqllogictest/test_files/projection_pushdown.slt | 8 ++++---- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/datafusion/physical-optimizer/src/projection_pushdown.rs b/datafusion/physical-optimizer/src/projection_pushdown.rs index e9c7ff1d4e7a8..a1a6414774421 100644 --- a/datafusion/physical-optimizer/src/projection_pushdown.rs +++ b/datafusion/physical-optimizer/src/projection_pushdown.rs @@ -76,9 +76,10 @@ impl PhysicalOptimizerRule for ProjectionPushdown { // narrows and holds a computed one. `RepartitionExec` declines both, it // is not removable because it renames, and nothing else moved. let plan = plan.transform_down(remove_unnecessary_projections).data()?; - // The rule also runs after `OutputRequirementExec` is removed, where nothing - // declares the ordering of the query, so the ordering of the root matters. - split_projections(plan, true) + // Before `OutputRequirementExec` is removed, it declares the ordering of the + // query. After, an operator that needs a global ordering, such as a sort or a + // merge, declares it, because the round robin repartition loses it. + split_projections(plan, false) } fn name(&self) -> &str { diff --git a/datafusion/sqllogictest/test_files/projection_pushdown.slt b/datafusion/sqllogictest/test_files/projection_pushdown.slt index bf708a3e928c2..262dc65d052b4 100644 --- a/datafusion/sqllogictest/test_files/projection_pushdown.slt +++ b/datafusion/sqllogictest/test_files/projection_pushdown.slt @@ -2915,7 +2915,7 @@ GROUP BY k ORDER BY k; 8 5 10 6 -# The output of the plan keeps the order of `k`, so the scan reads `c`. +# Nothing needs the order of `k`, so the scan does not read `c`. query TT EXPLAIN SELECT s['v'] + 1 AS l, a + b AS k FROM leaf_ordered WHERE c = a + b; ---- @@ -2924,9 +2924,9 @@ logical_plan 02)--Filter: leaf_ordered.c = leaf_ordered.a + leaf_ordered.b 03)----TableScan: leaf_ordered projection=[c, a, b, s], partial_filters=[leaf_ordered.c = leaf_ordered.a + leaf_ordered.b] physical_plan -01)ProjectionExec: expr=[__datafusion_leaf_0@3 + 1 as l, a@1 + b@2 as k] -02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, maintains_sort_order=true -03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/leaf_ordered.parquet]]}, projection=[c, a, b, get_field(s@3, v) as __datafusion_leaf_0], output_ordering=[c@0 ASC NULLS LAST], file_type=parquet, predicate=c@0 = a@1 + b@2 +01)ProjectionExec: expr=[__datafusion_leaf_0@2 + 1 as l, a@0 + b@1 as k] +02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1 +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/leaf_ordered.parquet]]}, projection=[a, b, get_field(s@3, v) as __datafusion_leaf_0], file_type=parquet, predicate=c@0 = a@1 + b@2 # A sort by another key does not need the order of `k`, so the scan does not read `c`. query TT