You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@datafusion.apache.org by "masonh22 (via GitHub)" <gi...@apache.org> on 2026/01/28 15:04:40 UTC
[PR] fix: The limit_pushdown physical optimization rule removes nested limits in some cases [datafusion]
masonh22 opened a new pull request, #20048:
URL: https://github.com/apache/datafusion/pull/20048
## Which issue does this PR close?
<!--
We generally require a GitHub issue to be filed for all bug fixes and enhancements and this helps us generate change logs for our releases. You can link an issue to this PR using the GitHub syntax. For example `Closes #123` indicates that this PR will close issue #123.
-->
None
## Rationale for this change
<!--
Why are you proposing this change? If this is already explained clearly in the issue then this section is not needed.
Explaining clearly why changes are proposed helps reviewers understand your changes and offer better suggestions for fixes.
-->
When pushing down limits, we recurse down the physical plan accumulating limits until we reach a node where we can't push the limit down further. At this point, we insert another limit executor (or push it into the current node, if that node supports it). After this, we continue recursing to try to find more limits to push down. If we do find another, we remove it, but we don't set the `GlobalRequirements::satisfied` field back to false, meaning we don't always re-insert this limit.
## What changes are included in this PR?
<!--
There is no need to duplicate the description in the issue here but it is sometimes worth providing a summary of the individual changes in this PR.
-->
This includes a one-line change to the push down limit logic that fixes the issue.
## Are these changes tested?
<!--
We typically require tests for all PRs in order to:
1. Prevent the code from being accidentally broken by subsequent changes
2. Serve as another way to document the expected behavior of the code
If tests are not included in your PR, please explain why (for example, are they covered by existing tests)?
-->
I added a test that replicates the issue and fails without this change.
## Are there any user-facing changes?
<!--
If there are user-facing changes then we may require documentation to be updated before approving the PR.
-->
No
<!--
If there are any breaking changes to public APIs, please add the `api change` label.
-->
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] fix: The limit_pushdown physical optimization rule removes nested limits in some cases [datafusion]
Posted by "masonh22 (via GitHub)" <gi...@apache.org>.
masonh22 commented on PR #20048:
URL: https://github.com/apache/datafusion/pull/20048#issuecomment-3812637469
Found one more bug. I updated the PR description and added a test + fix for that bug.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] fix: The limit_pushdown physical optimization rule removes limits in some cases leading to incorrect results [datafusion]
Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #20048:
URL: https://github.com/apache/datafusion/pull/20048#issuecomment-3819226110
> Nice find, I think you fixed a long standing bug. @alamb do we need to backport this to any previous releases, given that they were producing incorrect results?
What I think we should do is file a ticket with some example queries where this bug results in incorrect results. Such queries I think will help us to understand the impact, and depending on that we can figure out if we want to backport this change
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] fix: The limit_pushdown physical optimization rule removes limits in some cases leading to incorrect results [datafusion]
Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #20048:
URL: https://github.com/apache/datafusion/pull/20048#discussion_r2742819576
##########
datafusion/core/tests/physical_optimizer/limit_pushdown.rs:
##########
@@ -343,3 +354,104 @@ fn merges_local_limit_with_global_limit() -> Result<()> {
Ok(())
}
+
+#[test]
+fn preserves_nested_global_limit() -> Result<()> {
+ // If there are multiple limits in an execution plan, they all need to be
+ // preserved in the optimized plan.
+ //
+ // Plan structure:
+ // GlobalLimitExec: skip=1, fetch=1
+ // NestedLoopJoinExec (Left)
+ // EmptyExec (left side)
+ // GlobalLimitExec: skip=2, fetch=1
+ // NestedLoopJoinExec (Right)
+ // EmptyExec (left side)
+ // EmptyExec (right side)
+ let schema = create_schema();
+
+ // Build inner join: NestedLoopJoin(Empty, Empty)
+ let inner_left = empty_exec(Arc::clone(&schema));
+ let inner_right = empty_exec(Arc::clone(&schema));
+ let inner_join = nested_loop_join_exec(inner_left, inner_right, JoinType::Right)?;
+
+ // Add inner limit: GlobalLimitExec: skip=2, fetch=1
+ let inner_limit = global_limit_exec(inner_join, 2, Some(1));
+
+ // Build outer join: NestedLoopJoin(Empty, GlobalLimit)
+ let outer_left = empty_exec(Arc::clone(&schema));
+ let outer_join = nested_loop_join_exec(outer_left, inner_limit, JoinType::Left)?;
+
+ // Add outer limit: GlobalLimitExec: skip=1, fetch=1
+ let outer_limit = global_limit_exec(outer_join, 1, Some(1));
+
+ let initial = get_plan_string(&outer_limit);
+ let expected_initial = [
+ "GlobalLimitExec: skip=1, fetch=1",
+ " NestedLoopJoinExec: join_type=Left",
+ " EmptyExec",
+ " GlobalLimitExec: skip=2, fetch=1",
+ " NestedLoopJoinExec: join_type=Right",
+ " EmptyExec",
+ " EmptyExec",
+ ];
+ assert_eq!(initial, expected_initial);
+
+ let after_optimize =
+ LimitPushdown::new().optimize(outer_limit, &ConfigOptions::new())?;
+ let expected = [
+ "GlobalLimitExec: skip=1, fetch=1",
+ " NestedLoopJoinExec: join_type=Left",
+ " EmptyExec",
+ " GlobalLimitExec: skip=2, fetch=1",
+ " NestedLoopJoinExec: join_type=Right",
+ " EmptyExec",
+ " EmptyExec",
+ ];
+ assert_eq!(get_plan_string(&after_optimize), expected);
+
+ Ok(())
+}
+
+#[test]
+fn preserves_skip_before_sort() -> Result<()> {
+ // If there's a limit with skip before a node that (1) supports fetch but
+ // (2) does not support limit pushdown, that limit should not be removed.
+ //
+ // Plan structure:
+ // GlobalLimitExec: skip=1, fetch=None
+ // SortExec: TopK(fetch=4)
+ // EmptyExec
+ let schema = create_schema();
+
+ let empty = empty_exec(Arc::clone(&schema));
+
+ let ordering = [PhysicalSortExpr {
+ expr: col("c1", &schema)?,
+ options: SortOptions::default(),
+ }];
+ let sort = sort_exec(ordering.into(), empty)
+ .with_fetch(Some(4))
+ .unwrap();
+
+ let outer_limit = global_limit_exec(sort, 1, None);
+
+ let initial = get_plan_string(&outer_limit);
+ let expected_initial = [
+ "GlobalLimitExec: skip=1, fetch=None",
+ " SortExec: TopK(fetch=4), expr=[c1@0 ASC], preserve_partitioning=[false]",
+ " EmptyExec",
+ ];
+ assert_eq!(initial, expected_initial);
+
+ let after_optimize =
+ LimitPushdown::new().optimize(outer_limit, &ConfigOptions::new())?;
+ let expected = [
+ "GlobalLimitExec: skip=1, fetch=3",
Review Comment:
Without the code change in the PR, the actual code looks like
```
"SortExec: TopK(fetch=4), expr=[c1@0 ASC], preserve_partitioning=[false]"
" EmptyExec"
```
Note the offset (aka the `skip`) was dropped
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] fix: The limit_pushdown physical optimization rule removes nested limits in some cases [datafusion]
Posted by "masonh22 (via GitHub)" <gi...@apache.org>.
masonh22 commented on PR #20048:
URL: https://github.com/apache/datafusion/pull/20048#issuecomment-3812345217
I'm looking into the CI failures. I guess I forgot to run the tests before making the PR 🙃
From what I can tell so far, it looks like my change improves/fixes things in the tests it breaks
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] fix: The limit_pushdown physical optimization rule removes limits in some cases leading to incorrect results [datafusion]
Posted by "thinkharderdev (via GitHub)" <gi...@apache.org>.
thinkharderdev merged PR #20048:
URL: https://github.com/apache/datafusion/pull/20048
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] fix: The limit_pushdown physical optimization rule removes nested limits in some cases [datafusion]
Posted by "masonh22 (via GitHub)" <gi...@apache.org>.
masonh22 commented on code in PR #20048:
URL: https://github.com/apache/datafusion/pull/20048#discussion_r2737704680
##########
datafusion/sqllogictest/test_files/limit.slt:
##########
@@ -706,8 +706,8 @@ ON t1.b = t2.b
ORDER BY t1.b desc, c desc, c2 desc
OFFSET 3 LIMIT 2;
----
-3 99 82
-3 99 79
+3 98 79
+3 97 96
Review Comment:
The previous result was wrong. Look at the query directly above this. It is identical except that this query adds `OFFSET 3 LIMIT 2`. None of the rows in the previous test training are in the rows returned by the previous query, and the new training I added is just rows 4-5 in that query.
What was happening here is the inner OFFSET/LIMITs were being removed by the physical optimizer rule.
##########
datafusion/sqllogictest/test_files/union.slt:
##########
@@ -494,22 +494,25 @@ physical_plan
01)CoalescePartitionsExec: fetch=3
02)--UnionExec
03)----ProjectionExec: expr=[count(Int64(1))@0 as cnt]
-04)------AggregateExec: mode=Final, gby=[], aggr=[count(Int64(1))]
-05)--------CoalescePartitionsExec
-06)----------AggregateExec: mode=Partial, gby=[], aggr=[count(Int64(1))]
-07)------------ProjectionExec: expr=[]
-08)--------------AggregateExec: mode=FinalPartitioned, gby=[c1@0 as c1], aggr=[]
-09)----------------RepartitionExec: partitioning=Hash([c1@0], 4), input_partitions=4
-10)------------------AggregateExec: mode=Partial, gby=[c1@0 as c1], aggr=[]
-11)--------------------FilterExec: c13@1 != C2GT5KVyOPZpgKVl110TyZO0NcJ434, projection=[c1@0]
-12)----------------------RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1
-13)------------------------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/testing/data/csv/aggregate_test_100.csv]]}, projection=[c1, c13], file_type=csv, has_header=true
-14)----ProjectionExec: expr=[1 as cnt]
-15)------PlaceholderRowExec
-16)----ProjectionExec: expr=[lead(b.c1,Int64(1)) ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING@1 as cnt]
-17)------BoundedWindowAggExec: wdw=[lead(b.c1,Int64(1)) ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING: Field { "lead(b.c1,Int64(1)) ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING": nullable Int64 }, frame: ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING], mode=[Sorted]
-18)--------ProjectionExec: expr=[1 as c1]
-19)----------PlaceholderRowExec
+04)------GlobalLimitExec: skip=0, fetch=3
Review Comment:
I think this is a better plan than before: `GlobalLimitExec`s are pushed into the union, and before they were not pushed below `CoalescePartitionsExec`.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] fix: The limit_pushdown physical optimization rule removes nested limits in some cases [datafusion]
Posted by "masonh22 (via GitHub)" <gi...@apache.org>.
masonh22 commented on code in PR #20048:
URL: https://github.com/apache/datafusion/pull/20048#discussion_r2737715656
##########
datafusion/sqllogictest/test_files/limit.slt:
##########
@@ -706,8 +706,8 @@ ON t1.b = t2.b
ORDER BY t1.b desc, c desc, c2 desc
OFFSET 3 LIMIT 2;
----
-3 99 82
-3 99 79
+3 98 79
+3 97 96
Review Comment:
Also, when I disable the limit_pushdown rule, I get the new results I added here
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org