Skip to content

perf(plan): eliminate bounded aggregates grouped by primary key - #27850

Merged
XuPeng-SH merged 15 commits into
matrixorigin:mainfrom
XuPeng-SH:codex/design-grouped-aggregate-topk
Aug 31, 2026
Merged

XuPeng-SH merged 15 commits into
matrixorigin:mainfrom
XuPeng-SH:codex/design-grouped-aggregate-topk

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

Closes #27730.

This PR does not close or directly optimize ClickBench Q35 in #27685: hits.URL is not a declared unique key.

What changed

A direct scan grouped by every component of its declared primary key has exactly one row per surviving group. For bounded queries this PR replaces proven singleton aggregates with row expressions, deletes the hash Aggregate, and lets existing LIMIT pushdown stop an unordered scan early.

select id, count(*), sum(v)
from t
group by id
limit 10;
Before: Limit/Project -> Aggregate(group by PK) -> TableScan
After:  Project(PK, 1, cast(v)) -> TableScan(limit 10)

The rule:

  • propagates bounded demand only through unary Project, Filter, and Sort nodes;
  • requires one direct TABLE_SCAN grouped by every component of a real declared PK;
  • supports non-DISTINCT, unconfigured COUNT(*), COUNT(expr), SUM, AVG, MIN, MAX, and ANY_VALUE only when the singleton replacement is total and exact over the complete input domain;
  • rejects the whole candidate atomically if one aggregate is unsafe;
  • keeps Join, Union/shared CTE, grouping families, partial/malformed PK, unsupported/configured/DISTINCT aggregates, and aggregate-bearing queries without LIMIT on their established path;
  • retains Sort and complete-scan semantics for ORDER BY and complete scan semantics for SQL_CALC_FOUND_ROWS;
  • contains no colexec callback, new lifecycle/ownership protocol, spill-path, lock, goroutine/channel, protobuf, or RPC change.

Resolved deep-review findings

Two candidate-only correctness regressions were found by base/candidate differential review and fixed in c77fb38aeb:

  1. Singleton AVG(DECIMAL(38,10)) could change base success into Decimal128 scale overflow because the direct-cast result domain was narrower. Decimal AVG now retains Aggregate unless the complete source precision/scale domain fits the declared result type. The underlying base AVG value bug is tracked by [Bug]: AVG on high-precision DECIMAL128 silently returns an incorrect value #27855.
  2. Floating SUM/AVG of -0.0 changed later predicates because Aggregate canonicalizes signed zero to +0, while the direct cast preserved -0. Floating SUM/AVG now retain Aggregate. Floating MIN/MAX/ANY_VALUE remain eligible and were differentially verified.

The BVT now consumes the wide-decimal AVG result so projection pruning cannot hide the regression. Focused tests cover exact/unsafe decimal boundaries, malformed precision/scale, signed zero, and atomic mixed fallback.

Earlier execution-time Group/Top and GROUP_CONCAT-finalization prototypes were rejected and removed: they did not remove enough work and either regressed COUNT or improved memory by only about 2%. The decision record is docs/design/grouped_aggregate_topk_finalization.md.

Validation evidence

All runtime and performance validation was run on 10.222.1.55, against one MatrixOne data directory on NVMe; only the binary changed. Final source files on that host are SHA-identical to local head 5b92fe455d9c425bf3dd299f12799e51d65a6d8c. 5b92fe455d changes only tests/docs after the production fix in c77fb38aeb. Comparison base: a15139da62b938b0918c19675c619b259cd86460.

Performance

Shape Base Final Effect
10M PK group, unordered LIMIT 10 146.4 ms 9.7 ms 15.1x faster
10M PK group, LIMIT 10 OFFSET 100000 149.3 ms 10.4 ms 14.4x faster
10M PK group, ORDER BY COUNT LIMIT 10 160.1 ms 24.8 ms 6.5x faster
5M PK LIMIT 1000, COUNT + integer SUM 75 ms 10 ms 7.5x faster
5M PK LIMIT 1000, safe decimal AVG 75 ms 9 ms 8.3x faster
5M floating SUM fallback 75 ms 76 ms neutral
5M aggregate query without LIMIT 85 ms 85 ms neutral
10M no-PK COUNT control 249.0 ms 249.4 ms neutral (+0.2%)
10M Q35-like VARCHAR control 496.0 ms 497.7 ms neutral (+0.3%)

A non-eligible Join plan compiled 5,000 times in about 1.14-1.17s on final versus 1.16-1.18s on base after warm-up; no planner regression was measured.

Correctness and counterexamples

  • Base/final result files were SHA-identical across integer extrema, unsigned BIGINT max, BIT/YEAR, decimal boundaries, strings/CHAR padding, binary, temporal, bool, UUID, floating MIN/MAX/ANY_VALUE, and NULL.
  • Base/final result files were SHA-identical for nested LIMIT, HAVING+OFFSET, aggregate ordering, WHERE, bounded UNION branches, and derived filtering.
  • Full/partial composite PK, partitioned PK, regular/unique index access, prepared LIMIT reuse, LIMIT 0/large OFFSET, SQL_CALC_FOUND_ROWS, INSERT SELECT, CTAS, shared CTE, outer UNION, and correlated-subquery barriers were exercised.
  • Eligible plans removed Aggregate and acquired exact scan LIMIT/OFFSET. Sort/Join/Union/shared boundaries, unsafe decimal, floating SUM/AVG, unsupported/mixed aggregates, partial/no PK, and unbounded controls retained the required operator/barrier.
  • pk_group_limit.sql passed real mo-tester with metadata comparison three consecutive times: 15/15, 100%.
  • Focused tests and full pkg/sql/plan passed through the repository CGo wrapper under TZ=UTC; complete mo-service build passed.
  • Latest main does not modify this PR's seven files; merge-tree against 7a87bd6989 is conflict-free.

Confirmed pre-existing issues found during review do not block this PR because final behavior matches base:

CI on exact head 5b92fe455d remains a merge gate.

QA test plan

Same-data A/B

  1. Use a dedicated host with no other mo-service.
  2. Ensure mo-data is on NVMe and record commit/binary SHA, config, disk, client, and go version -m.
  3. Load/generate data once; change only the binary between base and candidate.
  4. Keep warm-ups, connection pattern, concurrency, query order, and configuration identical.

Correctness matrix

Compare values and metadata for:

  • single and composite PK, partial composite PK, no PK, nullable values, numeric extrema, decimal boundaries, -0.0, CHAR/VARCHAR/BINARY, and temporal values;
  • supported aggregates together and mixed unsafe/unsupported aggregates;
  • WHERE, HAVING, ORDER BY, LIMIT/OFFSET, LIMIT 0, prepared LIMIT, and SQL_CALC_FOUND_ROWS/FOUND_ROWS;
  • partitioned PK, regular/unique index access, Join, outer Union/shared CTE, CUBE/ROLLUP/GROUPING SETS, DISTINCT/configured aggregate, GROUP_CONCAT, INSERT SELECT, and CTAS.

Decimal gate: test AVG on at least DECIMAL(38,0), (38,5), (38,10), (38,12), (38,20), Decimal256, extrema, zero, and NULL. Any non-total cast domain must retain Aggregate and match base result/error behavior.

Signed-zero gate: FLOAT/DOUBLE SUM/AVG must retain Aggregate and preserve base HAVING behavior for -0.0; MIN/MAX/ANY_VALUE should remain eligible and byte-identical.

Plan assertions

Using EXPLAIN VERBOSE:

  • eligible unordered PK grouping: Aggregate absent, exact scan Limit/Offset present;
  • eligible ORDER BY: Aggregate absent, Sort retained, scan not incorrectly truncated;
  • WHERE/HAVING: filtering occurs before bounded demand;
  • SQL_CALC_FOUND_ROWS: complete scan and correct pre-limit FOUND_ROWS;
  • partial/no PK, Join, grouping families, outer Union/shared CTE, unsafe decimal, floating SUM/AVG, DISTINCT/configured/unsupported, and unbounded cases: Aggregate retained.

Performance gate

On at least 5M rows, use warm-ups plus seven timed runs. Record result count, median, scan rows/bytes, group memory/spill, CPU/peak RSS, and wall time for small LIMIT, LIMIT/OFFSET, selective WHERE/HAVING, ORDER BY aggregate, safe decimal AVG, floating fallback, unbounded, and unsupported controls.

Acceptance: one high-cardinality eligible case improves by at least 5x; eligible cases do not materially regress; fallback/unbounded controls retain the base plan and stay within 3% outside documented noise.

Repository gates

Focused planner tests, full pkg/sql/plan via the CGo wrapper, pk_group_limit.sql via mo-tester with metadata comparison, complete build, SCA, and all required CI jobs must pass on the exact PR head.

Follow-up

@XuPeng-SH
XuPeng-SH requested a review from fengttt as a code owner August 29, 2026 22:54
@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

Copy link
Copy Markdown
Contributor Author

Design review record

Change scope: complete #27730 grouped-aggregate finalization to bounded TopK feature.
Trigger: crosses Group or MergeGroup to Top ownership and lifecycle boundaries and materially changes a hot path.
Design revision: 9c91e8c.
Resolved findings:

  • MergeGroup concrete executors do not exist at Prepare, so eligibility is now a two-stage handshake with fallback before the first admission and no late fallback.
  • Top attachment is explicitly the last non-failing Prepare transition.
  • zero-aggregate grouped DISTINCT ownership is defined and covered.
  • Q1 ownership, Q2 termination, Q3 bounds, remote reconstruction, prepared reuse, offset, ties, unsupported fallback, and deterministic validation are closed.
    Decision: PASS. Implementation may proceed in this PR and must remain aligned with this revision; material deviations require a design update.

@XuPeng-SH XuPeng-SH changed the title docs(design): define grouped-aggregate TopK finalization perf(group): stream finalized aggregates into bounded TopK Aug 30, 2026
@matrix-meow matrix-meow added size/XXL Denotes a PR that changes 2000+ lines and removed size/XS Denotes a PR that changes [1, 9] lines labels Aug 30, 2026
@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Implementation self-review completed after the design gate.

Two review findings were fixed before this update:

  1. COUNT ownership on cancellation: state was initially detached before the cancellable extra-value loop finished. A mid-loop cancellation could therefore lose the only cleanup owner. Ownership is now transferred only after the loop succeeds, with a regression test that cancels inside the loop and proves Free retains terminal ownership.
  2. Strict activation and performance: unknown function metadata could have been classified as stable by a name-only check, and a one-chunk result paid callback overhead without a memory benefit. Activation now resolves the concrete overload safely and rejects malformed metadata; a no-spill single-chunk result uses the ordinary O(B) pull path.

The complete owning-package CGo suite and focused race suite pass after both fixes. The stable 100x, count=5 benchmark shows no material regression at the multi-chunk activation boundary, while the single-chunk control now falls back. No late fallback, asynchronous lifecycle, protocol change, or alternate comparator was introduced.

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

Design doc and/or issue, this kind of issue should have a full example query, not just a ... group by order by limit 10.

Give an example query -- I think you already had it from the numbers, but it is much clear to read the full query, and point out where exactly the top is pushed down, from which operator to which, and where is the saving really happens.

@LeftHandCold LeftHandCold left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Deep-reviewed exact head 0011a8e against merge-base 4dedea1. I traced the complete-PK proof through aggregate replacement, WHERE/HAVING remapping, pagination composition, ORDER BY and SQL_CALC_FOUND_ROWS barriers, and the shared PK consumers (HashOnPK, group hash keys, aggregate pullup, stats, and ONLY_FULL_GROUP_BY). I also checked signed-zero, CHAR/collation, composite/malformed PK metadata, fallible/volatile expressions, dynamic limits, overflow, and atomic fallback paths. Focused regressions and the full pkg/sql/plan suite passed through the repository CGo wrapper; go build, go vet, gofmt, and diff checks passed. All executed GitHub CI checks on this head are green. No merge-blocking correctness, compatibility, lifecycle, or performance issue found.

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

size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Enhancement]: Eliminate bounded aggregates grouped by a complete primary key

5 participants