Skip to content

fix(aggexec): widen AVG sum state to Decimal256 for DECIMAL(29..34) - #32488

Merged
mergify[bot] merged 4 commits into
matrixorigin:mainfrom
gouhongshen:agent/issue-32429-main-8b60e705
Nov 10, 2026
Merged

mergify[bot] merged 4 commits into
matrixorigin:mainfrom
gouhongshen:agent/issue-32429-main-8b60e705

Conversation

@gouhongshen

@gouhongshen gouhongshen commented Nov 10, 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 #32429

What this PR does / why we need it:

AVG over a valid DECIMAL(34,0) column failed with 20301 Decimal128 Add overflow at 17015 identical rows of 10^34 - 1, although the exact average 9999999999999999999999999999999999.0000 fits the declared DECIMAL(38,4) result, while casting the same values to DECIMAL(35,0) succeeded.

Root cause. AvgReturnType promotes AVG over DECIMAL(p,s) to DECIMAL(p+4,s+4), which still fits Decimal128 storage for p = 29..34, so aggregate dispatch selected sumDecimal128FastExec, whose single Decimal128 sum state is checked only against the Decimal128 domain. The exact mean of any in-range group is bounded by the input magnitude and always fits the declared result, but the intermediate sum accumulator passes 2^127 - 1 after about 1.7 * 10^(38-p) rows (17015 rows at p = 34), raising the intermediate overflow. The widened-state executor existed but was only dispatched when the AVG result itself was Decimal256 (p >= 35); no executor covered the band where the result fits Decimal128 while the intermediate sum does not.

What changed.

  • pkg/sql/colexec/aggexec/sumavg2.go: the new avgDecimal128UsesWideSumState routes AVG (not SUM) over DECIMAL(29..34) to the existing generic sumAvgDecExec[types.Decimal128, types.Decimal256]; widths <= 28 keep the fast Decimal128 executor (overflow there needs roughly 17 billion rows in one group, the already-accepted bound of the fast path), and width >= 35 plus all SUM dispatches are unchanged.
  • The new narrowAvgResult finalization computes the exact mean at the declared result scale in the Decimal256 domain (decimal256AvgAtScaleSigned) and narrows it into the unchanged public Decimal128 result type through the existing representability checks. It is wired into the distinct and grouped flush paths (the grouped path emits into a fresh Decimal128 result vector and frees the wide intermediates) and the window/sliding consumers; zero-count groups stay NULL. There is no result-type, wire-format, or persisted-state change.

Issue-to-test proof.

  • The focused UT TestAvgDecimal128WideSumStateBoundary / TestAvgDecimal128WideSumStateDispatch (param decimal(34,0), result decimal128(38,4), value = 34 nines) fails on base code with the issue's exact error Decimal128 Add overflow: 168959999999999999999999999999999983104+1189999999999999999999999999999999881 at 17015 rows while the 17014-row control passes, and passes after the fix. The suite also covers grouped input (including NULL and all-NULL groups), negative inputs, partial-state merge across the reported add pair, opposite-half cancellation, DISTINCT across the boundary, window sliding, and the dispatch counterexamples (width 28 keeps the fast executor; widths 29/30/34 select the wide executor with the unchanged result type).
  • On a locally built binary, the issue's exact SQL fixture returns COUNT/MIN/MAX/SUM identical to the reported readout (17015 rows, SUM = 170149999999999999999999999999999982985) and every AVG returns 9999999999999999999999999999999999.0000, including the previously failing 17015-row SELECT AVG(d) FROM t and the promoted DECIMAL(35,0) control.
  • The new BVT pair test/distributed/cases/dtype/avg_decimal34_boundary.test/.result covers the boundary at user level (both the 17014-row and 17015-row predicates, AVG(-d), AVG(DISTINCT d), two 17015-row groups via GROUP BY mod(id,2), the promoted DECIMAL(35,0) control, and a CTAS check that the public result stays decimal(38,4)). The generated result was reviewed row-by-row against an independent arbitrary-precision oracle before comparison, and two consecutive mo-tester comparison passes were green (17/17 statements, 100%, empty error.txt).

CI coverage follow-up (commit 6150dc4). The first CI run failed the Matrixone Coverage execution / Coverage gate: modified-line coverage of sumavg2.go was 69.70% (23/33) against the 75% threshold, because the promoted branch of avgDecimal128UsesWideSumState and most narrowDecimal256Avg guard clauses had no direct tests. Five focused UTs were added covering exactly those lines: the promoted-result dispatch (widths 35..38 and the helper's promotion/width classification), the promoted boundary execution (17015 rows through the Decimal256-result path), all five invalid-result-type guards, the wide-domain scale/Div/precision overflow ladder, and a promoted DISTINCT success case. Local line-level coverage on the CI-analyzed modified lines is now 79.17% (57/72) with the package's full suite; the remaining lines are the mutually-exclusive AppendFixed/allocation error returns inside Flush.

Test commands.

  • .agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=900s -run 'TestAvgDecimal128WideSumState(Boundary|Dispatch)' ./pkg/sql/colexec/aggexec/ - base: exit 1 with the reported overflow (the 17014-row control passes); fixed: exit 0.
  • .agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=3600s ./pkg/sql/colexec/aggexec/ - exit 0 (whole package).
  • BVT: test/distributed/cases/dtype/avg_decimal34_boundary.test via mo-tester (method=genrs to generate, then two method=run comparison passes).
  • .agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=900s -run 'TestAvgDecimal128WideSumStateDispatchPromotedResult|TestAvgDecimal128WideSumStateBoundaryPromotedResult|TestNarrowDecimal256AvgRejectsInvalidResultType|TestNarrowDecimal256AvgWideningAndPrecisionOverflow|TestAvgDecimal128WideSumStateDistinctErrorPropagates' ./pkg/sql/colexec/aggexec/ - exit 0 (coverage follow-up UTs).
  • gofmt -l <changed files> clean; GOWORK=off go vet -mod=readonly ./pkg/sql/colexec/aggexec (with the documented CGo include flags) clean; golangci-lint run -c .golangci.yml --new-from-rev <merge-base> ./pkg/sql/colexec/aggexec reports 0 issues.

Residual risks.

  • AVGs over widths 29..34 now carry a 32-byte Decimal256 sum state per accumulating group instead of 16 bytes in those plans only; there is no per-row behavior change because the state is strictly wider than the argument domain.
  • Distributed partial states reuse the preexisting widened-executor wire format already shared with width >= 35 AVG; MatrixOne upgrades by shutdown/restart only, so no live-version negotiation is involved.
  • SUM capacity in the same band is unchanged and out of scope (the [Bug]: numeric aggregates must preserve DECIMAL precision and result metadata #28230 aggregate-precision umbrella tracks that work).

AVG over a DECIMAL(p,s) column with p in 29..34 promoted its result to
DECIMAL(p+4,s+4), which still fits Decimal128, so aggregate dispatch
selected sumDecimal128FastExec, whose single Decimal128 sum state
overflowed past 2^127-1 at about 1.7*10^(38-p) rows although the exact
mean always fits the declared result. At p=34, 17015 copies of 10^34-1
failed with 20301 Decimal128 Add overflow while the exact mean fits
the declared DECIMAL(38,4) result.

Route such AVG to the existing sumAvgDecExec[Decimal128, Decimal256]
and finalize through the new narrowAvgResult mode: compute the exact
mean at the declared result scale in the Decimal256 domain, then narrow
to the unchanged public Decimal128 result type. SUM, widths <= 28, and
widths >= 35 keep their existing dispatch.

Add focused UTs (boundary, grouped/distinct/window, dispatch controls)
and the avg_decimal34_boundary BVT pair with an oracle-reviewed result.

Related to matrixorigin#32429
CI coverage gate fell to 69.70% on sumavg2.go modified lines because the
new dispatch helper's promoted branch and narrowDecimal256Avg's guard
ladder had no direct tests. Add focused UTs for both.
@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 10, 2026 •

Copy link
Copy Markdown
Contributor

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

@XuPeng-SH

XuPeng-SH commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: 6150dc49dfc96a7f8654de7676674dc5ba5c99cb

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: 6150dc49dfc96a7f8654de7676674dc5ba5c99cb

Assessment: approve

The fix reuses Decimal256 aggregation and preserves Decimal128 AVG results with bounded, accounted finalization. No actionable defects found.

Model: gpt-6.1-sol / max

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

Validation:

  • Full aggexec suite passed: 3,177 test/subtest passes, no failures or skips (aggexec-full-ready.stdout.jsonl; checks/1794331458372230142-3.json).

  • Codec round-trips, window snapshots and all 27 injected flush-allocation failures passed (agg-probes.stdout.jsonl; checks/1794331743270066858-3.json).

  • All 17 SQL fixture statements passed twice through MySQL, including exact values, result metadata, CTAS type and cleanup (public-probe.stdout.jsonl; checks/1794331746576725845-3.json).

  • Formatting, independent arithmetic oracles, go vet and configured incremental lint passed. validation-audit.json reconciles receipts, logs, unchanged source and complete discussion coverage.

Limitations:

  • Local SQL replay used one embedded CN. Normal mo-tester passes were author-reported and were not independently rerun. Pending CI was not counted as a pass.

@mergify mergify Bot added the queued label Nov 10, 2026
@mergify

mergify Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

✅ Merged into main as 4c701ab at 18:49 UTC

1 h 14 min in the queue, 1 h 12 min of it CI.

So far

  • ✅ Entered the queue Tue 10 Nov, 17:35 · rule main · triggered by rule Automatic queue on approval for main
  • ✅ Passed · in place
  • ✅ Merged 18:49 · 4c701ab · squash
3 merge conditions met
  • #review-threads-unresolved = 0 · required by GitHub branch protection
  • github-review-approved · required by GitHub branch protection
  • any of · required by GitHub branch protection:
    • check-success = CI Required
    • check-neutral = CI Required
    • check-skipped = CI Required

Times in UTC · dashboard · how the merge queue works

This branch was previously deployed

1 inactive deployment
ci — 8bf8848b Deployed Nov 10, 2026 by mergify[bot]
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/L Denotes a PR that changes [500,999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants