Skip to content

perf(sql): reduce redundant aggregation and preserve analytic parallelism - #32625

Merged
XuPeng-SH merged 16 commits into
matrixorigin:mainfrom
aptend:perf/tpcds-window-fusion-20261110
Nov 13, 2026
Merged

XuPeng-SH merged 16 commits into
matrixorigin:mainfrom
aptend:perf/tpcds-window-fusion-20261110

Conversation

@aptend

@aptend aptend commented Nov 12, 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:

Related to #26768.

What this PR does / why we need it:

Reduce repeated analytic work and avoid unnecessarily serial execution, using general relational and ownership proofs rather than query-specific rules:

  • Preaggregate total exact decimal SUMs before unique dimension payload joins, retaining the final regrouping and published types. Derive a necessary key-domain SEMI filter before grouped outer joins without replacing their original joins or predicates.
  • Reuse bounded, total grouped CTE inputs beneath per-consumer windows; recognize pending INNER equalities and safe literal routing predicates while retaining drain, error-domain and cumulative resource guards.
  • Fuse independent same-layout MIN/MAX windows, with per-expression resumable state and shared input/sort; preserve entirely coordinator-local shuffle placement.
  • Batch eligible inline-string hash-join projections. Preserve complete DISTINCT owners for downstream partial aggregation, and admit existing bounded parallel INTERSECT/MINUS execution after blocking DISTINCT without removing local deduplication.
  • Correct ANTI active-domain costing and preserve the corresponding build-side decision. Statistics affect profitability, never uniqueness, arithmetic totality or rewrite legality.

No SQL text matching, query/table names, schema changes, ANALYZE requirement, new settings, increased resource limits or new wire/storage formats. Automatic-merge disabling is benchmark-only and is not included in this PR.

Measured performance

TPC-DS 1T, original 99-query corpus, 129, one CN / 64 logical CPUs, automatic DOP, agg_spill_mem=4GiB, join_spill_mem=0 (automatic), sort_spill_mem=512MiB, GOGC=200, service memory cap 192GiB / swap disabled; automatic merge off in both runs.

Full-suite metric Recorded Nov 6 baseline Nov 12 optimized run Reduction
End-to-end 50m 17.555s 40m 54.635s 18.7%
Sum of SQL client times 48m 33.500s 39m 11.170s 19.3%
Completed / failed 99 / 0 99 / 0 No timeout or OOM

The full-suite comparison is historical (25d6a4746f versus the tested pre-rebase snapshot 93e97fd571), not an isolated same-main A/B. All 21 changed production files were hash-verified against the native tested sources. The 12 patches were subsequently rebased unchanged onto b9c06b27b0, followed by the input-totality review fix below; the full-suite timing above is from before those updates.

Independent original-SQL controls against each optimization's immediate parent support the individual improvements (incremental pairs; do not add their savings together):

Query / mechanism Parent seconds Optimized seconds Reduction
Q4, exact SUM pushdown 189.07 91.22 51.8%
Q11, exact SUM pushdown 105.08 52.67 49.9%
Q47, grouped CTE input reuse 56.91 27.79 51.2%
Q57, grouped CTE input reuse 39.01 25.93 33.5%
Q75, preserve DISTINCT owners 91.48 54.47 40.5%
Q78, necessary grouped-key domain 168.73 117.49 30.4%
Q38, parallel set admission 80.19 51.55 35.7%
Q87, parallel set admission 89.83 55.47 38.3%

Complete outputs match within each pair. Against the historical full99 outputs, 94 are byte-identical, four retain identical row multisets and ORDER BY key sequences with changes only within ties, and Q39 differs only in floating-point covariance results (maximum absolute difference 6.67e-16).

Versioned benchmark evidence includes all 99 timings, output checksums, settings, tested-source hashes and the post-rebase plan comparison.

Validation

  • Post-rebase normal owning-package tests pass with -count=1: vector, hashjoin, window, compile, plan and explain, using .agents/skills/mo-dev/scripts/mo-cgo-test -p=2 -count=1 -timeout=6m.
  • Dependent Group, aggregate executors and materialized Source packages also pass with -count=1.
  • Post-rebase captured-stat fixtures build all 103 TPC-DS statements and all 22 TPC-H 1T queries. All 22 TPC-H reachable execution trees match latest main, ignoring allocation/tag numbering and floating-point estimate tails. This is plan evidence; no new TPC-H runtime result is claimed.
  • Rebase preserves the active Q4/Q11 partial aggregations. Upstream's constant-FALSE selectivity fix avoids redundant partial aggregation in already-empty branches.
  • Current-head local SCA PASS (exit 0, 0 issues) with repository-pinned molint 35bd4d9a4055 and golangci-lint 2.14.0, repository configuration and tests included. The reverse-dependency selector reaches 351/509 packages and selects the full graph: molint check -mod=readonly ./...; golangci-lint run --allow-serial-runners --timeout=20m --concurrency=4 -c .golangci.yml --new-from-rev=b9c06b27b0d7384ca31ce67edd43f764152d56d2 ./.... The final error-code regression oracle was also rechecked with vet/molint/golangci over ./pkg/sql/plan ./pkg/tests/sqlintegration.

Reviewed design revisions and invariants are kept separately: versioned design bundle. Historical rejected alternatives in those notes are not part of the source diff. Raw benchmark records and fixture statistics remain outside this PR.

Review follow-up

Rebased onto b9c06b27b0. Grouped SUM pushdown now requires both complete join inputs to be deterministic and total, reusing the existing safety proof. This covers nested predicates/projections and dimension block filters before a partial aggregate can change hash-build demand.

The new public-SQL regression uses ordinary ANALYZE/UPDATE-stale estimates: the parent returns Error 20203 where aggPushDown=1 returns empty; the fixed default returns empty too, and still reports moerr.ErrInvalidArg when the dimension is nonempty and the CAST is demanded. The test passes twice in one process (4.73s first scenario, 0.21s reused scenario); three focused rejection cells are red on the parent and green after the fix. Owning planner tests pass (99.069s).

Both 103-statement TPC-DS and 22-query TPC-H fixtures pass. Q4/Q11 retain their performance plans and all 22 TPC-H reachable trees are unchanged. Q5 conservatively loses three newly introduced partial aggregates whose complete inputs cannot be proved total; its earlier small timing difference was not an established improvement. No new full99 runtime is claimed for this review-fix head.

@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 commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Queue requested — the merge queue status continues in this comment ↓.

@XuPeng-SH

XuPeng-SH commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: da5ebca8193d9c3f1d7e113fb0b0dfeaf12f2fce

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

Assessment: request_changes

The optimizations reasonably reuse existing execution and cleanup owners. However, grouped SUM pushdown has a reproducible regression: it can make a previously skipped fact predicate execute and turn an empty result into a CAST error.

Model: gpt-6.1-sol / max

Session: 01a1a004-90c3-73b1-acc9-3d4636452003 · slot 0 · generation 0

  • P2 pkg/sql/plan/grouped_sum_pushdown.go:168: A total DECIMAL SUM reads a fact subtree containing a fallible predicate such as CAST(bf.s AS BIGINT)>0. The dimension filter matches no rows, but estimates admit pushdown and cause the partial fact aggregate to become the hash-build input.
    Impact: The new blocking aggregate evaluates invalid fact rows that the original empty dimension build skipped. The query fails instead of returning an empty result. Checking only the SUM argument does not establish totality of the moved fact subtree.
    Evidence: A native public-SQL probe with 50,000 fact rows, two fact keys and 5,000 dimension rows reproduces this using ordinary stale statistics after ANALYZE and UPDATE. With aggPushDown=1, the query returns no rows without error; the default plan raises Error 20203 for CAST('broken' AS BIGINT). EXPLAIN confirms the build-side transition. See sum-fact-predicate-build-flip-public.txt, review_sql_fact_build_flip_test.go and checks/1794486630936944738-3.json (exit 1). Prove the entire moved fact input total, or preserve its evaluation boundary, and add a regression covering this transition.

Validation:

  • Preflight and native CPU build passed; provenance audit verified 198 native inputs and eight artifacts.

  • Go 1.27.1: 122 focused tests across six owning packages passed. All 271 Window tests passed under race detection, plus 24 focused repetitions.

  • Corrected public-SQL probes passed fused-window NULL/order oracles, grouped SUM results and DECIMAL metadata, and the activated outer-domain overflow control.

  • The final SQL counterexample confirmed the regression. validation-audit.json correlates all 13 evidence checks with commands, source fingerprints, retained logs and terminal receipts.

  • All three discussion keys were assessed exactly once; source remains unchanged.

Limitations:

  • The historical 1TB benchmark was audited for source continuity but was not rerun at the final head.

  • Broader suite and static-analysis coverage relies on the supplied head-specific CI and author reports.

@aptend
aptend force-pushed the perf/tpcds-window-fusion-20261110 branch from da5ebca to bff833f Compare November 12, 2026 14:42
@mergify

mergify Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

🚫 Left the queue · pull request dequeued

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

So far

  • ✅ Entered the queue Fri 13 Nov, 01:35 · rule main · triggered by rule Automatic queue on approval for main
  • ⏹️ Testing stopped · in place
  • 🚫 Left the queue 01:58 · d9b0b18

Reason

Pull request #32625 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.

To get back in the queue

  • Push a change if one is needed: the pull request is queued again once its queue conditions match.
  • If no change is needed, tick the box below to queue it again as it is.

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

This branch was successfully deployed

No deployments
ci — d9b0b18f Deployed Nov 13, 2026 by mergify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

dequeued kind/enhancement size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants