Skip to content

fix: only push filters on partition-by columns below WINDOW node (#24020) - #24050

Merged
mergify[bot] merged 3 commits into
matrixorigin:mainfrom
ck89119:issue-24020
Apr 3, 2026
Merged

mergify[bot] merged 3 commits into
matrixorigin:mainfrom
ck89119:issue-24020

Conversation

@ck89119

@ck89119 ck89119 commented Apr 3, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • Bug

Which issue(s) does this PR fix:

Fixes #24020

What this PR does / why we need it:

Previously, pushdownFilters for Node_WINDOW pushed any filter not referencing the window tag below the WINDOW node. This is incorrect because filtering on non-partition-by columns changes the window function's input rows, producing wrong ROW_NUMBER()/RANK()/etc. results.

Root cause: The outer filter INDUSTRY_NAME='Consumer Discretionary' was pushed below the WINDOW node with ROW_NUMBER() OVER (PARTITION BY STOCK_CODE ...), changing the partition contents and thus the row numbering.

Fix: Only push filters whose column references are a subset of the PARTITION BY columns. Other non-window-tag filters stay above the WINDOW node.

Changes

  • pkg/sql/plan/pushdown.go: Collect partition-by column refs; classify filters into three categories (window-tag / partition-by-only / other)
  • pkg/sql/plan/pushdown_test.go: Add TestWindowNonPartitionFilterNotPushedDown

…rixorigin#24020)

Previously, any filter not referencing the window tag was pushed below
the WINDOW node. This is incorrect because filtering on non-partition-by
columns changes the window function's input rows, producing wrong
ROW_NUMBER()/RANK()/etc. results.

Now only filters whose column references are a subset of the PARTITION BY
columns are pushed down. Other non-window-tag filters stay above the
WINDOW node.
@qodo-code-review

Copy link
Copy Markdown

Review Summary by Qodo

Fix filter pushdown for WINDOW nodes to only push partition-by column filters

🐞 Bug fix

Grey Divider

Walkthroughs

Description
• Fix incorrect filter pushdown below WINDOW nodes that changed partition contents
• Only push filters referencing partition-by columns below WINDOW node
• Filters on non-partition-by columns now stay above WINDOW node
• Add comprehensive test for non-partition-by filter behavior
Diagram
flowchart LR
  Filter["Filter on non-partition-by column"]
  Window["WINDOW node with PARTITION BY"]
  Child["Child node"]
  
  Filter -->|Previously pushed down incorrectly| Window
  Filter -->|Now stays above| Window
  Window -->|Only partition-by filters pushed| Child
Loading

Grey Divider

File Changes

1. pkg/sql/plan/pushdown.go 🐞 Bug fix +51/-4

Implement partition-by column filter classification logic

• Collect partition-by column references from all window specs into a set
• Classify filters into three categories: window-tag, partition-by-only, and other
• Only push filters whose column references are subset of partition-by columns
• Add two helper functions: collectColRefSet and exprColRefsSubsetOf

pkg/sql/plan/pushdown.go


2. pkg/sql/plan/pushdown_test.go 🧪 Tests +71/-0

Add test for non-partition-by filter pushdown behavior

• Add new test TestWindowNonPartitionFilterNotPushedDown to verify issue #24020 fix
• Test verifies filters on non-partition-by columns are not pushed below WINDOW node
• Test verifies filters on partition-by columns are still safely pushed down
• Test uses mock column references and window specifications

pkg/sql/plan/pushdown_test.go


Grey Divider

Qodo Logo

@qodo-code-review

qodo-code-review Bot commented Apr 3, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX Issues (0)

Grey Divider


Action required

1. exprColRefsSubsetOf() returns true by default ☑ 📎 Requirement gap ≡ Correctness
Description
The new window-filter pushdown gate treats any unhandled plan.Expr variant as a subset of
partition-by columns by falling through to return true, which can incorrectly push non-partition
predicates below a WINDOW node and change query semantics. This risks reintroducing wrong results
for window + outer-filter patterns when predicates contain columns inside list/sub/corr or
other non-Expr_F wrappers.
Code

pkg/sql/plan/pushdown.go[R764-774]

+	switch e := expr.Expr.(type) {
+	case *plan.Expr_Col:
+		return set[[2]int32{e.Col.RelPos, e.Col.ColPos}]
+	case *plan.Expr_F:
+		for _, arg := range e.F.Args {
+			if !exprColRefsSubsetOf(arg, set) {
+				return false
+			}
+		}
+	}
+	return true
Evidence
Compliance ID 1 requires predicate pushdown around window/CTE boundaries to be semantics-preserving.
The PR introduces exprColRefsSubsetOf() and uses it to decide which filters can be pushed under
plan.Node_WINDOW, but the implementation only inspects Expr_Col and Expr_F and then defaults
to true for all other plan.Expr variants, even though the expression AST supports variants that
can contain/represent column references (e.g., list, sub, corr).

CTE/derived-table WHERE predicate pushdown must preserve correctness for filtered COUNT(*) query
pkg/sql/plan/pushdown.go[93-117]
pkg/sql/plan/pushdown.go[757-775]
proto/plan.proto[211-228]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`exprColRefsSubsetOf()` currently returns `true` for any unhandled `plan.Expr` oneof variant, which can misclassify filters as partition-by-only and incorrectly push them below a `WINDOW` node.
## Issue Context
This function is used in the new `plan.Node_WINDOW` filter pushdown logic. `plan.Expr` supports variants beyond `Expr_Col` and `Expr_F` (e.g., `list`, `sub`, `corr`), some of which may contain or depend on column references and should not be treated as column-free.
## Fix Focus Areas
- pkg/sql/plan/pushdown.go[93-117]
- pkg/sql/plan/pushdown.go[742-775]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. Partition expression misclassified safe ☑ 🐞 Bug ≡ Correctness
Description
The WINDOW pushdown logic treats a filter as safe if it only references columns appearing anywhere
inside PARTITION BY expressions, but this is incorrect when the partition key is an expression
(e.g., PARTITION BY a+b or date(ts)). Such filters can remove rows within a partition (not whole
partitions), changing ROW_NUMBER/RANK results.
Code

pkg/sql/plan/pushdown.go[R96-117]

+		// Collect partition-by column references from all window specs.
+		// Only filters that exclusively reference partition-by columns can
+		// be safely pushed below the window node, because they merely
+		// eliminate entire partitions without changing row numbering.
+		partCols := make(map[[2]int32]bool)
+		for _, w := range node.WinSpecList {
+			if we := w.GetW(); we != nil {
+				for _, p := range we.PartitionBy {
+					collectColRefSet(p, partCols)
+				}
+			}
+		}
+
  	for _, filter := range filters {
-			// Keep any filter that references a window output above this window node.
-			// Pushing a filter on an earlier window output below a later window node
-			// changes the row set seen by the later window and can produce wrong results.
  		if containsTag(filter, windowTag) {
  			node.FilterList = append(node.FilterList, filter)
-			} else {
+			} else if exprColRefsSubsetOf(filter, partCols) {
  			canPushdown = append(canPushdown, filter)
+			} else {
+				cantPushdown = append(cantPushdown, filter)
  		}
  	}
Evidence
Partition keys are bound from arbitrary AST expressions (not restricted to simple column refs), so
PARTITION BY entries can be functions/expressions. The new logic collects underlying column refs
from those expressions and allows any filter referencing only those columns to be pushed below
WINDOW; however, for expression-based partitioning, predicates on underlying columns are not
necessarily constant within a partition (e.g., partition by a+b and filter a>0).

pkg/sql/plan/pushdown.go[93-129]
pkg/sql/plan/pushdown.go[742-755]
pkg/sql/plan/window_binder.go[60-90]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`Node_WINDOW` filter pushdown currently allows pushing a filter if its column references are a subset of the **columns referenced inside** the PARTITION BY expressions. This is not sufficient for correctness when PARTITION BY expressions are not simple column references (e.g., `PARTITION BY a+b`, `PARTITION BY date(ts)`), because a predicate on `a` (or `ts`) may vary within a single partition.
### Issue Context
Partition-by terms are bound via `BindExpr` and can be arbitrary expressions.
### Fix Focus Areas
- pkg/sql/plan/pushdown.go[93-129]
- pkg/sql/plan/pushdown.go[742-775]
- pkg/sql/plan/window_binder.go[60-90]
### Implementation notes (fail-safe)
- Only consider a partition key “pushdown-safe” when each `PartitionBy` element is a **direct** `Expr_Col`.
- Build `partCols` from `p.GetCol()` only.
- If any partition-by element is not a direct column ref, disable this optimization for that WINDOW node (i.e., do not push non-window-tag filters below it), except possibly constant-only filters.
- Add a unit test for an expression-based partition key (e.g., `PARTITION BY a+b`) with a filter on `a` that must **not** be pushed below the WINDOW node.
This keeps the optimization correct without needing complex functional-dependency reasoning.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

ⓘ The new review experience is currently in Beta. Learn more

Grey Divider

Qodo Logo

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread pkg/sql/plan/pushdown.go Resolved
Comment thread pkg/sql/plan/pushdown_test.go Resolved
@mergify mergify Bot added the queued label Apr 3, 2026
@mergify

mergify Bot commented Apr 3, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-04-03 10:03 UTC · Rule: main
  • ✅ Checks skipped · PR is already up-to-date
  • ✅ Merged — 2026-04-03 10:04 UTC · at ff0abd8cac905e9ea1271cd00f3f45661f712d5f

This pull request spent 9 seconds in the queue, including 1 second running CI.

Required conditions to merge
  • #approved-reviews-by >= 1 [🛡 GitHub branch protection]
  • #changes-requested-reviews-by = 0 [🛡 GitHub branch protection]
  • #review-threads-unresolved = 0 [🛡 GitHub branch protection]
  • branch-protection-review-decision = APPROVED [🛡 GitHub branch protection]
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Compose CI / multi cn e2e bvt test docker compose(PESSIMISTIC)
    • check-neutral = Matrixone Compose CI / multi cn e2e bvt test docker compose(PESSIMISTIC)
    • check-skipped = Matrixone Compose CI / multi cn e2e bvt test docker compose(PESSIMISTIC)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Standlone CI / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
    • check-neutral = Matrixone Standlone CI / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
    • check-skipped = Matrixone Standlone CI / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
    • check-neutral = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
    • check-skipped = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone CI / SCA Test on Ubuntu/x86
    • check-neutral = Matrixone CI / SCA Test on Ubuntu/x86
    • check-skipped = Matrixone CI / SCA Test on Ubuntu/x86
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone CI / UT Test on Ubuntu/x86
    • check-neutral = Matrixone CI / UT Test on Ubuntu/x86
    • check-skipped = Matrixone CI / UT Test on Ubuntu/x86
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Compose CI / multi cn e2e bvt test docker compose(Optimistic/PUSH)
    • check-neutral = Matrixone Compose CI / multi cn e2e bvt test docker compose(Optimistic/PUSH)
    • check-skipped = Matrixone Compose CI / multi cn e2e bvt test docker compose(Optimistic/PUSH)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH,Optimistic)
    • check-neutral = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH,Optimistic)
    • check-skipped = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH,Optimistic)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Upgrade CI / Compatibility Test With Target on Linux/x64(LAUNCH)
    • check-neutral = Matrixone Upgrade CI / Compatibility Test With Target on Linux/x64(LAUNCH)
    • check-skipped = Matrixone Upgrade CI / Compatibility Test With Target on Linux/x64(LAUNCH)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Utils CI / Coverage
    • check-neutral = Matrixone Utils CI / Coverage
    • check-skipped = Matrixone Utils CI / Coverage

@mergify
mergify Bot merged commit 7a22ce3 into matrixorigin:main Apr 3, 2026
28 of 29 checks passed
@mergify mergify Bot removed the queued label Apr 3, 2026
@ck89119
ck89119 deleted the issue-24020 branch April 3, 2026 10:04
fengttt pushed a commit to fengttt/matrixone that referenced this pull request May 7, 2026
…rixorigin#24020) (matrixorigin#24050)

Previously, `pushdownFilters` for `Node_WINDOW` pushed any filter not referencing the window tag below the WINDOW node. This is incorrect because filtering on non-partition-by columns changes the window function's input rows, producing wrong `ROW_NUMBER()`/`RANK()`/etc. results.

**Root cause:** The outer filter `INDUSTRY_NAME='Consumer Discretionary'` was pushed below the WINDOW node with `ROW_NUMBER() OVER (PARTITION BY STOCK_CODE ...)`, changing the partition contents and thus the row numbering.

**Fix:** Only push filters whose column references are a subset of the PARTITION BY columns. Other non-window-tag filters stay above the WINDOW node.

### Changes
- `pkg/sql/plan/pushdown.go`: Collect partition-by column refs; classify filters into three categories (window-tag / partition-by-only / other)
- `pkg/sql/plan/pushdown_test.go`: Add `TestWindowNonPartitionFilterNotPushedDown`

Approved by: @ouyuanning

This branch was previously deployed

1 inactive deployment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/bug Something isn't working size/M Denotes a PR that changes [100,499] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: WHERE filter within the CTE, MO fails to correctly push down the filtering conditions.

4 participants