Skip to content

fix(plan): support GROUPING expressions in ROLLUP ORDER BY - #25335

Merged
mergify[bot] merged 40 commits into
matrixorigin:mainfrom
ck89119:issue-25287-main
Jul 25, 2026
Merged

mergify[bot] merged 40 commits into
matrixorigin:mainfrom
ck89119:issue-25287-main

Conversation

@ck89119

@ck89119 ck89119 commented Jul 1, 2026

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • API-change
  • BUG
  • Improvement
  • Documentation
  • Feature
  • Test and CI
  • Code Refactoring

Which issue(s) this PR fixes:

issue #25287

What this PR does / why we need it:

ROLLUP, CUBE, and GROUPING SETS are expanded into an internal UNION ALL plan. The original ORDER BY is bound above that union, where source columns referenced by expressions such as GROUPING(region) are no longer visible even when the same expression is already projected.

This change rewrites an ORDER BY expression that exactly matches a select-list expression to its projection ordinal before building the internal grouping-set union. It reuses the projected value, preserves the final output schema, and does not relax the rules for explicit user-written set operations.

The change also adds planner unit coverage and a distributed ROLLUP regression case with real NULL values.

Validation:

  • go test -count=1 ./pkg/sql/plan
  • go build ./pkg/sql/plan/...
  • go vet ./pkg/sql/plan/...
  • modified helper coverage: 100%
  • make
  • rollup BVT: 112 passed, 0 failed, 2 ignored
  • git diff --check

make static-check remains blocked by existing pkg/common/docfilter CGo unsafe molint violations; the same failure was reproduced on a clean main checkout.

@mergify mergify Bot added the kind/bug Something isn't working label Jul 1, 2026
@matrix-meow matrix-meow added the size/M Denotes a PR that changes [100,499] lines label Jul 1, 2026
@ck89119
ck89119 marked this pull request as ready for review July 1, 2026 14:21
@ck89119
ck89119 requested review from aunjgr and ouyuanning as code owners July 1, 2026 14:21
@ck89119
ck89119 requested a review from a user July 1, 2026 14:21
@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

ck89119 and others added 3 commits July 14, 2026 11:50
Extend the grouping-set ORDER BY fix to the DISTINCT path:
- carry star-layout classification (hidden / visible / non-star) so a
  grouping() key matching a visible select item resolves to its
  star-expanded position instead of an AST-space ordinal
- split alias semantics: SELECT-side keys use NoAlias (name == source
  column) while ORDER BY-side keys keep AliasBeforeColumn, so alias
  shadowing is rejected instead of silently matching the wrong item
- report NotYetImplemented for a grouping() ORDER BY item wedged between
  multiple '*' expansions rather than mis-ordering silently

Add UT for the DISTINCT+star, alias-shadowing and between-stars cases,
and append rollup BVT coverage (results targeted-appended, not
whole-file re-recorded).

Co-Authored-By: Claude Opus 4.8 <[email protected]>

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

Codex automated review

The DISTINCT grouping-set ORDER BY rewrite still compares unbound text and erases relation identity inside GROUPING(), causing valid queries to be rejected and distinct queries to sort by the wrong grouping bit.

P1 - Bind source columns before matching DISTINCT grouping expressions (pkg/sql/plan/query_builder.go:4281)

On the DISTINCT grouping-set path, select-list keys call qualifyGroupingOrderExpr with useAlias=false, which returns the raw clone without source-column binding. The ORDER BY side uses a fresh alias-only context, so unqualified ordinary columns also remain raw. Consequently, select distinct grouping(a) + t.b ... group by t.a, t.b with rollup order by grouping(a) + b produces keys grouping(a)+t.b and grouping(a)+b and is rejected at line 4233, although b unambiguously resolves to the same source column. The normal binder qualifies select expressions with NoAlias and ORDER BY expressions with AliasBeforeColumn, so this special path should compare bound/canonical expressions while preserving alias semantics.

P1 - Do not discard relation identity inside GROUPING arguments (pkg/sql/plan/query_builder.go:4420)

The recursive qualifier stripping makes GROUPING(t1.a) and GROUPING(t2.a) identical comparison keys. On the DISTINCT path, that causes select distinct grouping(t1.a) from select_test.bind_select t1, select_test.bind_select t2 group by t1.a, t2.a with rollup order by grouping(t2.a) to match the visible ordinal and bypass normal binding. The sort then uses the selected GROUPING(t1.a) bit instead of the requested GROUPING(t2.a) bit, and an ORDER BY expression that is not in the DISTINCT select list is accepted. GROUP BY binding preserves these qualified columns as distinct grouping entries, so matching must retain bound relation identity and reject ambiguous or mismatched arguments.

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

GROUPING matching is still not identity-safe. DISTINCT grouping-set ORDER BY can compare against unbound expression text, and GROUPING strips relation identity, so same-named columns from different self-join inputs may select the wrong grouping bit. Preserve bound column identity through GROUPING and compare normalized bound expressions. Add qualified self-join and DISTINCT expression regressions.

aunjgr
aunjgr previously requested changes Jul 20, 2026

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

GROUPING matching is still not identity-safe. DISTINCT grouping-set ORDER BY can compare against unbound expression text, and GROUPING strips relation identity, so same-named columns from different self-join inputs may select the wrong grouping bit. Preserve bound column identity through GROUPING and compare normalized bound expressions. Add qualified self-join and DISTINCT expression regressions.

ck89119 added 3 commits July 23, 2026 14:21
# Conflicts:
#	pkg/sql/plan/query_builder.go
#	test/distributed/cases/window/rollup.result
#	test/distributed/cases/window/rollup.sql
@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

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

Codex automated review

Previously blocking identity, qualifier, nested-expression, star-expansion, and hidden-ordinal topics are fixed by the new branch-bound remapping path. One new compatibility blocker remains in DISTINCT grouping-set normalization. Focused tests could not run because go is unavailable in this environment.

P1 - Preserve BINARY/VARBINARY output types in DISTINCT grouping sets (pkg/sql/plan/query_builder.go:6146)

SELECT DISTINCT b FROM t GROUP BY b WITH ROLLUP now routes every branch through this synthetic IF(GROUPING(b), NULL, b). iffCheck has no T_binary or T_varbinary result candidate; for (ANY, BINARY) / (ANY, VARBINARY) its implicit-cast costs select BLOB. The resulting normalized[i].Typ is used unchanged downstream, so a query that previously returned BINARY/VARBINARY now exposes BLOB metadata (and its associated type semantics) to clients. Preserve the original varlen binary type during normalization—either support binary/varbinary in IF or avoid generic IF coercion here—and add BINARY and VARBINARY rollup/cube DISTINCT regressions.

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

Codex automated review

Previously blocking identity, qualifier, nested-expression, star-expansion, hidden-ordinal, and BINARY/VARBINARY type issues are fixed; no correctness blocker remains. Focused tests could not start because go is unavailable in the environment. One non-blocking PR-scope issue remains.

P2 - Remove internal review notes from the change (CLAUDE_TODO_2026-07-24.md:67)

The current commit adds 22 lines of private review workflow notes, planned commands, and submission instructions. This file has no product, test, or user-documentation consumer and does not exist on the base branch, so these additions only leave unrelated development scratch material in the repository. Remove this block from the PR.

@XuPeng-SH XuPeng-SH 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.

Requesting changes on the latest head (64f0397e9). The earlier correctness blockers around identity-safe binding, star expansion, grouping NULL normalization, volatile expressions, and binary/vector typing are fixed. One performance blocker remains.

P1 — Preserve branch-local DISTINCT after grouping NULL normalization

At pkg/sql/plan/query_builder.go:3857, every generated grouping-set branch is now forced to Distinct: false, leaving only the global DISTINCT above the complete UNION ALL. The global DISTINCT is required for correctness, but removing the branch-local DISTINCT creates an exponential fan-in regression for CUBE and a large-cardinality regression for ROLLUP/GROUPING SETS.

Concrete plan repro:

select distinct 1
from select_test.bind_select
group by cube(a, b, c);

On the PR base, each of the 8 cube branches has a local duplicate-elimination AGG before the UNION. On this head, there is no branch-local duplicate elimination; all rows emitted by all 8 grouping aggregates flow through the 7-node UNION ALL chain, and only then reach one global AGG. For a high-cardinality grouping key and low-cardinality visible projection, this changes the parent input from O(number of grouping sets) to O(sum of grouping-set cardinalities), increasing CPU/data movement and making CUBE especially risky.

Please retain the new global DISTINCT, but also apply local DISTINCT after each branch has run appendGroupingSetDistinctProjectionNode (so grouping NULLs are normalized first). In a detached worktree, restoring Distinct: selectClause.Distinct at this branch point preserved the full pkg/sql/plan/... test pass. Add a plan-shape regression proving branch reduction remains below UNION while global DISTINCT remains above it.

P2 — Remove internal review scratch files

CLAUDE_TODO_2026-07-23.md and CLAUDE_TODO_2026-07-24.md add 263 lines of private review workflow, planned commands, and submission notes with no product/test/documentation consumer. They should not ship in the repository.

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

Codex automated review

Previous branch-local DISTINCT fan-in blocker is fixed: local de-dup now follows grouping-NULL normalization, while global DISTINCT remains above UNION ALL; ROLLUP, CUBE, and GROUPING SETS have plan-shape coverage. The scratch-file P2 is fixed by removal. Earlier identity, star/ordinal, volatile, and binary/vector-type blockers remain fixed. The merge has no remerge-resolution delta. git diff --check passes; focused tests could not run because go is unavailable.

@XuPeng-SH XuPeng-SH 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.

Reviewed exact head 82f0125 against main 6d8b254. No blocking findings remain.

Verified the prior correctness and performance blockers are closed: bound relation identity is preserved for GROUPING expressions; nested expressions, aliases, self-joins, star expansion, and hidden ordinal boundaries are covered; DISTINCT keeps branch-local reduction after grouping-NULL normalization plus global de-dup above UNION ALL; derived ORDER BY keys are materialized after DISTINCT; binary/vector result metadata is preserved.

Compatibility/risk: the change is planner-local with no catalog, protobuf, persisted-state, or upgrade migration impact. The additional runtime projection is confined to DISTINCT grouping-set branches and all compile-time maps/slices are statement-bounded.

Validation on this exact head:

  • git diff --check: pass
  • full pkg/sql/plan and pkg/sql/plan/function tests: pass
  • focused grouping-set/IF regressions: pass
  • required CI (UT, SCA, compose/standalone BVT, coverage, Iceberg): green

@mergify

mergify Bot commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-07-25 16:32 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • ✅ Checks skipped · PR is already up-to-date
  • ✅ Merged — 2026-07-25 16:32 UTC · at 82f0125c376f16f499b469b37c6ecaee02239c4a · squash

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

Required conditions to merge
  • #review-threads-unresolved = 0 [🛡 GitHub branch protection]
  • github-review-approved [🛡 GitHub branch protection] (documentation)
  • github-review-decision = APPROVED [🛡 GitHub branch protection] (documentation)
  • 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 / 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 Utils CI / Coverage
    • check-neutral = Matrixone Utils CI / Coverage
    • check-skipped = Matrixone Utils CI / Coverage
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone CI / SCA Test on Linux/arm64
    • check-neutral = Matrixone CI / SCA Test on Linux/arm64
    • check-skipped = Matrixone CI / SCA Test on Linux/arm64

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/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants