Skip to content

fix: keep the output properties of a leaf projection split - #27925

Open
adriangb wants to merge 7 commits into
apache:mainfrom
adriangb:adriangb/leaf-split-properties
Open

adriangb wants to merge 7 commits into
apache:mainfrom
adriangb:adriangb/leaf-split-properties

Conversation

@adriangb

@adriangb adriangb commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

Which issue does this PR close?

No issue. This is also preparation for #27867, which is stacked on it.

Rationale for this change

#27152 splits a projection across a round robin repartition to extract leaf expressions such as s['v']. The split can drop a column that gives the output its ordering, or makes it constant. If an ancestor relies on that, the query fails to plan:

SET datafusion.execution.target_partitions = 4;
SET datafusion.execution.batch_size = 2;
SET datafusion.execution.parquet.pushdown_filters = true;
SET datafusion.optimizer.enable_leaf_expression_pushdown = false;
COPY (SELECT value * 2 AS c, value AS a, value AS b, named_struct('v', value) AS s
      FROM range(0, 20)) TO 'o.parquet' STORED AS PARQUET;
CREATE EXTERNAL TABLE o STORED AS PARQUET LOCATION 'o.parquet' WITH ORDER (c ASC);
SELECT s['v'] + 1 AS k, a + b AS m FROM o WHERE c = a + b ORDER BY m LIMIT 2;
-- SanityCheckPlan: order and distribution requirements stopped holding after
-- physical optimizer rule 'ProjectionPushdown'

All the failures we know need the non-default enable_leaf_expression_pushdown = false. The pruning in #27867 reaches the same problem with the default settings.

What changes are included in this PR?

 try_split_leaf_projection
+  columns = those that the expressions read
+  an equality or constant would be lost   -> columns += those of the input equivalences
+  an ordering that matters would be lost  -> columns += the sort columns of the input
   push the lower projection
+  one of these properties is lost         -> keep the plan
   otherwise                               -> commit the split
  • Constants and equalities are always protected, because sorts and repartitions keep them. Equalities that contain a leaf expression are not compared: every split that extracts the leaf loses them, also on main.
  • Orderings are protected only if an ancestor can rely on them. A sort replaces the ordering of its input, and OutputRequirementExec declares the one that the query needs.
  • Unknown operators count as relying on their input ordering, because they may not declare that. PartialSortExec does not, and nothing would detect the wrong rows. The list of known operators in relies_only_on_declared_ordering deserves review.

Some queries that split today do more planning work, because the check builds a trial split. The benchmarks of the stacked PR include this cost.

Review commit by commit:

  1. Extract two helpers. No behavior change.
  2. Add tests with the plans and the errors of main.
  3. Protect every property. Two plans read a column more than on main.
  4. Protect only the orderings that an ancestor can rely on. Those two plans are again as on main.

AI assistance

Claude Code wrote the code, the tests and this description at the request of the PR author.

What is the testing strategy for this PR?

  • SLT cases for a merge, an aggregate and a constant sort key that fail on main, and for two plans that must not change.
  • A unit test for a PartialSortExec. It fails if unknown operators lose the protection.
  • A differential test, not part of this PR: 20,736 generated queries with constants, equalities, grouping, joins, unions and windows. The results agree wherever main plans the query. None newly fails to plan, and 12 that fail on main now succeed.

Are there any user-facing changes?

No public API changes. Some queries that fail to plan now succeed.

🤖 Generated with Claude Code

adriangb and others added 4 commits December 1, 2026 12:15
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
…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 <noreply@anthropic.com>
@adriangb
adriangb requested a review from kosiew December 1, 2026 21:41
@adriangb
adriangb marked this pull request as ready for review December 1, 2026 21:41
@github-actions github-actions Bot added optimizer Optimizer rules sqllogictest SQL Logic Tests (.slt) labels Dec 1, 2026

@alamb alamb left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for working on this @adriangb -- this feels like it is not quite right given all the operator special casing. I left some comments -- let me know what you think

.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::<OutputRequirementExec>();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this seems incorrect to me to special case check for OutputRequirementExec -- @jayzhan211 and I just today updated the docs to try and explain what it does better:

/// OptimizerRule that preserves the final query output ordering and
/// distribution requirements across physical plan rewrites.
///
/// This rule is needed because global ordering (and distribution) requirements
/// are not explicitly represented in an [`ExecutionPlan`]. Thus, the optimizer
/// may rewrite the plan in ways that break the global ordering (and thus
/// produce wrong results).
///
/// # Example
///
/// For example, the query `SELECT a FROM t ORDER BY a` requires that the final
/// output be sorted by `a`.
///
/// If a single partition data source is already sorted by `a`, the simplified
/// physical plan starts with a sort above the scan:
///
/// ```text
/// SortExec: expr=[a@0 ASC NULLS LAST], preserve_partitioning=[false]
/// DataSourceExec: projection=[a], output_ordering=[a@0 ASC NULLS LAST]
/// ```
///
/// The optimizer then removes the redundant sort because the scan already
/// produces the requested order.
///
/// ```text
/// DataSourceExec: projection=[a], output_ordering=[a@0 ASC NULLS LAST]
/// ```
///
/// However, a later rewrite could split the scan into several partitions to
/// read it in parallel, and the resulting plan would no longer be globally
/// sorted (and thus would produce wrong results).
///
/// To ensure the output is sorted correctly, this rule adds an
/// [`OutputRequirementExec`] above the original sort. It reports the overall
/// query's requirements as its required input ordering and distribution, which
/// are ensured by [`EnsureRequirements`].
///
/// [`EnsureRequirements`]: crate::ensure_requirements::EnsureRequirements
///
/// ```text
/// OutputRequirementExec: order_by=[(a@0, asc)], dist_by=SinglePartition
/// SortExec: expr=[a@0 ASC NULLS LAST], preserve_partitioning=[false]
/// DataSourceExec: projection=[a], output_ordering=[a@0 ASC NULLS LAST]
/// ```
///
/// # Add and Remove Modes
///
/// At the start of physical optimization, the rule runs in **add** mode and
/// always places an [`OutputRequirementExec`]. If there is no `SortExec` or
/// `SortPreservingMergeExec` to take the requirements from, it is placed at the
/// root with no ordering requirement and an unspecified distribution.
///
/// After [`EnsureRequirements`] has made the plan satisfy the requirements, the
/// rule runs in **remove** mode to take the [`OutputRequirementExec`] out. Rules
/// that run after remove mode can no longer see the requirements, so they must
/// keep the plan's output ordering and partitioning themselves.

Basically ordering should matter if the node above this one is relying on the ordering coming out

/// 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<dyn ExecutionPlan>) -> bool {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If this is an important property if should be put on ExectionPlan rather than this hard coded list -- otherwise extension nodes can't transmit it

I also don't understand how it differs from required_input_ordering -- all those operators don't need a required_input_ordering execept SortPreservingMergeExec

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Poking around with the 🤖 it seems like maybe the real issue is that PartialSortExec does not declare required_input_ordering or maintains_input_order. even though it relies on its sorted prefix

We could probably add that as a separate PR (and remove the generic check here)

Distribution::UnspecifiedDistribution => {
// Since ordering is lost, trying to preserve ordering is pointless
if !maintains_input_order
|| plan.is::<OutputRequirementExec>()
{
context = replace_order_preserving_variants(context)?;
}
}

adriangb and others added 2 commits December 1, 2026 15:20
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
@github-actions github-actions Bot added the physical-plan Changes to the physical-plan crate label Dec 1, 2026
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 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

optimizer Optimizer rules physical-plan Changes to the physical-plan crate sqllogictest SQL Logic Tests (.slt)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants