Skip to content

fix: WindowTopN keeps the plan when its rewrite breaks a requirement that held - #27772

Open
jayzhan211 wants to merge 2 commits into
apache:mainfrom
jayzhan211:fix/window-topn-keeps-requirements
Open

jayzhan211 wants to merge 2 commits into
apache:mainfrom
jayzhan211:fix/window-topn-keeps-requirements

Conversation

@jayzhan211

@jayzhan211 jayzhan211 commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Which issue does this PR close?

Rationale for this change

A rule list that runs WindowTopN after EnsureRequirements can return rows in the wrong order. For

SELECT pk, rk, rn, id FROM (
  SELECT pk, v, id,
         rank() OVER (PARTITION BY pk ORDER BY v) AS rk,
         row_number() OVER (PARTITION BY pk ORDER BY v) AS rn
  FROM t
) WHERE rn <= 1 ORDER BY pk

EnsureRequirements sorts the window's input by pk ASC NULLS LAST and drops the sort for ORDER BY pk, since the window's output already has that order. WindowTopN then puts a PartitionedTopKExec under the window, which emits pk with NULLS FIRST, so the row with a NULL pk comes first. When an order-preserving repartition and a merge sit above the window, the same rewrite fails planning instead (window_topn.slt:1580 under a local harness that moves the rule).

With this PR, WindowTopN keeps the plan as it was when its rewrite breaks a requirement that held, as every rule after EnsureRequirements must.

This covers positions up to the point where OutputRequirements removes its marker. After that, nothing in the plan declares the ORDER BY, so a WindowTopN placed there still returns rows out of order, as on main.

What changes are included in this PR?

  • WindowTopN::optimize in window_topn.rs: if the plan's order and distribution requirements held before the rewrite and don't after it, the rule returns the plan unchanged. In the default order WindowTopN runs before EnsureRequirements, when the window's sort isn't there yet, so its rewrites stay as they are.

The decision I'd most like reviewed: the check is per plan, not per window, so one rewrite that breaks a requirement drops every WindowTopN rewrite in that plan. I chose it because the operator that relies on the order can be several nodes above the window (in window_topn.slt:1580, a merge above a projection and a repartition), which a check at the window can't see. The two plan walks only run when the rule rewrote something.

What is the testing strategy for this PR?

  • window_topn_after_enforcement_keeps_order_relied_on in core/tests/physical_optimizer/window_topn.rs: a session with WindowTopN after EnsureRequirements runs the query above and returns pk 1, 2, NULL. On main it returns the NULL row first.
  • The sqllogictest suite (with TPC-H) under a local harness, main 73af333 vs this PR: default order 0 → 0 failures and no plan changes; WindowTopN after EnsureRequirements 1 → 0 SanityCheckPlan errors.

Are there any user-facing changes?

No public API change, and no plan change in the default rule order.

For rule lists that run WindowTopN after EnsureRequirements and before OutputRequirements removes its marker: a plan where the rewrite would break an order keeps its window instead of using PartitionedTopKExec, and returns rows in ORDER BY order.

@shihchengwei-lab

Copy link
Copy Markdown

I reproduced an ORDER BY failure on 46cb924 when a custom optimizer pipeline runs WindowTopN immediately after OutputRequirements removes the output ordering marker. The query succeeds but returns pk as NULL, 1, 2. It should return 1, 2, NULL.

To reproduce, keep the data, SQL, and expected rows in the regression test in this PR and change where the helper inserts WindowTopN.

-    let enforcement = position(&rules, EnsureRequirements::new().name());
-    rules.insert(enforcement + 1, window_topn);
+    let removal = rules
+        .iter()
+        .rposition(|rule| rule.name() == "OutputRequirements")
+        .unwrap();
+    rules.insert(removal + 1, window_topn);
cargo test -p datafusion window_topn_after_enforcement_keeps_order_relied_on

I ran the same SQL in a standalone harness. The PR returned the expected order at the original rule position. At the later position, both the base and the PR head returned NULL first. The plan had no sort above PartitionedTopKExec to restore NULLS LAST.

Could we extend this fix and its regression test to cover that later rule position?

AI assisted with source review, test design, and drafting.

@jayzhan211

Copy link
Copy Markdown
Contributor Author

Could we extend this fix and its regression test to cover that later rule position?

Thanks for the repro. I'd like to keep this PR to positions before OutputRequirements removes its marker, and fix the later positions in a separate PR that keeps the marker until the physical planner's final check, with your case as its test. Does that work for you?

Your case reproduces on this branch: with WindowTopN just before the removal, the window is kept and pk comes back 1, 2, NULL; just after it, NULL, 1, 2. Once EnsureRequirements drops the sort for ORDER BY pk, the marker is the only node that declares that order, and the removal drops it (output_requirements.rs). From then on, neither this PR's check nor the planner's final check can see that the query relies on the window's order. Any rule that changes the output order after that point has the same blind spot, so keeping the marker fixes them together. A check in WindowTopN alone would have to treat every change to the output order as a break, which would also block the rewrite for queries without ORDER BY.

@shihchengwei-lab

Copy link
Copy Markdown

A separate PR works for me. Thanks for reproducing it.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants