Skip to content

fix(aggregate): align exact AVG types with MySQL - #27873

Merged
XuPeng-SH merged 15 commits into
matrixorigin:mainfrom
daviszhen:codex/24436-avg-exact-type
Sep 5, 2026
Merged

XuPeng-SH merged 15 commits into
matrixorigin:mainfrom
daviszhen:codex/24436-avg-exact-type

Conversation

@daviszhen

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • Bug

What this PR does / why we need it

Continues #24436 by aligning the public AVG contract for exact numeric inputs with MySQL instead of applying a CTAS-only schema patch.

  • Exact integer inputs now return DECIMAL with four fractional digits, e.g. AVG(INT) -> DECIMAL(14,4) and AVG(BIGINT) -> DECIMAL(23,4).
  • DECIMAL inputs use precision + 4 and scale + 4, e.g. AVG(DECIMAL(20,6)) -> DECIMAL(24,10).
  • Results that exceed DECIMAL128 precision are promoted to DECIMAL256, capped at MySQL's precision/scale limits, so high-precision ordinary and window AVG no longer overflow in the Decimal128 accumulator.
  • FLOAT/DOUBLE AVG remains DOUBLE.
  • Ordinary aggregates, window aggregates, CTAS, and protocol/JDBC metadata share the same return-type rule.
  • VARIANCE/STDDEV keep their existing return type and behavior.

This fixes both metadata and value semantics. For example, AVG over integer values 1, 2, 4 now returns 2.3333 rather than a DOUBLE approximation.

SUM precision rules are intentionally out of scope and will be handled separately.

Which issue(s) this PR fixes

Related to #24436

Special notes for your reviewer

The Decimal128-to-Decimal256 promotion is required for inputs such as DECIMAL(38,19): clamping the result to DECIMAL128 would either discard integer capacity or lose the required four additional fractional digits.

Testing

  • make build
  • go test ./pkg/sql/colexec/aggexec -count=1
  • go test ./pkg/sql/plan ./pkg/sql/colexec/window -count=1
  • 23 affected distributed BVT case files with current mo-tester (-g -n), including func_aggr_avg, numeric/decimal/decimal256, prepared aggregates, grouping, DISTINCT, CTAS, and the full window case
  • Local mo-service checks for ordinary AVG, window AVG, CTAS schema, and DECIMAL(38,19) promotion

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

@daviszhen

Copy link
Copy Markdown
Contributor Author

已更新分支并处理 failing checks 与代码冲突:

  • 修复 YEAR AVG 使用 types.MoYear 向量却按 int16 读取导致的类型检查 panic;同时保留 YEAR SUM 的 int64 累加路径。
  • fulltext BM25 的内部 AVG(pos) 显式 CAST 为 DOUBLE,保持 runCountStar 的 float64 读取契约。
  • 更新 func_arrayagg 的 AVG DECIMAL 结果精度。
  • 合并最新 upstream/main,并按当前 Decimal128 溢出用例解决 window.result 冲突。

本机定向 Go 测试受 macOS 原生依赖头文件缺失影响,已由 CI 重新验证。

@daviszhen

Copy link
Copy Markdown
Contributor Author

Addressed in commit adde979. Reconciled the #27869 overflow fixtures with the exact AVG contract: DECIMAL(38,10) now uses the required DECIMAL(42,14) Decimal128-to-Decimal256 path, so promoted boundary cases and window/BVT expectations are successful results rather than obsolete Decimal128 overflow errors. Updated the PK-group-elimination assertions accordingly, retained narrow-target decAvg error coverage, and kept Decimal256 declared-precision overflow coverage.

@matrix-meow matrix-meow removed the size/M Denotes a PR that changes [100,499] lines label Aug 31, 2026

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

Deep re-review of exact head af506cc077f9d29ce9ceee727cce8d5ed78090cd against base c46d897e9645b80178568ef0783dd8e99e527222, including the complete AVG type/execution change, the increment after my prior requested-changes head adde9798bc69, ordinary/DISTINCT/window/distributed merge paths, negative rounding, Decimal128-to-256 promotion, high-scale inputs, allocation/error cleanup, internal consumers, and constant-expression counterexamples.

The four prior blockers are materially addressed: exact AVG now rounds once at the declared scale; valid high-scale Decimal128 input is promoted without truncating its source scale; direct literal metadata is value-sensitive; and the common INT32 path has a dedicated production fast finalizer plus benchmark coverage. I found no new lifecycle, deadlock, or common-path performance blocker. One correctness/type-system boundary remains:

  1. [P1][correctness/metadata] Integer constant-expression precision is unbounded, but integer AVG is always declared as Decimal128. avgIntegerConstantPrecision recursively adds precision for multiplication/addition (base_binder.go:3636-3665) and writes it directly into the integer argument type. AvgReturnType then unconditionally returns DECIMAL128(precision+4,4) for every integer OID (sumavg2.go:35-40) without the Decimal128 limit/promotion used by decimal inputs.

    A valid, non-overflowing counterexample is:

    SELECT AVG(0 * 100000000 * 100000000 * 100000000 * 100000000);

    The expression value is exactly zero, while the new AST rule derives precision 1+9+9+9+9 = 37, so AVG is declared as DECIMAL128(41,4). That width is not representable by the Decimal128 public type; CTAS and protocol metadata can therefore expose an invalid schema even though execution data is trivial. Addition/cancellation chains can reach the same boundary.

    This must be closed coherently, not by changing only the return OID: flushExactAvg currently states that native integer AVG always returns Decimal128, and its non-Decimal128 branch calls decAvg[Decimal128], which rejects a Decimal256 result type (sumavg2.go:873-917). Define a bounded type rule for integer constant expressions and make planner, factory/state, ordinary/DISTINCT/window finalization, CTAS, and protocol metadata agree. Add boundary tests immediately below/above precision 38, including a zero/cancellation expression so value overflow cannot mask the metadata defect.

Validation note: exact-head substantive CI is terminal green and current main has no post-base overlap in the touched production paths. Focused local compilation was blocked by this isolated worktree's missing third-party usearch.h while building its exact CGo prerequisite, so I do not claim a local test pass; the blocker above follows directly from the exact production type equations and existing test-confirmed integer-expression path.

@daviszhen

Copy link
Copy Markdown
Contributor Author

Addressed the remaining wide integer constant-expression AVG boundary in commit 0d4d0c90ef:

  • Bound integer constant-expression precision to the public Decimal256(65,4) AVG contract.
  • Promote AVG from Decimal128 to Decimal256 at input precision 35 (result precision 39), while keeping precision 34 at Decimal128(38,4).
  • Added Decimal256 native-integer finalization for ordinary and DISTINCT paths; the Decimal256 state factory is selected for wide int64/uint64 AVG, and window finalization remains consistent.
  • Added zero-expression CTAS metadata coverage for precision 34/35/37 and execution coverage for ordinary/DISTINCT/window modes.

Validation:

  • go test ./pkg/sql/colexec/aggexec ./pkg/sql/plan -count=1
  • go test ./pkg/sql/colexec/window -count=1
  • go vet ./pkg/sql/colexec/aggexec ./pkg/sql/plan
  • make build (passed; only macOS duplicate-library linker warnings)

@daviszhen

Copy link
Copy Markdown
Contributor Author

Follow-up: the branch was amended to f29e4b2064 to clarify the AVG precision comment; the implementation and validation described above are unchanged.

@daviszhen

Copy link
Copy Markdown
Contributor Author

Follow-up for the coverage check: commit 14557369db adds coverage for the wide integer AVG Decimal256 native finalizer (int32 ordinary/DISTINCT/window) and the planner precision cap above 61 digits. The previous 74.01% modified-line coverage failure is addressed; local aggregate/plan tests pass.

@daviszhen

Copy link
Copy Markdown
Contributor Author

CI run 33646744442 is now green. The Ubuntu UT, SCA, both BVT jobs, UT Coverage, and final Coverage merge all passed on head 14557369db. The previous 74.01% coverage failure is resolved.

@XuPeng-SH

Copy link
Copy Markdown
Contributor

当前 PR 与最新 main 存在 merge conflict,暂无法进入 review 队列。请 rebase 最新 main 并解决冲突后重新 push,完成后我再继续 review。

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/bug Something isn't working size/XL Denotes a PR that changes [1000, 1999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants