Skip to content

Push the fetch of a sort removed by PushdownSort down like LimitPushdown does - #27816

Merged
adriangb merged 5 commits into
apache:mainfrom
zhuqi-lucas:qizhu/pushdown-sort-fetch-through-projection
Dec 1, 2026
Merged

adriangb merged 5 commits into
apache:mainfrom
zhuqi-lucas:qizhu/pushdown-sort-fetch-through-projection

Conversation

@zhuqi-lucas

@zhuqi-lucas zhuqi-lucas commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Which issue does this PR close?

None.

Rationale for this change

This is a missed optimization, not a wrong-results bug: the rows are the same either way, but the source never gets the fetch.

When PushdownSort removes a SortExec that has a fetch, it hands the fetch to the node right below the sort, or puts a limit node on top of it. Nodes like ProjectionExec and CooperativeExec take no fetch, so the limit stays above them and the source never sees it. PushdownSort runs after LimitPushdown, so nothing moves it later.

A parquet scan hits this when an expression repeats, here on a table whose files PushdownSort puts in order by their statistics. The scan absorbs the common subexpression, but not the projection that uses it twice, since that would compute it twice:

SELECT id, (value + 1) * 2 AS a, (value + 1) * 3 AS b
FROM t ORDER BY id LIMIT 2
GlobalLimitExec: skip=0, fetch=2
  ProjectionExec: expr=[id@1 as id, __common_expr_1@0 * 2 as a, __common_expr_1@0 * 3 as b]
    DataSourceExec: projection=[CAST(value@1 AS Int64) + 1 as __common_expr_1, id], file_type=parquet

With this PR the scan gets limit=2. Custom sources that keep a ProjectionExec above them hit the same thing.

What changes are included in this PR?

PushdownSort puts the limit node on top of the new input as before, then pushes it down with LimitPushdown's own logic. Each node's limit_behavior decides where it goes: it passes nodes that keep the row count, such as ProjectionExec and CooperativeExec, stops above nodes it can't cross, such as RepartitionExec, and lands in the first node that takes it as a fetch.

limit_pushdown.rs gets a crate-private push_down_limits entry point for this. The first commit only moves the rule body into a function. The second is the fix, and the third adds the tests.

TestScan keeps its partitioning when it accepts a sort, and reports itself as a leaf that takes a limit as its fetch. The exact_sort_source used by sort_pushdown.slt gets a variant that takes a fetch, exact_sort_fetch_source.

Are these changes tested?

Yes, in pushdown_sort.rs: 8 plan tests (through projections and CooperativeExec, sources with and without fetch support, OFFSET, partitioned sorts, and a repartition the limit must not pass) and 2 tests that run the optimized plan and check the rows.

In sort_pushdown.slt, plans and results for the parquet query above, and for a custom source below a projection: the fetch ends up in the source when it takes one, and in a LocalLimitExec right above it otherwise, each also with OFFSET. Without the fix, all five plans keep the limit above the projection.

Are there any user-facing changes?

No.

@github-actions github-actions Bot added optimizer Optimizer rules core Core DataFusion crate labels Nov 28, 2026
@zhuqi-lucas
zhuqi-lucas marked this pull request as ready for review December 1, 2026 03:24
@zhuqi-lucas
zhuqi-lucas requested review from adriangb, alamb and jayzhan211 and a balanced review from Copilot December 1, 2026 03:24
@zhuqi-lucas zhuqi-lucas changed the title Push the fetch of a sort removed by PushdownSort through projections Push the fetch of a sort removed by PushdownSort down like LimitPushdown does Dec 1, 2026
@zhuqi-lucas
zhuqi-lucas requested a review from xudong963 December 1, 2026 03:31

Copilot AI 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.

🟢 Approval recommended

No active review issues were identified for the changes that propagate eliminated-sort fetch limits through eligible operators.

No open issues 🎉

What changed in this PR

This PR lets PushdownSort pass an eliminated sort’s fetch through projections and other eligible operators, allowing custom sources to receive the limit even after LimitPushdown has run.

Changes:

  • Reuses limit-pushdown logic with a statistics context while preserving global and per-partition limit semantics.
  • Updates test sources to support exact sort pushdown and preserve partitioning.
  • Adds eight plan tests and two execution tests covering projections, cooperative execution, offsets, partitioned sorts, and repartition barriers.
File Description
datafusion/​physical-optimizer/​src/​pushdown_sort.rs Adds optimize_with_context and pushes fetch limits down after sort elimination.
datafusion/​physical-optimizer/​src/​limit_pushdown.rs Adds the crate-visible push_down_limits helper for reuse by other rules.
datafusion/​core/​tests/​physical_optimizer/​test_utils.rs Adds exact_memory_exec and updates test-source limit and partitioning behavior.
datafusion/​core/​tests/​physical_optimizer/​pushdown_sort.rs Adds plan and execution coverage for fetch pushdown.

Review effort: Balanced

@github-actions github-actions Bot added the sqllogictest SQL Logic Tests (.slt) label Dec 1, 2026
@adriangb

adriangb commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

@zhuqi-lucas I'm trying to review this but struggling to wade through refactor diff vs. change diff. For future: could I ask that you make 2 commits: a refactor commit (in this case factoring away sort pushdown into pushdown_sorts) and a separate fix/perf/etc commit that changes only the relevant code? That would let me skip over the refactor commit (I agree it's good and can have an agent check that it is indeed a pure refactor) and focus my attention on the code that has actually been changed 🙏🏻

@adriangb

adriangb commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

Another minor piece of feedback: I had to think a bit (and ask an agent to confirm) that this is a missed-optimization fix, not a bug fix. It was not clear from the title / description if this is fixing a bug / incorrect results or a performance improvement.

@zhuqi-lucas
zhuqi-lucas force-pushed the qizhu/pushdown-sort-fetch-through-projection branch from 1298bb8 to a2952bd Compare December 1, 2026 06:49
@zhuqi-lucas

zhuqi-lucas commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks @adriangb ! Split it into three commits: 11fe34a only moves the rule body into a function, 3d15566 is the fix, and a2952bd adds the tests. It's a missed optimization, not a wrong-results bug; I added that to the description.

@adriangb adriangb 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.

Thank you @zhuqi-lucas! The reuse of the LimitPushdown logic keeps this change small. I left a few small suggestions about the tests.

Comment on lines +1111 to +1114
// A leaf: it takes a limit as its own fetch, like `DataSourceExec`.
fn limit_behavior(&self) -> LimitBehavior {
LimitBehavior::Stops
}

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.

Nit: could we remove both methods? DataSourceExec overrides neither of them. It accepts a limit through with_fetch, and TestScan keeps that method. supports_limit_pushdown tells the optimizer that a limit can pass through to the input, but a leaf has no input. The default limit_behavior is already Stops, so the pushdown_sort tests pass with this change:

-    fn supports_limit_pushdown(&self) -> bool {
-        self.supports_fetch
-    }
-
-    // A leaf: it takes a limit as its own fetch, like `DataSourceExec`.
-    fn limit_behavior(&self) -> LimitBehavior {
-        LimitBehavior::Stops
-    }
-

The LimitBehavior import is then unused.

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

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.

The PR description says that each case also has an OFFSET test. Could we add the one for the source without a fetch? This passes locally.

Suggested change
06)----------ExactSortSource: fetch=5
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

----
0 3
0 4
0 5

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.

Could we also check the rows for the LocalLimitExec path? These queries pass locally.

Suggested change
0 5
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

Comment on lines +1226 to +1227
// The limit of the eliminated SortExec passes the projection and goes
// into the source, instead of staying above the projection.

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.

Nit: the comment can describe only the current behavior.

Suggested change
// The limit of the eliminated SortExec passes the projection and goes
// into the source, instead of staying above the projection.
// The limit of the eliminated SortExec passes the projection and goes
// into the source.

#[test]
fn test_sort_pushdown_exact_partitioned_pushes_fetch_through_projection() {
// SPM -> SortExec(preserve_partitioning): each partition keeps its own
// fetch, now in the source below the projection.

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.

Nit: same here.

Suggested change
// fetch, now in the source below the projection.
// fetch, in the source below the projection.

@xudong963 xudong963 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

it routes ORDER BY … LIMIT into a hole in LimitPushdown that silently drops the limit for custom leaves using the deprecated supports_limit_pushdown() hook. Can we consider this case?

@adriangb

adriangb commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

it routes ORDER BY … LIMIT into a hole in LimitPushdown that silently drops the limit for custom leaves using the deprecated supports_limit_pushdown() hook. Can we consider this case?

Claude caught the same thing on my end and freaked out about it. I was writing this artisanal comment because I disagree with Claude on this one. IMO we could handle it, but not in this PR. It's a pre-existing issue, this PR just exposes new query patterns to it. Not just that: it only happens when deprecated methods are involved. What I propose: we file an issue for it and don't block this PR. THen in that issue we can discuss if it's worth fixing, etc.

@zhuqi-lucas

zhuqi-lucas commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor Author

it routes ORDER BY … LIMIT into a hole in LimitPushdown that silently drops the limit for custom leaves using the deprecated supports_limit_pushdown() hook. Can we consider this case?

Claude caught the same thing on my end and freaked out about it. I was writing this artisanal comment because I disagree with Claude on this one. IMO we could handle it, but not in this PR. It's a pre-existing issue, this PR just exposes new query patterns to it. Not just that: it only happens when deprecated methods are involved. What I propose: we file an issue for it and don't block this PR. THen in that issue we can discuss if it's worth fixing, etc.

Thanks @xudong963 and @adriangb! Filed #27891 for the leaf case. It's pre-existing, a plain LIMIT hits it too. Also applied the test suggestions.

@alamb

alamb commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

🧑‍🍳 👌

@adriangb
adriangb added this pull request to the merge queue Dec 1, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Dec 1, 2026
@adriangb
adriangb added this pull request to the merge queue Dec 1, 2026
Merged via the queue into apache:main with commit dc1245a Dec 1, 2026
42 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

core Core DataFusion crate optimizer Optimizer rules sqllogictest SQL Logic Tests (.slt) v57.0.0

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants