Skip to content

fix(plan): preserve DISTINCT and ordered admission for sort ROLLUP - #31505

Merged
XuPeng-SH merged 2 commits into
matrixorigin:mainfrom
iamlinjunhong:codex/loom/develop/a37d8207d6fbb9c77a6d34afe1f2dfa9f259e4ecf9e38d9acc2a13db0a1bfe3e
Oct 28, 2026
Merged

XuPeng-SH merged 2 commits into
matrixorigin:mainfrom
iamlinjunhong:codex/loom/develop/a37d8207d6fbb9c77a6d34afe1f2dfa9f259e4ecf9e38d9acc2a13db0a1bfe3e

Conversation

@iamlinjunhong

@iamlinjunhong iamlinjunhong commented Oct 28, 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:

What this PR does / why we need it:

Follow-up to merged #28987. Its streaming ROLLUP/AVG path remains in place; this closes the returned DISTINCT rewrite and order/admission gaps.

  • Preserve every argument and per-prefix DISTINCT state before scalar or tuple pair rewrites can replace the globally ordered ROLLUP input with hash aggregates. Keep comparison-key normalization and ordinary GROUP BY optimization.
  • Prove global input order through bound column tags, projection positions and equality types. Reuse it across direct aliases, reordered projections, filters and nested wrappers; resolve NDV from the mapped base columns. Unproven topology and CN-local scan order keep the conservative fallback.
  • Require existing proven global order in COST mode, retaining known-statistics, resource, shared-HASH and 80% cost-margin checks. SORT can still add a sort for eligible base-table input, and HASH/legacy hint controls remain available.

Original-head validation (28e094d216eae448cddbfdb517609107715fe57c) on Darwin/arm64, Go 1.27.1, GOMAXPROCS=4: targeted regressions and the planner/compiler packages pass, including an optimized SQL-to-compiler consumer. Scoped vet/lint and formatting pass. The extended SQL BVT passes 51/51 twice on the same isolated single-CN service; each round leaves no test database. High-stat baseline planner probes observed DISTINCT clearing and a hash AGG child before this correction; no old SQL result mismatch is claimed.

Executor lifecycle is unchanged. Forced SORT remains experimental for high NDV; this PR does not claim a performance improvement or rerun the historical benchmark figures. Full CI and a real multi-CN runtime run are not included in the local evidence.

Maintenance validation for candidate 11eb3903dbad1b1bbfbe8f52e4f4719520af2565, rebased onto official main df8bfd602ecc036424ff7897187565657366919d: git range-diff confirms an equivalent single-patch replay, with no conflict resolution or additional source edits. The 184 focused test roots covering ROLLUP, DISTINCT, integer precision, MATCH boolean semantics and compiler consumption pass using GOMAXPROCS=4 .agents/skills/mo-dev/scripts/mo-cgo-test -p 1 -v -count=1 -timeout=180s -run 'Test.*(Rollup|IntegerPrecision|Distinct)|^TestFullTextBooleanMatchTruthIsFound$' ./pkg/sql/plan ./pkg/sql/compile. Both complete owning packages (5939 test roots) and all vet analyzers pass with the same wrapper using -p 1 -v -vet=all -count=1 -timeout=300s ./pkg/sql/plan ./pkg/sql/compile. Formatting, git diff --check and the committed-artifact check pass. The original-head BVT evidence is reused for the unchanged patch; no BVT, benchmark or multi-CN runtime run was repeated for this maintenance update. New CI remains pending.

@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 →

@XuPeng-SH

XuPeng-SH commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

mo-bot review · mo-bot-local · done

Commit: 11eb3903dbad1b1bbfbe8f52e4f4719520af2565

Review completed. Read the assessment.

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

mo-bot review · mo-bot-local · review

Commit: 11eb3903dbad1b1bbfbe8f52e4f4719520af2565

Assessment: approve

The complete change preserves per-prefix DISTINCT semantics, proves order and NDV through bound column lineage, and restricts COST admission appropriately. The linked issue’s correctness concern is resolved. No actionable defects remain.

Model: gpt-6-astra / xhigh

Session: 01a13dcf-1586-7a01-9000-d45e20995cf8 · slot 1 · generation 1

Validation:

  • 172 focused planner/compiler tests passed, including all new regressions. Command, clean-source fingerprint and exit 0 verified in attempt-1/checks/1793167073539007860-4.json against focused-tests.sh and focused-tests.log.

  • Isolation preflight passed; 193 native/module inputs matched retained build artifacts, and repository provenance verification passed.

  • Frozen exact-head evidence reports successful UT, SCA, build, coverage and multi-CN BVT checks.

  • Saved discussion-assessment.json covering all three discussion entries, review-notes.md and validation-audit.json. Final audit confirmed unchanged source.

Limitations:

  • No fresh SQL-server BVT or benchmark run; compiler seam tests substitute physical storage. Per-case CI logs and author-run receipts were not supplied.

  • Forced SORT retains its documented high-NDV performance limitation; this PR does not claim to resolve it.

@mergify mergify Bot added the queued label Oct 28, 2026
@mergify

mergify Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

🚫 Left the queue

34 min in the queue, with no time running CI.

So far

  • ✅ Entered the queue Wed 28 Oct, 06:02 · rule main · triggered by rule Automatic queue on approval for main
  • ⏹️ Testing stopped · in place
  • 🚫 Left the queue 06:36 · 939f538

Reason

Pull request #31505 has been dequeued

Pull request from fork cannot be queued. This pull request comes from a fork, and Mergify needs the author's permission to update its branch.

The author needs to enable "Allow edits from maintainers" on this pull request.

Hint

You should look at the reason for the failure and decide if the pull request needs to be fixed or if you want to requeue it.
If you do update this pull request, it will automatically be requeued once the queue conditions match again.
If you think this was a flaky issue instead, you can requeue the pull request, without updating it, by posting a @mergifyio queue comment.

Merge conditions: 2 of 3 met

This pull request

Condition Required by
✅ #review-threads-unresolved = 0 GitHub branch protection
✅ github-review-approved GitHub branch protection

The batch, tested in place

Condition Required by
❌ any of: check-neutral = CI Required, check-skipped = CI Required, check-success = CI Required GitHub branch protection

Tick the box to put this pull request back in the merge queue (same as @mergifyio queue).

  • Requeue this pull request

Times in UTC · dashboard · how the merge queue works

@XuPeng-SH
XuPeng-SH merged commit da0c931 into matrixorigin:main Oct 28, 2026
21 of 22 checks passed
@mergify mergify Bot added dequeued and removed queued labels Oct 28, 2026
XuPeng-SH pushed a commit that referenced this pull request Oct 28, 2026
## What type of PR is this?

- [ ] API-change
- [ ] BUG
- [x] Improvement
- [x] Documentation
- [ ] Feature
- [ ] Test and CI
- [ ] Code Refactoring

## Which issue(s) this PR fixes:

- #20653

## What this PR does / why we need it:

SORT ROLLUP repeatedly finalizes and rebuilds completed aggregate groups
and allocates argument windows. At high group cardinality, these costs
can dominate aggregation. This change reuses single-group state through
append/reset and fills input ranges directly when the complete aggregate
list supports the narrow COUNT/native SUM/AVG fast path. A list
containing any unsupported aggregate keeps the existing path for the
whole list. Results, NULL handling, output ownership, cancellation
checks, planner admission, and COST thresholds are preserved.

This is a follow-up to merged #28987 (SORT ROLLUP feature) and #31505
(DISTINCT correctness and ordered-input admission). Those
DISTINCT/admission fixes are already present; this PR addresses the
remaining executor cost. The earlier static cost concern is separate
from the pre-merge measurements below. This change does not optimize
every SORT ROLLUP workload. After merge, the original reporter should
verify the remaining workload against this change.

**Validation at the merged PR head**

At `e9281125b65348d22cdfe7afafa28c5a69f2871d`:

- 623 aggexec and 236 group owning-package tests (859 total), plus 40
planner/compiler consumer and allocation-guard tests.
- 20 exact manual SQL oracle assertions across 42 statements, plus FLOAT
fail-closed execution through the HASH fallback.
- KILL QUERY during actual SORT ROLLUP work, followed by correct ROLLUP
results on the same connection and verified transaction, lock, and
working-frame cleanup. The test service exited and test databases were
removed.
- Incremental vet/lint passed for seven related packages. The new binary
records this exact revision with `vcs.modified=false`; gpt-6-astra
medium final overall review passed at this head.

The earlier two complete ROLLUP BVT runs (51/51 each) and full
cancellation/timeout matrix (10 result checks, 6 resource-closure
checks, including client cancellation, KILL QUERY/CONNECTION, reuse, and
cleanup) remain evidence from pre-merge revision
`07701c4cd47779ca7017b4674c3552fed719b815`, reviewed with the
documentation update at `44aab779ca5b5430c12edd22fba8758577b434f6`.
These full matrices were not rerun at the merged head.

**Performance and limitations**

Pre-merge local physical-operator benchmarks on Apple M4, Go 1.27.1,
GOMAXPROCS=4 (100 ms, three samples per shape) show 78–94% lower time
and more than 96% lower B/op and allocs/op for four ordered high-NDV
shapes against the pre-change SORT implementation. Derived-input shapes
including sorting also improve. These are historical operator
measurements of production candidate
`c123861e5500408a2f1798a0f8e4e80a05a35d22` with final benchmark fixtures
at `07701c4cd47779ca7017b4674c3552fed719b815` (pre-merge reviewed head
`44aab779ca5b5430c12edd22fba8758577b434f6`). No performance timing was
rerun after the main merge at
`e9281125b65348d22cdfe7afafa28c5a69f2871d`; the final review confirms
the optimization mechanism and the applicability of these historical
results, without establishing merged-head percentages, exact timings, or
absence of regression. There are no SQL end-to-end or multi-CN
performance claims.

Forced SORT remains 1.08–6.80x slower than the retained shared-HASH
baseline in the measured comparisons. DISTINCT, dedicated decimal
implementations, MIN/MAX, and unsupported mixed lists are not
accelerated. Earlier design-document performance numbers remain
historical calibration, separate from the pre-merge candidate
measurements above; neither set is a new measurement of the merged
revision.

In those pre-merge measurements, for low-NDV protection, all three
contemporaneous baseline/candidate pairs per shape fit the unchanged 20%
engineering budget (nine pairs total, maximum ratio 1.128; median ratios
0.977/1.048/0.932). Pooling measurements across different periods
instead gives COUNT/AVG ratios of 1.283/1.473, exceeding that budget;
the initial comparison was also unfavorable. Using all contemporaneous
pairs as the primary acceptance evidence is an explicitly reviewed,
post-hoc applicability revision. The small sample and fixed
baseline-first order limit the conclusion: this is not statistical proof
of no regression.

CI remains pending and is separate from the local results above. No real
multi-CN run was performed; distributed routing/state and compiler
placement gates are unchanged.

---------

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>

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

dequeued kind/bug Something isn't working kind/enhancement size/L Denotes a PR that changes [500,999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants