Skip to content

fix: wrong window values under a LIMIT when the input has more than one partition - #27532

Open
cool9850311 wants to merge 6 commits into
apache:mainfrom
cool9850311:fix-27457-window-limit-partitioned-topk
Open

cool9850311 wants to merge 6 commits into
apache:mainfrom
cool9850311:fix-27457-window-limit-partitioned-topk

Conversation

@cool9850311

@cool9850311 cool9850311 commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Which issue does this PR close?

Rationale for this change

A window function with PARTITION BY returns wrong values under a LIMIT when its input has more than one partition:

SET datafusion.execution.target_partitions = 4;
SET datafusion.execution.batch_size = 1;
SET datafusion.optimizer.repartition_file_scans = false;
CREATE TABLE t1 (a INT, b INT) AS VALUES (5, 1), (0, 1), (0, 2), (0, 3);
CREATE TABLE t2 (a INT, b INT) AS VALUES (5, 2);

SELECT a, b, row_number() OVER (PARTITION BY a ORDER BY b ROWS UNBOUNDED PRECEDING) AS rn
FROM (SELECT * FROM t1 UNION ALL SELECT * FROM t2) LIMIT 3;
-- returns a row (5, 2, 1); (5, 2) has rn = 2 in the full result

LimitPushPastWindows sets the fetch on the SortExec below the window, and a partition-preserving sort with a fetch keeps the globally first fetch rows of its input rather than the first rows of each partition on its own: the partitions of one SortExec share a TopK threshold, and TopKRepartition copies the TopK below the hash repartition, where it keeps the first rows of each input partition. A window reads each partition on its own, and a row missing from the middle of a group changes the value of every later row of that group.

What changes are included in this PR?

LimitPushPastWindows no longer sets the fetch on a sort with more than one output partition, unless the limit comes from a SortPreservingMergeExec whose input is hash-partitioned on keys that each appear in the merge's ordering (after equivalences, e.g. a projection alias) or are constant across partitions. ties_stay_in_one_partition checks this once at the merge.

Rows that tie on the merge's ordering then sit in one input partition of the merge, and that partition reaches it in sort-key order. So a row the window computed a wrong value for sorts behind at least fetch correct rows that the merge emits first, and the merge's own fetch drops it.

What is the testing strategy for this PR?

Nine shapes in window_limits.slt. Six are reproductions, each asserting that every row it returns is a row of the full result -- which rows a LIMIT with no total order returns is up to the partitions' timing -- preceded by an assertion that the limited query returns three rows at all, so the subset check cannot pass on an empty result. The first four returned a wrong row in 19 to 20 of 20 runs on main; the two @jayzhan211 gave returned one in 17 to 19 and in 6 to 19 of 20 runs at an earlier head of this branch. All six return none in 20 runs here. The other three are the plans the guard must not block -- the constant key, the subset hash, and two stacked windows -- pinned with an EXPLAIN that is identical to main.

Ten unit tests in limit_pushdown_past_window.rs, printing the plan on both sides of the rule. Dropping the constant arm, the equivalence normalization, or either call of ties_stay_in_one_partition turns a test red.

Are there any user-facing changes?

The wrong results are fixed. A window under a LIMIT whose input has more than one partition now gets a full sort below it, unless an ORDER BY above it contains every column the window's input is hash-partitioned on (the PARTITION BY columns, a subset of them, or columns a filter fixes to one value). In that case the plan is the same as on main. No API change.

🤖 Generated with Claude Code

@github-actions github-actions Bot added optimizer Optimizer rules sqllogictest SQL Logic Tests (.slt) labels Nov 17, 2026
@cool9850311
cool9850311 marked this pull request as ready for review November 22, 2026 12:25
@cool9850311
cool9850311 force-pushed the fix-27457-window-limit-partitioned-topk branch 2 times, most recently from 9abfef7 to 4c3569b Compare November 22, 2026 12:36

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

@cool9850311 thanks for switching to the expression comparison: both repros are fixed and covered. The two inline comments are about plans where the guard drops a TopK that main already gets right. Once they're in, could you reword the "stricter than correctness requires" paragraph in the description? It says stacked windows pass when both are covered, but at this head they never do.

Comment on lines +223 to +225
if node.output_partitioning().partition_count() > 1
&& !(partitions_separated && keeps_partitions_whole(node, narrowest_partition_by))
{

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.

@cool9850311 the window already requires KeyPartitioned(PARTITION BY), so every window partition is whole in one stream. keeps_partitions_whole checks a narrower version of that rule, and it drops the TopK on valid plans where main keeps it: a constant key (the sort drops a, so the hash isn't a prefix of the sort anymore), and a subset hash:

SET datafusion.execution.target_partitions = 4;
SET datafusion.optimizer.repartition_file_scans = false;
CREATE TABLE t1 (a INT, b INT, c INT) AS VALUES (1,1,1),(1,2,2),(2,1,3);
CREATE TABLE t2 (a INT, b INT, c INT) AS VALUES (1,1,6);
EXPLAIN SELECT a, b, c, row_number() OVER (PARTITION BY a, b ORDER BY c ROWS UNBOUNDED PRECEDING) rn
FROM (SELECT * FROM t1 UNION ALL SELECT * FROM t2) WHERE a = 1 ORDER BY a, b LIMIT 3;
EXPLAIN SELECT b, m, row_number() OVER (PARTITION BY m, b ORDER BY m ROWS UNBOUNDED PRECEDING) rn
FROM (SELECT b, max(c) m FROM (SELECT * FROM t1 UNION ALL SELECT * FROM t2) GROUP BY b) ORDER BY m, b LIMIT 3;

The three unit tests behind this check (round robin, hash on b, hash on a, b) build plans that SanityCheckPlan rejects. The constant filter in merge_ordering only makes the check stricter, and no test fails without it. Could you drop keeps_partitions_whole, partition_by_width, narrowest_partition_by, the constant filter and those three tests, and add the two queries above as EXPLAIN tests? With that and the window carry, I get the unit tests, window_limits.slt and clippy green, and a randomized subset check returns 0 wrong rows out of 180 per shape.

Suggested change
if node.output_partitioning().partition_count() > 1
&& !(partitions_separated && keeps_partitions_whole(node, narrowest_partition_by))
{
if node.output_partitioning().partition_count() > 1 && !partitions_separated {
The rest of the change, besides deleting the two functions
-    /// The narrowest `PARTITION BY` over the windows crossed so far.
-    pub narrowest_partition_by: usize,
@@
-        self.narrowest_partition_by = usize::MAX;
@@
                 ctx.partitions_separated &= separates_partitions(&node, &ctx);
-                ctx.narrowest_partition_by =
-                    ctx.narrowest_partition_by.min(partition_by_width(&node));
@@
         partitions_separated,
-        narrowest_partition_by,
         ..
@@
 fn merge_ordering(merge: &SortPreservingMergeExec) -> Vec<Arc<dyn PhysicalExpr>> {
-    let input = merge.input().equivalence_properties();
     merge
         .expr()
         .iter()
-        .filter(|sort_expr| input.is_expr_constant(&sort_expr.expr).is_none())
         .map(|sort_expr| Arc::clone(&sort_expr.expr))
         .collect()
 }

Comment on lines +323 to +327
} else if node.schema() == child.schema() {
Some(exprs)
} else {
None
};

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.

@cool9850311 the carry stops at every window, because a window's schema differs from its input's. So two stacked windows always lose the fetch, even when the ORDER BY covers both, and main keeps TopK(fetch=3) there:

SET datafusion.execution.target_partitions = 4;
SET datafusion.optimizer.repartition_file_scans = false;
CREATE TABLE t1 (a INT, b INT, c INT) AS VALUES (1,1,1),(1,2,2),(2,1,3);
CREATE TABLE t2 (a INT, b INT, c INT) AS VALUES (1,1,6);
EXPLAIN SELECT a, b, c,
  row_number() OVER (PARTITION BY a ORDER BY b ROWS UNBOUNDED PRECEDING) r1,
  row_number() OVER (PARTITION BY a ORDER BY b, c ROWS UNBOUNDED PRECEDING) r2
FROM (SELECT * FROM t1 UNION ALL SELECT * FROM t2) ORDER BY a LIMIT 3;

A window appends its columns after its input's, so the ordering can pass through it. Could you add this, plus the query above as an EXPLAIN test? It also needs use datafusion_physical_expr::utils::collect_columns;.

Suggested change
} else if node.schema() == child.schema() {
Some(exprs)
} else {
None
};
} else if node.schema() == child.schema() {
Some(exprs)
} else if node.is::<BoundedWindowAggExec>() {
// A window appends its columns after its input's, so an expression
// over input columns means the same on both sides.
let input_columns = child.schema().fields().len();
exprs
.into_iter()
.map(|expr| {
collect_columns(&expr)
.iter()
.all(|column| column.index() < input_columns)
.then_some(expr)
})
.collect()
} else {
None
};

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks for catching that, done fixing.

@cool9850311
cool9850311 force-pushed the fix-27457-window-limit-partitioned-topk branch from ce7b183 to d14b140 Compare November 24, 2026 05:31

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

@cool9850311 thanks for applying both changes so quickly. The inline comment is the one remaining change, and it's mostly a correction of what I asked for on the issue. Once it's in, the "What changes" section can describe the single check at the merge, and the "stricter than correctness requires" paragraph can go.

Comment on lines +248 to +251
/// Whether the ordering in hand sorts `node`'s rows into the groups its windows
/// read: every `PARTITION BY` expression has to be one of the ordering's own. A
/// window with no `PARTITION BY` reads one group that no ordering separates.
fn separates_partitions(node: &Arc<dyn ExecutionPlan>, ctx: &TraverseState) -> 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.

@cool9850311 thanks for the quick turnaround. I need to correct my own earlier ask: requiring every PARTITION BY expression in the merge's ordering is stricter than the argument needs, and it drops TopK(fetch=3) on two plans main gets right (0 wrong rows in 240 randomized runs). Those plans are stacked windows PARTITION BY a over PARTITION BY a, b under ORDER BY a, and WHERE a = 1 … PARTITION BY a, b … ORDER BY b. The argument only needs every row that ties with r on the merge's ordering to sit in r's merge-input partition, and that holds when every hash key of the merge's input is in the ordering or is a constant. Checked once at the merge, that also removes carry_down, separates_partitions and merge_ordering (−85/+37). With it, the unit tests, window_limits.slt (including all six repros) and clippy pass, and the randomized subset check finds 0 wrong rows on every shape. Could you apply it and add the two EXPLAIN tests below? Both fail at this head.

The change
-use datafusion_physical_expr::PhysicalExpr;
-use datafusion_physical_expr::utils::collect_columns;
-use datafusion_physical_plan::projection::ProjectionExec;
+use datafusion_physical_expr::{AcrossPartitions, physical_exprs_contains};
 use datafusion_physical_plan::sorts::sort::SortExec;
 use datafusion_physical_plan::sorts::sort_preserving_merge::SortPreservingMergeExec;
-use datafusion_physical_plan::windows::BoundedWindowAggExec;
 use datafusion_physical_plan::{
-    ExecutionPlan, ExecutionPlanProperties, LimitBehavior, WindowLookahead,
+    ExecutionPlan, ExecutionPlanProperties, LimitBehavior, Partitioning, WindowLookahead,
 };
@@ struct TraverseState
-    /// The ordering of the merge the limit came from, in the expression space of
-    /// the node being visited.
-    pub merge_exprs: Option<Vec<Arc<dyn PhysicalExpr>>>,
-    /// Whether it separates the groups of every window crossed so far.
-    pub partitions_separated: bool,
+    /// Whether rows that tie on the ordering of the merge the limit came from
+    /// share one of its input partitions.
+    pub ties_in_one_partition: bool,
@@ fn reset_limit
-    pub fn reset_limit(
-        &mut self,
-        limit: Option<usize>,
-        merge_exprs: Option<Vec<Arc<dyn PhysicalExpr>>>,
-    ) {
+    pub fn reset_limit(&mut self, limit: Option<usize>, ties_in_one_partition: bool) {
         self.limit = limit;
         self.lookahead = 0;
         self.phase = Phase::FindOrGrow;
-        self.partitions_separated = merge_exprs.is_some();
-        self.merge_exprs = merge_exprs;
+        self.ties_in_one_partition = ties_in_one_partition;
@@ fn optimize
                 if !grow_limit(lookahead, &mut ctx) {
                     return reset(node, &mut ctx);
                 }
-                ctx.partitions_separated &= separates_partitions(&node, &ctx);
-                carry_down(&node, &mut ctx);
                 return Ok(Transformed::no(node));
@@
             if node.output_ordering().is_none() {
-                ctx.merge_exprs = None;
-                ctx.partitions_separated = false;
+                ctx.ties_in_one_partition = false;
             }
-            carry_down(&node, &mut ctx);
@@ fn apply_limit
-        partitions_separated,
+        ties_in_one_partition,
@@
-        ctx.reset_limit(fetch.or_else(|| node.fetch()), Some(merge_ordering(merge)));
+        ctx.reset_limit(
+            fetch.or_else(|| node.fetch()),
+            ties_stay_in_one_partition(merge),
+        );
@@
-    if node.output_partitioning().partition_count() > 1 && !partitions_separated {
+    if node.output_partitioning().partition_count() > 1 && !ties_in_one_partition {
@@ fn get_limit
-        ctx.reset_limit(limit.input_rows(), None);
+        ctx.reset_limit(limit.input_rows(), false);
@@
-        ctx.reset_limit(merge.fetch(), Some(merge_ordering(merge)));
+        ctx.reset_limit(merge.fetch(), ties_stay_in_one_partition(merge));

Then replace merge_ordering, separates_partitions and carry_down with:

/// Whether rows that tie on `merge`'s ordering always share one of its input
/// partitions. A fetch on a sort below that keeps several partitions then drops
/// only rows behind at least `fetch` rows that reach the merge before them.
fn ties_stay_in_one_partition(merge: &SortPreservingMergeExec) -> bool {
    let input = merge.input();
    let Partitioning::Hash(keys, _) = input.output_partitioning() else {
        return false;
    };
    let eq_properties = input.equivalence_properties();
    let eq_group = eq_properties.eq_group();
    let ordering = merge
        .expr()
        .iter()
        .map(|sort_expr| eq_group.normalize_expr(Arc::clone(&sort_expr.expr)))
        .collect::<Vec<_>>();
    keys.iter().all(|key| {
        physical_exprs_contains(&ordering, &eq_group.normalize_expr(Arc::clone(key)))
            || matches!(
                eq_properties.is_expr_constant(key),
                Some(AcrossPartitions::Uniform(_))
            )
    })
}

The doc comments on a_merge_ordered_by_an_alias_above_a_projection_takes_the_fetch and a_merge_over_stacked_windows_takes_the_fetch describe the carry and would need a reword.

Two EXPLAIN tests for window_limits.slt, before the final RESETs (both keep the TopK, as on main)
query TT
EXPLAIN
SELECT a, b, c,
  row_number() OVER (PARTITION BY a ORDER BY b, c ROWS UNBOUNDED PRECEDING) AS r1,
  row_number() OVER (PARTITION BY a, b ORDER BY c ROWS UNBOUNDED PRECEDING) AS r2
FROM (SELECT * FROM w27457_covered UNION ALL SELECT * FROM w27457_covered_late)
ORDER BY a LIMIT 3;
----

query TT
EXPLAIN
SELECT a, b, c, row_number() OVER (PARTITION BY a, b ORDER BY c ROWS UNBOUNDED PRECEDING) AS rn
FROM (SELECT * FROM w27457_covered UNION ALL SELECT * FROM w27457_covered_late)
WHERE a = 1 ORDER BY b LIMIT 3;
----

--complete fills in plans with SortExec: TopK(fetch=3) below the windows.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Took me a while to understand it, applied.

cool9850311 and others added 5 commits November 28, 2026 20:03
A window function with `PARTITION BY` returned wrong values under a `LIMIT`
when its input had more than one partition. `LimitPushPastWindows` set the
fetch on the partition-preserving `SortExec` below the window, and such a sort
keeps the globally first `fetch` rows of its input rather than the first rows
of each partition on its own: the partitions of one `SortExec` share a TopK
threshold, so one partition drops a row another partition's threshold
rejected, and `TopKRepartition` copies the TopK below the hash repartition,
where it keeps the first rows of each input partition. Both are what a merge
or coalesce with a fetch wants, and neither is what a window wants, because a
window reads each partition on its own and a row missing from the middle of a
group changes the value of every later row of that group.

`apply_limit` now sets the fetch only on a node with one output partition.
`SortPreservingMergeExec` always reports one, so the merge path is unchanged,
and with no fetch on the sort `TopKRepartition` has no TopK to copy.

Four shapes returned wrong values and now do not: a bare `LIMIT` with and
without `TopKRepartition`, a merge that orders fewer columns than the window
partitions by, and the same with a constant column leading the merge's
ordering. Each has a reproduction in `window_limits.slt` asserting that every
row it returns is a row of the full result, with the row count asserted first
so the check cannot pass on an empty result.

Six plans in the test suite lose their TopK and fall back to a full sort. All
six have a merge above the window that orders its partitions apart, which
makes them sound as they stand, and one of them is the shape
`datafusion/core/benches/topk_repartition.rs` measures, where the full sort
costs 16x at `LIMIT 10`. The next commit narrows the check to leave those
plans alone.

Closes apache#27457

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The previous commit took the fetch off every sort with more than one output
partition below a window. That is more than correctness needs. A merge above
the window that takes the first `fetch` rows of its output makes the globally
first rows a bound on what the window reads too: a row the window computed a
wrong value for lost to `fetch` rows that all reach the merge before it, so it
sits past the merge's own fetch and is never emitted. All six plans the
previous commit changed are of that shape, including the one
`datafusion/core/benches/topk_repartition.rs` measures.

`LimitPushPastWindows` now records how many of the ordering columns of the
merge a limit came from actually order its rows -- a column that is constant in
the merge's input orders nothing, and dropping it leaves an equivalent ordering
-- and how many `PARTITION BY` columns the windows it crosses need ordered
apart. It rewrites a node with more than one output partition only when the
first covers the second, when the node is hashed on the columns its own
ordering starts with, and when nothing between the limit and the node dropped
the ordering the rank was measured on. A limit from a `GlobalLimitExec` or a
`CoalescePartitionsExec` orders nothing and never qualifies, which is what both
shapes in the issue reduce to.

Comparing counts is enough for the first of those three because no second sort
can sit between the limit and the node being rewritten -- `SortExec` reports
`LimitBehavior::Stops` and ends the walk -- so that node orders everything
above it, and the merge's ordering is therefore equivalent to one of its
prefixes, which starts with the window's `PARTITION BY`. The other two are
guaranteed earlier in the pipeline by `EnsureRequirements`; they are checked
here so that the rule does not depend on another rule having run first, and
they change no decision across the `.slt` suite.

The six plans keep their fetch, so only the four shapes that returned wrong
values change, and `topk_repartition.rs` is back to what it measures on `main`.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The previous commit counted: how many of the ordering columns of the merge a
limit came from order its rows, against how many `PARTITION BY` columns the
windows it crosses need ordered apart. @jayzhan211 pointed out on the issue
that a count does not settle it, and gave two shapes that still returned wrong
values. `a, a AS a2` orders by `a` twice, and `a, floor(d)` leaves rows whose
`d` differs tied, so neither separates the groups of a window partitioned by
`a, d` although both have an expression per `PARTITION BY` column. Both
returned a row whose `row_number` is 1 where the full result says 2.

`LimitPushPastWindows` now carries the merge's ordering itself down the plan,
and crossing a window counts as bounded only when every one of that window's
`PARTITION BY` expressions is one of the ordering's own. The bound on the
hash's width becomes the narrowest `PARTITION BY` crossed rather than the
widest, since a hash wider than a window's `PARTITION BY` splits one of its
groups across buckets. The rule still does not try to tell which other
expressions over a key preserve its grouping, so one that is not the key
itself blocks the pushdown.

Carrying the ordering down means rewriting it into the expression space of
each node below the merge, because a projection moves and renames columns:
`ProjectionExprs::unproject_expr` does that, a node that leaves the schema
alone needs nothing, and anything else ends the carry. The rewrite is
load-bearing rather than tidiness -- the query
`datafusion/core/benches/topk_repartition.rs` measures plans a
`ProjectionExec` between the merge and the window, so without it that plan
loses its TopK and the rule falls back to the narrow guard of the first
commit. `EXPLAIN` of that query is identical to `main`.

Both shapes are reproduced in `window_limits.slt` with the row count asserted
first, as the four before them are. They returned a wrong row in 17 to 19 and
in 6 to 19 of 20 runs before this commit and in none of 20 after; the second
one's rate is up to the partitions' timing, so the unit tests rather than the
`.slt` are what pin these two deterministically. Replacing the expression
comparison with a count turns those two unit tests red and no others, and
dropping the projection branch of the rewrite turns only the test over a
projection red.

The twelve unit tests this branch adds now print the plan on both sides of the
rule, in the shape `OptimizationTest` in the core tests prints, so that a test
claiming the rule left a plan alone shows it as two identical halves. The
tests already in the file are unchanged.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The guard also asked, on its own, that the node be hashed on a prefix of its
sort key no wider than the narrowest `PARTITION BY`, and dropped the ordering
expressions that are constant in the merge's input. A window already requires
`KeyPartitioned(PARTITION BY)`, so every group it reads is whole within one of
its input's partitions; the narrower check only cost plans a TopK that `main`
keeps -- a constant key the sort drops, and a hash on part of the key. The
three tests behind it built plans `SanityCheckPlan` rejects.

Carry the merge's ordering through a window too: a window appends its columns
after its input's, so an expression over input columns means the same on both
sides, and two stacked windows keep the fetch when the ordering covers both.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The guard asked that the merge's ordering contain every `PARTITION BY`
expression of every window it crossed. The argument needs less: a row the
window got wrong lost to `fetch` rows that all reach the merge before it, and
the only ones whose turn the ordering does not already settle are those tied on
it, so it is enough that rows tied on the ordering share one of the merge
input's partitions. That holds when the ordering determines every hash key --
each key is one of its expressions, or is constant with the same value in every
partition. A hash narrower than the `PARTITION BY` is legal, since a window's
`KeyPartitioned` is satisfied by a subset of its keys, so asking for the wider
cover only cost plans a TopK that `main` keeps: a subset hash under stacked
windows, and a key a filter fixes to one value.

Read the hash keys off the merge's own input instead. The ordering and the
partitioning are written in the same schema there, so the ordering no longer
has to be carried down through projections and windows, and `merge_ordering`,
`separates_partitions` and `carry_down` go with it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@cool9850311
cool9850311 force-pushed the fix-27457-window-limit-partitioned-topk branch from d14b140 to 4e9e325 Compare November 28, 2026 12:10

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

@cool9850311 thanks for applying it. The code is ready from my side: the unit tests, clippy, rustdoc and the full sqllogictest suite pass at this head, and a randomized subset check over seven more shapes (a lookahead frame, lead, OFFSET, NULL keys, DESC, ORDER BY a, rn, a running count) returned 0 wrong rows in 8 runs of each.

One ask before merge: the description still explains the previous mechanism (every PARTITION BY in the merge's ordering, the carry through projections and windows, the "stricter than correctness requires" paragraph), so a maintainer reading it will look for code that is no longer there. Could you replace "What changes", the user-facing line and the last testing paragraph with something like the text below?

Suggested text for those three sections

What changes are included in this PR?

LimitPushPastWindows no longer sets the fetch on a sort with more than one output partition, unless the limit comes from a SortPreservingMergeExec whose input is hash-partitioned on keys that each appear in the merge's ordering (after equivalences, e.g. a projection alias) or are constant across partitions. ties_stay_in_one_partition checks this once at the merge.

Rows that tie on the merge's ordering then sit in one input partition of the merge, and that partition reaches it in sort-key order. So a row the window computed a wrong value for sorts behind at least fetch correct rows that the merge emits first, and the merge's own fetch drops it.

Are there any user-facing changes?

The wrong results are fixed. A window under a LIMIT whose input has more than one partition now gets a full sort below it, unless an ORDER BY above it contains every column the window's input is hash-partitioned on (the PARTITION BY columns, a subset of them, or columns a filter fixes to one value). In that case the plan is the same as on main. No API change.

Testing (last paragraph)

Ten unit tests in limit_pushdown_past_window.rs, printing the plan on both sides of the rule. Dropping the constant arm, the equivalence normalization, or either call of ties_stay_in_one_partition turns a test red.

Comment on lines +117 to +122
// The ordering only holds further down while the nodes in between
// keep their input's order.
if node.output_ordering().is_none() {
ctx.ties_in_one_partition = false;
}

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.

Optional cleanup: this check can no longer change the result. ties_in_one_partition is now computed from the merge's own input and every SortPreservingMergeExec below recomputes it, and the only node the walk crosses that drops the ordering, CoalescePartitionsExec, also leaves the merge's input without a hash partitioning. Deleting it lets an_unordered_node_under_the_merge_blocks_the_pushdown cover the non-hash return false in ties_stay_in_one_partition: flipping that to true turns it red, while at this head no test notices. With the doc comment change below, the unit tests, the full sqllogictest suite and clippy pass.

Suggested change
// The ordering only holds further down while the nodes in between
// keep their input's order.
if node.output_ordering().is_none() {
ctx.ties_in_one_partition = false;
}
-    /// A `CoalescePartitionsExec` between the merge and the window does not keep
-    /// its input's order, so the merge's ordering says nothing below it.
+    /// A `CoalescePartitionsExec` between the merge and the window leaves the
+    /// merge's input without a hash partitioning, so no ordering covers it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done.

`ties_in_one_partition` is computed from the merge's own input and every
`SortPreservingMergeExec` below recomputes it. The only node the walk
crosses that drops the ordering, `CoalescePartitionsExec`, also leaves the
merge's input without a hash partitioning, so `ties_stay_in_one_partition`
already returns false there.

Deleting it lets `an_unordered_node_under_the_merge_blocks_the_pushdown`
cover the non-hash `return false`: flipping that to `true` now turns the
test red, while before the deletion no test noticed.

Co-Authored-By: Claude Opus 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 sqllogictest SQL Logic Tests (.slt)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Window function returns wrong values under LIMIT when its input has more than one partition

2 participants