Skip to content

Commit 2860ada

Browse files
authored
fix: The limit_pushdown physical optimization rule removes limits in some cases leading to incorrect results (#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. --> Bug 1: 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. Bug 2: When we're pushing down a limit with a skip/offset and no fetch/limit and we run into a node that supports fetch, we set `GlobalRequirements::satisfied` to true. This is wrong: the limit is not satisfied because fetch doesn't support skip/offset. Instead, we should set `GlobalRequirements::satisfied` to true if skip/offset is 0. ## 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. -->
1 parent cad3865 commit 2860ada

4 files changed

Lines changed: 136 additions & 20 deletions

File tree

datafusion/core/tests/physical_optimizer/limit_pushdown.rs

Lines changed: 113 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,14 +26,15 @@ use arrow::compute::SortOptions;
2626
use arrow::datatypes::{DataType, Field, Schema, SchemaRef};
2727
use datafusion_common::config::ConfigOptions;
2828
use datafusion_common::error::Result;
29-
use datafusion_expr::Operator;
29+
use datafusion_expr::{JoinType, Operator};
3030
use datafusion_physical_expr::Partitioning;
3131
use datafusion_physical_expr::expressions::{BinaryExpr, col, lit};
3232
use datafusion_physical_expr_common::sort_expr::{LexOrdering, PhysicalSortExpr};
3333
use datafusion_physical_optimizer::PhysicalOptimizerRule;
3434
use datafusion_physical_optimizer::limit_pushdown::LimitPushdown;
3535
use datafusion_physical_plan::empty::EmptyExec;
3636
use datafusion_physical_plan::filter::FilterExec;
37+
use datafusion_physical_plan::joins::NestedLoopJoinExec;
3738
use datafusion_physical_plan::projection::ProjectionExec;
3839
use datafusion_physical_plan::repartition::RepartitionExec;
3940
use datafusion_physical_plan::{ExecutionPlan, get_plan_string};
@@ -87,6 +88,16 @@ fn empty_exec(schema: SchemaRef) -> Arc<dyn ExecutionPlan> {
8788
Arc::new(EmptyExec::new(schema))
8889
}
8990

91+
fn nested_loop_join_exec(
92+
left: Arc<dyn ExecutionPlan>,
93+
right: Arc<dyn ExecutionPlan>,
94+
join_type: JoinType,
95+
) -> Result<Arc<dyn ExecutionPlan>> {
96+
Ok(Arc::new(NestedLoopJoinExec::try_new(
97+
left, right, None, &join_type, None,
98+
)?))
99+
}
100+
90101
#[test]
91102
fn transforms_streaming_table_exec_into_fetching_version_when_skip_is_zero() -> Result<()>
92103
{
@@ -343,3 +354,104 @@ fn merges_local_limit_with_global_limit() -> Result<()> {
343354

344355
Ok(())
345356
}
357+
358+
#[test]
359+
fn preserves_nested_global_limit() -> Result<()> {
360+
// If there are multiple limits in an execution plan, they all need to be
361+
// preserved in the optimized plan.
362+
//
363+
// Plan structure:
364+
// GlobalLimitExec: skip=1, fetch=1
365+
// NestedLoopJoinExec (Left)
366+
// EmptyExec (left side)
367+
// GlobalLimitExec: skip=2, fetch=1
368+
// NestedLoopJoinExec (Right)
369+
// EmptyExec (left side)
370+
// EmptyExec (right side)
371+
let schema = create_schema();
372+
373+
// Build inner join: NestedLoopJoin(Empty, Empty)
374+
let inner_left = empty_exec(Arc::clone(&schema));
375+
let inner_right = empty_exec(Arc::clone(&schema));
376+
let inner_join = nested_loop_join_exec(inner_left, inner_right, JoinType::Right)?;
377+
378+
// Add inner limit: GlobalLimitExec: skip=2, fetch=1
379+
let inner_limit = global_limit_exec(inner_join, 2, Some(1));
380+
381+
// Build outer join: NestedLoopJoin(Empty, GlobalLimit)
382+
let outer_left = empty_exec(Arc::clone(&schema));
383+
let outer_join = nested_loop_join_exec(outer_left, inner_limit, JoinType::Left)?;
384+
385+
// Add outer limit: GlobalLimitExec: skip=1, fetch=1
386+
let outer_limit = global_limit_exec(outer_join, 1, Some(1));
387+
388+
let initial = get_plan_string(&outer_limit);
389+
let expected_initial = [
390+
"GlobalLimitExec: skip=1, fetch=1",
391+
" NestedLoopJoinExec: join_type=Left",
392+
" EmptyExec",
393+
" GlobalLimitExec: skip=2, fetch=1",
394+
" NestedLoopJoinExec: join_type=Right",
395+
" EmptyExec",
396+
" EmptyExec",
397+
];
398+
assert_eq!(initial, expected_initial);
399+
400+
let after_optimize =
401+
LimitPushdown::new().optimize(outer_limit, &ConfigOptions::new())?;
402+
let expected = [
403+
"GlobalLimitExec: skip=1, fetch=1",
404+
" NestedLoopJoinExec: join_type=Left",
405+
" EmptyExec",
406+
" GlobalLimitExec: skip=2, fetch=1",
407+
" NestedLoopJoinExec: join_type=Right",
408+
" EmptyExec",
409+
" EmptyExec",
410+
];
411+
assert_eq!(get_plan_string(&after_optimize), expected);
412+
413+
Ok(())
414+
}
415+
416+
#[test]
417+
fn preserves_skip_before_sort() -> Result<()> {
418+
// If there's a limit with skip before a node that (1) supports fetch but
419+
// (2) does not support limit pushdown, that limit should not be removed.
420+
//
421+
// Plan structure:
422+
// GlobalLimitExec: skip=1, fetch=None
423+
// SortExec: TopK(fetch=4)
424+
// EmptyExec
425+
let schema = create_schema();
426+
427+
let empty = empty_exec(Arc::clone(&schema));
428+
429+
let ordering = [PhysicalSortExpr {
430+
expr: col("c1", &schema)?,
431+
options: SortOptions::default(),
432+
}];
433+
let sort = sort_exec(ordering.into(), empty)
434+
.with_fetch(Some(4))
435+
.unwrap();
436+
437+
let outer_limit = global_limit_exec(sort, 1, None);
438+
439+
let initial = get_plan_string(&outer_limit);
440+
let expected_initial = [
441+
"GlobalLimitExec: skip=1, fetch=None",
442+
" SortExec: TopK(fetch=4), expr=[c1@0 ASC], preserve_partitioning=[false]",
443+
" EmptyExec",
444+
];
445+
assert_eq!(initial, expected_initial);
446+
447+
let after_optimize =
448+
LimitPushdown::new().optimize(outer_limit, &ConfigOptions::new())?;
449+
let expected = [
450+
"GlobalLimitExec: skip=1, fetch=3",
451+
" SortExec: TopK(fetch=4), expr=[c1@0 ASC], preserve_partitioning=[false]",
452+
" EmptyExec",
453+
];
454+
assert_eq!(get_plan_string(&after_optimize), expected);
455+
456+
Ok(())
457+
}

datafusion/physical-optimizer/src/limit_pushdown.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,7 @@ pub fn pushdown_limit_helper(
155155
global_state.skip = skip;
156156
global_state.fetch = fetch;
157157
global_state.preserve_order = limit_exec.preserve_order();
158+
global_state.satisfied = false;
158159

159160
// Now the global state has the most recent information, we can remove
160161
// the `LimitExec` plan. We will decide later if we should add it again
@@ -172,7 +173,7 @@ pub fn pushdown_limit_helper(
172173
// If we have a non-limit operator with fetch capability, update global
173174
// state as necessary:
174175
if pushdown_plan.fetch().is_some() {
175-
if global_state.fetch.is_none() {
176+
if global_state.skip == 0 {
176177
global_state.satisfied = true;
177178
}
178179
(global_state.skip, global_state.fetch) = combine_limit(

datafusion/sqllogictest/test_files/limit.slt

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -706,8 +706,8 @@ ON t1.b = t2.b
706706
ORDER BY t1.b desc, c desc, c2 desc
707707
OFFSET 3 LIMIT 2;
708708
----
709-
3 99 82
710-
3 99 79
709+
3 98 79
710+
3 97 96
711711

712712
statement ok
713713
drop table ordered_table;

datafusion/sqllogictest/test_files/union.slt

Lines changed: 19 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -494,22 +494,25 @@ physical_plan
494494
01)CoalescePartitionsExec: fetch=3
495495
02)--UnionExec
496496
03)----ProjectionExec: expr=[count(Int64(1))@0 as cnt]
497-
04)------AggregateExec: mode=Final, gby=[], aggr=[count(Int64(1))]
498-
05)--------CoalescePartitionsExec
499-
06)----------AggregateExec: mode=Partial, gby=[], aggr=[count(Int64(1))]
500-
07)------------ProjectionExec: expr=[]
501-
08)--------------AggregateExec: mode=FinalPartitioned, gby=[c1@0 as c1], aggr=[]
502-
09)----------------RepartitionExec: partitioning=Hash([c1@0], 4), input_partitions=4
503-
10)------------------AggregateExec: mode=Partial, gby=[c1@0 as c1], aggr=[]
504-
11)--------------------FilterExec: c13@1 != C2GT5KVyOPZpgKVl110TyZO0NcJ434, projection=[c1@0]
505-
12)----------------------RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1
506-
13)------------------------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/testing/data/csv/aggregate_test_100.csv]]}, projection=[c1, c13], file_type=csv, has_header=true
507-
14)----ProjectionExec: expr=[1 as cnt]
508-
15)------PlaceholderRowExec
509-
16)----ProjectionExec: expr=[lead(b.c1,Int64(1)) ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING@1 as cnt]
510-
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]
511-
18)--------ProjectionExec: expr=[1 as c1]
512-
19)----------PlaceholderRowExec
497+
04)------GlobalLimitExec: skip=0, fetch=3
498+
05)--------AggregateExec: mode=Final, gby=[], aggr=[count(Int64(1))]
499+
06)----------CoalescePartitionsExec
500+
07)------------AggregateExec: mode=Partial, gby=[], aggr=[count(Int64(1))]
501+
08)--------------ProjectionExec: expr=[]
502+
09)----------------AggregateExec: mode=FinalPartitioned, gby=[c1@0 as c1], aggr=[]
503+
10)------------------RepartitionExec: partitioning=Hash([c1@0], 4), input_partitions=4
504+
11)--------------------AggregateExec: mode=Partial, gby=[c1@0 as c1], aggr=[]
505+
12)----------------------FilterExec: c13@1 != C2GT5KVyOPZpgKVl110TyZO0NcJ434, projection=[c1@0]
506+
13)------------------------RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1
507+
14)--------------------------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/testing/data/csv/aggregate_test_100.csv]]}, projection=[c1, c13], file_type=csv, has_header=true
508+
15)----ProjectionExec: expr=[1 as cnt]
509+
16)------GlobalLimitExec: skip=0, fetch=3
510+
17)--------PlaceholderRowExec
511+
18)----ProjectionExec: expr=[lead(b.c1,Int64(1)) ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING@1 as cnt]
512+
19)------GlobalLimitExec: skip=0, fetch=3
513+
20)--------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]
514+
21)----------ProjectionExec: expr=[1 as c1]
515+
22)------------PlaceholderRowExec
513516

514517

515518
########

0 commit comments

Comments
 (0)