Skip to content

fix: widen decimal arithmetic to Decimal256 - #28629

Merged
XuPeng-SH merged 41 commits into
matrixorigin:mainfrom
daviszhen:codex/decimal-arithmetic-widen
Sep 16, 2026
Merged

XuPeng-SH merged 41 commits into
matrixorigin:mainfrom
daviszhen:codex/decimal-arithmetic-widen

Conversation

@daviszhen

@daviszhen daviszhen commented Sep 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:

Fixes #28584

What this PR does / why we need it:

  • Promotes Decimal128 addition, subtraction, and multiplication to Decimal256 when the declared result requires more than 38 digits, including mixed Decimal64/Decimal128, BIT, and signed/unsigned integer operands.
  • Preserves explicit DECIMAL cast domains and canonicalizes genuinely weak decimal literals, including scientific notation, before overload selection.
  • Enforces the public 65-digit DECIMAL result limit at runtime so wider Decimal256 coefficients cannot escape under DECIMAL(65) metadata.
  • Prevents comparison optimization from narrowing a wide Decimal256 expression back to Decimal128 and keeps affine SUM rewrites compatible with widened arithmetic.
  • Adds 65-digit success and 66-digit overflow boundaries, comparison and CTAS coverage, mixed-domain and BIT/DECIMAL resolver coverage, and updates affected decimal BVT expectations.

Testing

  • go test ./pkg/container/types ./pkg/sql/plan/function ./pkg/sql/plan ./pkg/sql/compile ./pkg/sql/colexec/external -count=1
  • make build

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

@aptend aptend 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 review of exact head ac9cee1 (merge-base 9a07655). I read the linked issue, the only issue comment, and checked all review/inline/thread history (there are no prior reviews or threads), then traced the complete six-file diff through overload selection, binder-inserted casts, Decimal128/256 kernels, comparison narrowing, affine SUM rewriting, and downstream published result types. The same-type 39/40-digit cases are correctly widened and the comparison/affine adaptations are directionally sound, but three uncovered boundaries remain blocking: mixed numeric operands still stay on Decimal128, explicit casted string literals can generate an invalid width<scale implicit cast, and products beyond the public 65-digit precision can escape inside a value tagged DECIMAL(65). Native dependencies were built. Full exact-head ./pkg/sql/plan and ./pkg/sql/plan/function tests pass, as do the changed focused tests under -race. Three review-only counterexamples reproduced the findings and were removed; git diff --check is clean.

Comment thread pkg/sql/plan/function/list_operator.go Resolved
Comment thread pkg/sql/plan/base_binder.go Resolved
Comment thread pkg/sql/plan/function/list_operator.go Resolved

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

Re-reviewed the complete diff, all review history and resolved threads, plus the delta since my prior review at ac9cee1, against exact head 308db3c. The three previously reported Decimal/integer, explicit-cast/literal, and published-precision issues are closed. One exact numeric coercion domain is still omitted and reproduces the same overflow this PR is intended to eliminate. Exact-head CI is green, but it does not cover this direct BIT/DECIMAL pair.

Comment thread pkg/sql/plan/function/list_operator.go Resolved
@daviszhen

daviszhen commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor Author

Pushed 83222be, merging current upstream/main (bb358ea) and restarting CI.

The reported TestIssue28313EmptyRemoteDispatch failure was a 180-second context timeout in the full Ubuntu UT run; the Decimal change does not touch dispatch/shuffle lifecycle code. On the updated head, the exact regression passes three consecutive runs, and the affected plan/function packages pass as well.

@aptend aptend 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 completed on exact head ae7fd9949383d80de87092894865cfa619f80ab3 against exact merge-base 07fdd4ae0f80f287b93fc4b525fd296d5617abc7. I read the complete review and inline-comment history, author replies, issue discussion, and resolved/unresolved thread state; compared the delta after my prior reviewed head 308db3cc5d93480beba3182b6d984f873b58b66a; and rechecked the complete arithmetic resolver, binder casts, Decimal256 kernels/precision checks, comparison and affine-SUM consumers, Substrait boundary, tests, and BVT expectations. My remaining BIT/DECIMAL blocker is closed in code: BIT is now treated as a 20-digit exact unsigned domain for the widening decision, both operand orders produce Decimal256 casts, and +/* publish 39/58-digit Decimal256 results. I independently built the plan-level BIT(64)/DECIMAL(38,0) + and * shapes and confirmed their physical arguments/results are Decimal256. The earlier mixed integer/decimal, explicit-cast/weak-literal, and 65-digit runtime-boundary findings remain closed. Validation on this exact head: full pkg/sql/plan, pkg/sql/plan/function, and pkg/sql/plan/substrait suites pass with repository CGO/third-party artifacts; git diff --check passes; all required CI checks are green. No remaining blocking issue found.

@daviszhen

Copy link
Copy Markdown
Contributor Author

Resolved the latest main conflict at 0a490af after preserving the remote branch updates and merging upstream/main through 2ea4ec2.

The list_operator conflict now retains both dispatch layers: main mixed signed/unsigned integer domain handling runs first, then this PR applies widened Decimal256 operand selection for decimal arithmetic. This also integrates main Decimal256 high-scale multiplication coverage without dropping either behavior.

Local validation passed for container/types, plan/function, plan, compile, and external, followed by the complete native-provenance-aware make build.

@mergify

mergify Bot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-09-15 08:22 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • 🟠 Checks running · in-place
  • 🚫 Left the queue — 2026-09-15 09:01 UTC · at 47a700176d728d2dadbe2d93feebb4fcd6e9ff9b

This pull request spent 39 minutes 36 seconds in the queue, with no time running CI.

Waiting for any of
  • check-neutral = CI Required
  • check-skipped = CI Required
  • check-success = CI Required
All conditions

Reason

Pull request #28629 has been dequeued

Queue conditions are not satisfied:

  • #changes-requested-reviews-by<=0

Hint

You should look at the reason for the failure and decide if the pull request needs to be fixed or if you want to requeue it.
If you do update this pull request, it will automatically be requeued once the queue conditions match again.
If you think this was a flaky issue instead, you can requeue the pull request, without updating it, by posting a @mergifyio queue comment.

Requeued — the merge queue status continues in this comment ↓.

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

[P2] Correct the newly accepted wrapped decimal multiplication result.

At test/distributed/cases/dtype/decimal.result:1306-1310, this PR replaces an overflow with three successful values that are mathematically incorrect. The fixture declares col2 DECIMAL(19,0), and its first value is 1235467899687894561. For:

SELECT col2 * -2733892455124775.7851878942123454 FROM decimal19;

the first exact product is:
-3377636369505588272411432821735887.9920303797133694

but the new expected result is:
-12929400140562083461.4885988496007550

The exact coefficient has 50 digits and fits the advertised DECIMAL(51,16), so this is not an allowed overflow or rounding difference. The expected value exactly equals col2 multiplied by the signed low 64 bits of the literal's scaled coefficient: int64(-27338924551247757851878942123454) = -104651850070959550, divided by 10^16. The other two newly accepted rows follow the same truncated coefficient.

Please correct the oracle using independent arbitrary-precision arithmetic and verify the exact-head SQL execution. If execution produces the checked-in values, fix the constant conversion/widened execution path before accepting the result. Add a focused positive/negative wide-fractional-literal case and literal-versus-typed-column control; resolver/type-only and scale-zero multiplication tests cannot catch this.

Reviewed all 16 changed files and traced original-domain widening, explicit-cast/weak-literal handling, physical argument casts, Decimal256 precision checks, comparison/affine consumers and tests. Prior mixed integer/BIT-domain fixes are retained. This finding is independently proven against the checked-in fixture/oracle with exact integer arithmetic; I have not run a fresh SQL reproduction or established the precise runtime truncation site, and am not claiming that a generated expected file proves runtime behavior. Current-head UT and BVT were still running at submission preflight. No other confirmed blocker found.

@daviszhen

Copy link
Copy Markdown
Contributor Author

Thanks — confirmed on exact head: the checked-in values were the low-64-bit wrapped products.

Root cause was in the Decimal256 fast-path classifiers, not in literal parsing or Decimal128→Decimal256 casting. d256AllFitInt64 mixed ^ and | without grouping the per-limb comparisons. Because those operators have the same precedence and associate left-to-right in Go, the all-ones sign-extension limbs of a wide negative value could cancel the non-zero mismatch. The value was then incorrectly sent through the int64 multiplication tier, which consumed only B0_63. d256AllFitInt32 had the same latent expression and is fixed as well.

Fixed in c9bdffc:

  • parenthesized/isolated each upper-limb sign-extension mismatch before OR-reduction;
  • corrected all three decimal19 oracle rows using independent arbitrary-precision arithmetic;
  • added executing positive/negative wide-fractional-literal SQL regressions;
  • added literal-scalar versus typed-column vector controls for both signs;
  • added a typed DECIMAL(32,16) BVT column control alongside the literal cases.

Exact-head validation:

  • pkg/sql/plan/function: full package PASS;
  • pkg/sql/plan: full package PASS;
  • focused exact SQL bind/execute now returns -3377636369505588272411432821735887.9920303797133694 for the reported first row;
  • git diff --check: PASS.

@daviszhen

Copy link
Copy Markdown
Contributor Author

Resolved the conflict with current main (091825aac2).

Conflict decision in pkg/sql/plan/substrait/tpch_test.go:

  • preserved the Decimal256 arithmetic fallback coverage from this PR;
  • included Q6 introduced by Decimal256 SUM on main;
  • retained exact type eligibility assertions for Q6/Q11, while checking the earlier expression rejection produced by widened arithmetic in the other affected queries.

New exact head: 0aba14a1b0fff6928e5e4097bfe0e4921eea8251

Validation passed:

  • make config
  • go test ./pkg/sql/plan ./pkg/sql/plan/function ./pkg/sql/plan/substrait -count=1 (with the resolved TPCH assertion rerun after refinement)

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

No blocking finding at this revision.

Compared the patch series against my previous reviewed head: all nine non-merge patches are unchanged after the main merge. Rechecked the decimal widening/cast/precision boundaries, comparison non-narrowing, affine-result restoration and changed binder surroundings. The prior full source/test/BVT review remains applicable, and exact-head CI is green.

Existing review and CI evidence reused; no new local test execution or performance claim.

@mergify

mergify Bot commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-09-16 14:28 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • 🟠 Checks running · in-place
  • 🚫 Left the queue — 2026-09-16 14:53 UTC · at 87c918d7857e27b78737ebc71cc5d230c599b245

This pull request spent 25 minutes 38 seconds in the queue, with no time running CI.

Waiting for any of
  • check-neutral = CI Required
  • check-skipped = CI Required
  • check-success = CI Required
All conditions

Reason

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

Hint

You should look at the reason for the failure and decide if the pull request needs to be fixed or if you want to requeue it.
If you do update this pull request, it will automatically be requeued once the queue conditions match again.
If you think this was a flaky issue instead, you can requeue the pull request, without updating it, by posting a @mergifyio queue comment.

Tick the box to put this pull request back in the merge queue (same as @mergifyio queue).

  • Requeue this pull request

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/L Denotes a PR that changes [500,999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: DECIMAL arithmetic does not widen results beyond Decimal128

5 participants