Skip to content

feat: add cost-based streaming sort rollup - #28987

Merged
mergify[bot] merged 30 commits into
matrixorigin:mainfrom
iamlinjunhong:codex/issue-20653-sort-rollup
Oct 27, 2026
Merged

mergify[bot] merged 30 commits into
matrixorigin:mainfrom
iamlinjunhong:codex/issue-20653-sort-rollup

Conversation

@iamlinjunhong

@iamlinjunhong iamlinjunhong commented Sep 16, 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:

Fixes #20653

What this PR does / why we need it:

  • Add a streaming sort-based ROLLUP executor with correct rollup-value filling and GROUPING bitmap semantics.

  • Add conservative COST/SORT/HASH selection through the session variable rollup_algorithm, while retaining the legacy rollupSort=1/2 compatibility hint.

  • Reuse a proven ordering from a narrow derived-table ORDER BY shape and avoid a second sort.

  • Keep hash as the fail-closed fallback for unknown statistics, unsafe aggregate state, unsupported grouping types, and unproven physical properties.

  • Close cross-batch boundary replay and output-batch lifecycle issues; account for hidden aggregates and dense HLL output capacity in cost admission.

  • Preserve SAMPLE ROLLUP detail and grand-total branches under SORT and eligible COST by retaining the existing grouping-set expansion.

Validation of the SAMPLE fix on candidate 5b977792726fbf1f3c258e82a4666a23994ba3ee (parent afbaa2658bfc5f9e66003cf702454885fc1aa979; Darwin/arm64, Go 1.27.1, CGO enabled):

  • Newly run: GOMAXPROCS=4 .agents/skills/mo-dev/scripts/mo-cgo-test -v -count=1 -timeout=180s -run '^TestSortRollupSamplePreservesGroupingSets$' ./pkg/sql/plan. Before the guard, both ROLLUP spellings failed under SORT and eligible COST: expected two reachable SAMPLE branches, got one. With the guard, all cases pass, including HASH, ordinary GROUP BY and non-SAMPLE SORT-admission controls on the same ordered input/statistics.
  • Newly run: the complete planner package with the same wrapper, -count=1 -timeout=240s ./pkg/sql/plan, passed (63.026s). Scoped go vet and incremental golangci-lint 2.14.0 against the parent passed (0 lint issues); formatting and PR artifact checks passed.
  • Newly run: built the service from this source and ran test/distributed/cases/hint/rollup_sort.sql in normal mo-tester comparison mode (ignore nometa pprof, pinned tool revision 309a0ca650e0c55e90292767fd61e4976818d66d). Both rounds passed 42/42 on the same clean single-CN launch. Each round's teardown left zero matching test databases; the owned service exited normally. The new one-row, 100-percent SAMPLE cases assert both ROLLUP branches, both spellings, HASH/COST controls and ordinary GROUP BY output. Expected rows were authored from the existing SAMPLE contract, not generated from the fixed binary.
  • Reused: unchanged Group lifecycle/race and compiler/frontend evidence, plus successful parent-head UT, coverage, SCA and complementary BVT checks. These are parent-head results; fresh complete CI on this candidate is pending. No new race, multi-CN or performance run is claimed for this planner-only guard.

The fix reuses the existing SAMPLE detector at the common ROLLUP admission gate. Sampling and legacy expansion remain owned by their existing planner/executor paths; there is no new streaming SAMPLE implementation or wire capability. The maintained design records this fallback, and its approval history remains separate from validation results. Raw logs and per-run records remain outside tracked source.

Historical operator benchmark (not rerun for this refresh):
On the deterministic 1M-row derived-order benchmark on an Apple M4, SORT was 24.94 ms vs HASH parallel 41.52 ms for COUNT, and 23.59 ms vs 35.92 ms for AVG. The existing 500k high-cardinality unordered SQL workload remains faster with HASH, so the default COST mode keeps HASH there.

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

@mergify mergify Bot added the kind/feature label Sep 16, 2026
@matrix-meow matrix-meow added the size/XXL Denotes a PR that changes 2000+ lines label Sep 16, 2026
@iamlinjunhong
iamlinjunhong force-pushed the codex/issue-20653-sort-rollup branch from 7e439d0 to 04f5e1d Compare September 16, 2026 07:30
@iamlinjunhong
iamlinjunhong force-pushed the codex/issue-20653-sort-rollup branch from 04f5e1d to d23aed6 Compare September 16, 2026 09:46
@XuPeng-SH

XuPeng-SH commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: afbaa2658bfc5f9e66003cf702454885fc1aa979

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: afbaa2658bfc5f9e66003cf702454885fc1aa979

Assessment: request_changes

The mandatory design-first gate remains open for revision R1.2. Reusing Group’s aggregate and cleanup owners is reasonable, but the prior approval predates the revised empty-input contract. Implementation approval stops at this gate; no runtime defect is claimed.

Model: gpt-6-astra / xhigh

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

  • P1 docs/design/rollup-sort-rollup.md:70: R1.2 changes empty-input ROLLUP from one grand-total row to zero rows and changes EOF finalization, after the previously approved revision.
    Impact: This feature adds over 2,500 production lines across planner, compiler, executor and frontend, triggering the repository’s mandatory design review. The current semantic and lifecycle revision lacks the required traceable acceptance. Record independent approval of the exact R1.2 specification and its affected EOF, cleanup and capacity decisions before implementation approval.
    Evidence: The latest supplied approval targets 4b68b4c, whose design requires one empty-input grand-total row. Comparing that revision with the candidate confirms the changed design and executor finalization. Current lines 75–79 explicitly state that R1.1 acceptance does not approve R1.2 and approval remains pending. The PR body independently acknowledges pending design approval.

Validation:

  • Read the complete design, supplied PR discussion and review history; inspected ownership boundaries and compared the candidate with the previously approved revision.

  • Static audit verified the frozen head/base, clean source, complete 32-file patch and approval chronology. Receipt checks/1792952142882223734-3.json exited 0 and matches design-gate-audit.log.

  • Audit and reconciliation are retained under /home/xupeng/.local/state/mo-bot/jobs/5ffbc783a8bdfdc98b0dab2c/attempt-1/design-gate-review.json and review-evidence.json.

Limitations:

  • The repository’s .agents/skills/mo-dev/references/feature-design-review.md requires reviewers to “stop the implementation approval path” when this gate fails. Complete implementation, test, lifecycle and performance conformance review remains outstanding.

  • No Go tests or native benchmarks were run. local_validation is empty; frozen successful CI statuses do not establish design approval.

  • The full linked issue #20653 text was not supplied.

@iamlinjunhong

Copy link
Copy Markdown
Contributor Author

Independent design approval is pending for revision R1.2 in docs/design/rollup-sort-rollup.md at head afbaa26, as identified in review #28987 (review) . Compared with the specification at the previously approved head 4b68b4c, R1.2 changes empty-input ROLLUP from one grand-total row to zero rows to follow official main's merged #30169 contract. EOF finalization is suppressed when no input row was observed; real source NULLs still contribute all prefixes. The document records no new wire capability, owner or resource budget and explicitly keeps R1.2 approval pending. Exact-head CI run https://github.com/matrixorigin/matrixone/actions/runs/40214684933 passed CI Required, Ubuntu UT, UT coverage, coverage merge, arm64 SCA and both BVT producers. No new local tests or benchmarks were run for this request. Please record independent approval of the exact R1.2 specification, including its affected EOF, cleanup and capacity decisions.

Loom 只为 head afbaa2658bfc 发送这一次审批请求,不会重复发送。

@XuPeng-SH

XuPeng-SH commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: afbaa2658bfc5f9e66003cf702454885fc1aa979

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: afbaa2658bfc5f9e66003cf702454885fc1aa979

Assessment: request_changes

The mandatory design gate remains open for R1.2. Its compatibility rationale is reasonable, and earlier technical findings have corresponding source fixes, but neither historical approval nor green CI establishes acceptance of the revised specification. No runtime defect is claimed.

Model: gpt-6-astra / xhigh

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

  • P1 docs/design/rollup-sort-rollup.md:75: R1.2 changes empty-input ROLLUP from one grand-total row to zero rows, including EOF finalization and capacity-check behavior, after the approval of revision 4b68b4c.
    Impact: Design approval requirement: this feature exceeds the repository’s production-size threshold and crosses planner, compiler, executor and frontend ownership boundaries. Record independent acceptance of the exact R1.2 specification and its affected EOF, cleanup and capacity decisions before implementation approval.
    Evidence: Current lines 70–79 explicitly exclude R1.2 from R1.1 acceptance. Comparing the historically approved source confirms the semantic and executor changes. Author comment issue_comments:6436485002 acknowledges approval remains pending; no later acceptance appears in the complete frozen discussion. The applicable requirement is .agents/skills/mo-dev/references/feature-design-review.md, section 2.

Validation:

  • Static audit passed with clean source at the assigned head/base. Receipt checks/1793089061888748113-4.json matches design-gate-audit.log under /home/xupeng/.local/state/mo-bot/jobs/a8396f93466f27e301e55f4d/attempt-1.

  • Saved discussion-assessment.json accounting for all 32 nonempty discussion items, including author counterevidence and historical approvals.

  • Verified the 32-file delta inventory and compared R1.2 with the historically approved specification. Detailed scope and evidence are retained in design-gate-review.json and review-evidence.json.

  • Frozen current-head CI reports successful UT, coverage, SCA, shared build and complementary BVT checks. These statuses do not establish design approval.

Limitations:

  • The mo-self-review skill states: “Missing/unapproved or failed design makes the decision REQUEST_CHANGES and short-circuits full implementation polishing.” Complete implementation, lifecycle, test and performance conformance review remains outstanding.

  • No Go tests or benchmarks were run. local_validation is empty, and the referenced prior audit directory is absent; its execution claims were not reused.

  • Historical operator measurements are not newly validated throughput evidence. The linked issue body and raw CI logs were not supplied.

@XuPeng-SH

XuPeng-SH commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: afbaa2658bfc5f9e66003cf702454885fc1aa979

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: afbaa2658bfc5f9e66003cf702454885fc1aa979

Assessment: request_changes

Reviewed the complete delta and discussion. The aggregate design and revised cost model are reasonable; the author's empty-input explanation matches the baseline, and the earlier human-only approval objection is unsupported. One correctness defect remains: SORT selection silently removes SAMPLE ROLLUP branches, including under eligible default COST.

Model: gpt-6-astra / xhigh

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

  • P1 pkg/sql/plan/query_builder.go:6339: With an integer grouping key, execute SELECT a, SAMPLE(b,100 PERCENT) FROM t GROUP BY a WITH ROLLUP using rollup_algorithm='SORT'. Default COST also triggers this for eligible ordered input; reproduced with protocol 131, 100000 estimated rows and NDV 1.
    Impact: The candidate gate admits SAMPLE and suppresses grouping-set expansion, but appendSampleNode bypasses the streaming aggregate that would produce the remaining prefixes. Results therefore omit grouping-set rows. Exclude selectClauseHasSampleExpr(selectClause) from this gate and retain SAMPLE's existing expansion; add regression coverage for both ROLLUP spellings under SORT and eligible COST.
    Evidence: Public Parse/BuildPlan probes produce one SAMPLE branch and no prefix-producing aggregate; HASH retains two branches, and ordinary GROUP BY controls pass. The preexisting mysql_compat_null_rollup_grouping.result:131-139 independently requires two rows for a single-row SAMPLE ROLLUP. attempt-2/sample-probe-v2.log and checks/1793095395618608486-14.json retain the failures. Restoring the base query_builder owner, with only two signature adaptations, passes all eleven cases: sample-baseline-owner-compat.log and checks/1793095701891758861-13.json.

Validation:

  • Recovered exact-head focused group/planner tests passed: attempt-1/focused-tests.log, receipt 1793094896394360635-14.json. Coverage includes prefix results, NULL/GROUPING, yield/EOF, cancellation, cleanup, DISTINCT and cost boundaries.

  • Recovered compile/frontend/control tests passed: attempt-1/consumer-tests.log, receipt 1793095009397948599-13.json. Coverage includes coordinator placement, codec restrictions and session/prepared-plan invalidation.

  • Executor preflight passed. Verified all 195 retained native inputs against current source and revalidated the library through the repository provenance owner.

  • Saved review-plan.md, review-notes.md, discussion-assessment.json and review-evidence.json under attempt-2. Final audit passed: receipt 1793095926486503614-4.json confirms clean frozen source, all 36 discussion keys accounted for, and command/source/exit/log correlation.

Limitations:

  • The new reproduction exercises the production planner with typed metadata mocks, not a live SQL server. The passing control restores the baseline planner owner on current dependencies, not a complete baseline build.

  • No full distributed BVT, live multi-CN run, race suite or fresh performance benchmark was executed. Historical calibration remains qualified evidence; raw historical benchmark artifacts were unavailable. Author-reported green CI was not independently retrieved.

@XuPeng-SH

XuPeng-SH commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: 5b977792726fbf1f3c258e82a4666a23994ba3ee

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: 5b977792726fbf1f3c258e82a4666a23994ba3ee

Assessment: approve

Reviewed the complete change, reusing verified unchanged closures from the parent review. The SAMPLE guard preserves grouping-set branches through the existing owner and resolves the prior row-loss finding. The empty-input contract matches the baseline; the earlier human-only approval objection lacks an applicable policy. No actionable findings remain.

Model: gpt-6-astra / xhigh

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

Validation:

  • Full planner package passed in 16.569s, including the new regression and both independent SAMPLE probes. Receipt: checks/1793100922051277222-4.json; log: planner-tests.log.

  • Verified and reused parent Group lifecycle, compiler, codec and frontend checks with matching source and retained receipts/logs.

  • Executor preflight passed; all 195 native inputs matched and the repository provenance owner verified the retained library.

  • Author reports two exact-candidate single-CN SQL comparison runs, each 42/42. Expected SAMPLE rows independently match the preexisting contract.

  • Saved discussion-assessment.json covering all 38 discussion keys and review-evidence.json. Final audit passed: checks/1793101114556781619-4.json.

Limitations:

  • Author SQL logs were not supplied; those runs are author-reported, not locally reproduced. Complete candidate CI remains pending.

  • No fresh multi-CN, race or performance run; unchanged closures reuse scoped evidence. Historical benchmark raw artifacts remain unavailable.

  • Linked issue #20653 was supplied and reviewed; mentioned parent #20650 was unavailable, so no additional requirements were inferred.

@mergify

mergify Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

✅ Merged into main as 935811c at 18:51 UTC

2 h 56 min in the queue, 1 h 1 min of it CI.

So far

  • ✅ Entered the queue Tue 27 Oct, 15:54 · rule main · triggered by rule Automatic queue on approval for main
  • ✅ Passed · in place
  • ✅ Merged 18:51 · 935811c · squash
Merge conditions: 3 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-success = CI Required, check-neutral = CI Required, check-skipped = CI Required GitHub branch protection

Times in UTC · dashboard · how the merge queue works

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Subtask]: Rollup using Sort

7 participants