Skip to content

fix(types): preserve Decimal128 precision and single rounding - #29853

Merged
XuPeng-SH merged 9 commits into
matrixorigin:mainfrom
MatrixAdventurer:fix/decimal128-leading-zero-precision
Oct 11, 2026
Merged

XuPeng-SH merged 9 commits into
matrixorigin:mainfrom
MatrixAdventurer:fix/decimal128-leading-zero-precision

Conversation

@MatrixAdventurer

@MatrixAdventurer MatrixAdventurer commented Oct 11, 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:

issue #29841

Fixes #29841

What this PR does / why we need it:

Decimal128 parsing counts significant digits correctly and rounds exactly once to the declared destination scale. The existing parser retains the coefficient and first discarded digit for destination parsing; final range checking remains after rounding. Exact-tail scanning now stays in the existing token loop, so accepted spaces/plus before an exponent cannot hide that exponent, and invalid trailing tokens are rejected. Public Parse128 keeps its existing precision-limit rounding mode.

UT and INSERT/CSV/JSONLINE regressions use exact text oracles for leading zeros, real 38-significant-digit tails, both signs, exponent separators, carry and overflow. Three existing variance-suite INSERTs that round beyond DECIMAL(38,0) remain rejection controls; only their affected result blocks are corrected, including the missing extra row and precision metadata. Aggregate error-class oracles remain intact.

Validation

Full normal/race tests for pkg/container/types, pkg/sql/plan, pkg/sql/plan/function, pkg/sql/colexec/external and pkg/sql/jsonvalue; incremental gofmt/vet/molint/configured golangci-lint all pass on the final source. An independent Python Decimal ROUND_HALF_UP oracle checks 4,320 combinations and detects the original tail/exponent defect.

Freshly built final CPU service: 426/426 SQL comparisons (43 precision + 242 VAR_POP + 141 VAR_SAMP), zero ignored/failed/abnormal, using the repository-recommended nometa comparison mode. The precision case also passed full metadata comparison before the scan-only optimization; unchanged metadata is reused. A separate full-metadata attempt encountered unchanged variance metadata/comparison-mode differences and is not claimed as passed. Max38digits+.4 is valid; signed .5/.7 overflow is rejected without changing target rows, and a later valid INSERT succeeds.

Rebased onto main 42d42546fd2c2b2449cb81cea47f81d300139753 (the requested base snapshot). Current GitHub CI is reported separately from local validation.

Local successful-input microbenchmarks (original author parser → final parser, linux/amd64, Go 1.27.1, no concurrent builds): 123.45 46.99→48.24 ns, 0.01 22.71→24.10 ns, 44-character tail 306.9→329.1 ns, 1,043-character tail 651.8→667.5 ns. All four remain 0 B/op and 0 allocs/op. Reusing the existing digit-span scan eliminates the earlier repair's ~4× long-tail cost. These are parser measurements, not whole-SQL throughput claims.

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

@CLAassistant

CLAassistant commented Oct 11, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@MatrixAdventurer

Copy link
Copy Markdown
Contributor Author

End-to-end verification

Setup: built mo-service (make build) from main (d7752ff) and from this branch, launched single-node with ./mo-service -launch etc/launch/launch.toml, client mysql -h127.0.0.1 -P6001 -uroot -p111.

Table d(id int primary key, d decimal(38,38)), values given as strings:

Scenario main this PR
INSERT '0.'+37×0+'1' stored 0.000…000 (precision lost) 0.000…001
INSERT '0.'+38×9 / '-0.'+38×9 ERROR 20301 beyond the range stored exactly
LOAD CSV of the 4 values (incl. .000…01) ERROR 20101 invalid Decimal128 4 rows, exact
LOAD JSONLINE (object) of the 3 values ERROR 20101 3 rows, exact
LOAD CSV with only the tiny value 0.000…000 0.000…001

BVT (mo-tester run.sh -n -g): test/distributed/cases/load_data 1234 total / 0 failed, cases/dtype 7744 total / 0 failed. The numbers match the main baseline.

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

Reviewed head b89fe0856eacf56c52b828669374423ca8068bb0 against base/merge-base 4022729da24d71b082c22b52aaed3faba2b77ea5. Requesting changes for the confirmed numeric-result regression in the inline comment.

The responsibility placement is reasonable: existing string-ingestion consumers already delegate to ParseDecimal128/Parse128. This is a focused parser fix, with no new state machine, storage, allocation owner, or execution path. The design gap is its interaction with the existing downstream scale conversion: changing the precision boundary must also preserve the final rounding contract. Implementation is +8 lines, tests +44, documentation unchanged; there are no committed SQL/BVT changes. The new unit test is small and useful but does not cover excess fractional precision combined with a smaller destination scale.

Validation at the reviewed head:

  • The PR's new regression test passes. The existing pkg/container/types suite passes with reviewer-only probes excluded.
  • Independent exact-rational probes: all 10 cases pass with the base parser; four cases fail on the head (positive/negative 145 and 149 tails).
  • Real CSV/JSONLINE reader probes: all six pass with the base parser and fail on the head. These assert produced column vectors; they are component ingestion checks, not a claim that I ran a rebuilt service end to end.
  • I read the author's newly posted end-to-end verification. It supports closure of the original DECIMAL(38,38) examples, but its scenarios do not select this smaller-scale counterexample. Please preserve the public regression in the suite alongside the fix rather than relying only on the manual run. There were no earlier substantive review threads to resolve.

Performance is not a separate blocker based on current evidence. Local darwin/arm64, Go 1.27.1 microbenchmarks of ParseDecimal128(...,38,2) (five 300 ms samples, baseline also repeated after head) showed 1234567.89 at roughly 44–47 ns on base versus 50 ns on head; 0.01 and the long-leading-zero input improved. All measured cases allocate 0 bytes. This measures parser cost only and does not establish a TP throughput change.

The local probes used the repository CGo wrapper with freshly built, provenance-checked native artifacts in an isolated worktree. Baseline comparison overlaid only decimal.go from the recorded base, keeping the same test inputs, oracle, dependencies, and native artifacts. No production changes were made. At the final CI check there were no failed checks, but Ubuntu UT was still running.

Comment thread pkg/container/types/decimal.go Resolved
@XuPeng-SH XuPeng-SH changed the title fix(types): do not count integer leading zeros toward Decimal128 precision fix(types): preserve Decimal128 precision and single rounding Oct 11, 2026
@XuPeng-SH
XuPeng-SH force-pushed the fix/decimal128-leading-zero-precision branch from df8876f to 8d0cc3f Compare October 11, 2026 09:55

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

Final review reconciled on 8d0cc3f. The earlier findings have been addressed, with replies on each original thread. Full affected-owner normal/race tests and incremental SCA pass; public SQL evidence and hardware/comparison-mode limits are in the updated PR description. Design and final overall review used an explicitly selected gpt-6.1-sol/xhigh CLI session. Disclosure: I contributed the follow-up changes and rebase; the separate model reviewed the complete final change map. Newly triggered GitHub CI remains separate from local validation.

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

Supplementary deep review of 8d0cc3fccaebdbf545f297916a185d0a70be1419. I also participated in the previous repair round; this is a follow-up review of the complete implementation/test/result changes, not an independent third-party certification.

No new material source blocker found after tracing the shared coefficient parser, tail grammar, final rounding/range checks and planner/ingestion consumers. Exact-tail mode uses the existing token loop and final caller rounding; it does not introduce another pre-scan grammar or storage representation. The first-dropped-digit flag is necessary to retain a dropped zero across later spans. Signed rounding/overflow, leading zeros, accepted exponent spellings, invalid tails and extreme exponents are covered by the existing regression/reference oracle.

Reused exact-head five-package normal/race/configured incremental SCA passes, 4320 independent reference-oracle cases and the final 426/426 SQL comparison without metadata for the broader variance group. The full-metadata attempt was not all green: it has 56 other metadata discrepancies. The three changed overflow INSERT/readback/result-header blocks themselves passed full-metadata comparison. Newly rebuilt this exact head and ran the focused precision case twice on one service with full metadata: 43/43 each, zero failed/ignored/abnormal, teardown verified between runs.

The parser keeps O(n) time/constant state and zero allocations in the controlled microbenchmarks; the 1043-character case was about 652→668 ns versus the author baseline after removing the earlier large tail overhead. This is not a whole-SQL throughput claim. The implementation/tests and three stale variance-result corrections are proportionate to the changed rounding contract. GitHub checks remain in progress.

@mergify

mergify Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-10-11 11:19 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • 🟠 Checks running · in-place
  • 🚫 Left the queue — 2026-10-11 13:37 UTC · at acfe78e4099586327970e285ce9c66d430bf52d9

This pull request spent 2 hours 17 minutes 58 seconds in the queue, with no time running CI.

Reason

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

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

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

  • Requeue this pull request

@XuPeng-SH
XuPeng-SH merged commit 485bdf6 into matrixorigin:main Oct 11, 2026
@mergify mergify Bot added dequeued and removed queued labels Oct 11, 2026
XuPeng-SH pushed a commit that referenced this pull request Oct 11, 2026
## What type of PR is this?

- [ ] API-change
- [x] BUG
- [ ] Improvement
- [ ] Documentation
- [ ] Feature
- [ ] Test and CI
- [ ] Code Refactoring

## Which issue(s) this PR fixes:

issue #29883

Fixes #29883

## What this PR does / why we need it:

This is the Decimal256 counterpart of #29853 (Decimal128). Production
change is in `pkg/container/types/decimal.go` only. It is based on
`main` and independent of #29853: it adds a separate `parse256` and
touches no Decimal128 code.

**Bug.** `ParseDecimal256` called `Parse256`, which rounds at its
76-digit limit, and then rounded again to the column scale. A carry from
the first rounding changes the second one. For example, in
`DECIMAL(65,64)`, LOAD CSV and LOAD JSONLINE store `0.<63
zeros>14999999999995` as `2e-64`; the correct result is `1e-64`.
`Parse256` also had two smaller problems:
- leading zeros of `0.xxx` counted toward the 76 digits;
- an exponent after the dropped digits was ignored, because the loop
`break`s at the limit.

**Fix** (same approach as #29853):
- `Parse256(x)` now wraps `parse256(x, exactTail=false)`. Its behaviour
is unchanged for existing callers, except that leading zeros are
skipped.
- `ParseDecimal256` uses `exactTail=true`:
  - nothing is rounded at the 76-digit limit;
  - the first dropped digit is returned;
  - the value is rounded once to the column scale (half away from zero).
- Remaining dropped digits are skipped, and a following `e`/`E` exponent
is still applied.

## Verification

**Unit tests** (`decimal256_parse_test.go`):
- `TestParseDecimal256RoundsOnceWhenDownscaling`: issue values,
negatives, `e0`/`E+0`, carry chains, exponent after dropped digits.
- `TestParseDecimal256MatchesExactRoundingRandomized`: 20k random
inputs, a third of them with carry-prone `4999…` tails, compared against
exact `big.Rat` rounding.
- `TestParse256LeadingZerosDoNotConsumePrecision`.

On main, the first two fail (`…0002` vs `…0001`; random case
`-96552…392.4999…` at scale 0) and the third fails with scale 75 vs 76.
All three pass with the fix. `go test` passes for
`./pkg/container/types/`, `./pkg/sql/colexec/external/` and
`./pkg/sql/plan/function/`, and `go vet` is clean.

**End to end:** `mo-service` built from main (same
`decimal.go`/`external` code as this base) and from this branch, each
run single-node. Table is `DECIMAL(65,64)` and the value is `v = 0.<63
zeros>14999999999995` (79 digits). Exact result: `1e-64`.

| path | main | this PR |
|---|---|---|
| INSERT `'v'`, `'-v'`, `'ve0'`, numeric literal | `…0001` (correct) |
`…0001` |
| CAST(`'v'` AS DECIMAL(65,64)) | `…0001` | `…0001` |
| LOAD CSV `v`, `-v`, `ve0` | `…0002`, `-…0002`, `…0002` | `…0001`,
`-…0001`, `…0001` |
| LOAD JSONLINE `v`, `-v`, `ve0` | `…0002`, `-…0002`, `…0002` | `…0001`,
`-…0001`, `…0001` |

**SQL regression:** new
`test/distributed/cases/load_data/decimal256_text_rounding.sql` plus
`.result` and the CSV/JSONLINE fixtures. It covers INSERT, CSV, JSONLINE
and CAST, and includes a non-double-rounding control (`…15` → `…2e-64`).
Values are rendered as `concat('d=', d)` because mo-tester compares
numbers with a tolerance. The `.result` was generated by mo-tester
against this build.
- On main: 16 total, 2 FAILED (the CSV and JSONLINE selects).
- On this PR: 16/16 pass.

**BVT on this build:**
- `load_data`: 1250 total, 0 failed (2 ignored)
- `dtype`: 7744 total, 0 failed (32 ignored)

---------

Signed-off-by: MatrixAdventurer <[email protected]>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>

This branch was previously deployed

1 inactive deployment
ci — acfe78e4 Deployed Oct 11, 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/M Denotes a PR that changes [100,499] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Decimal128 text parser counts leading zero and loses DECIMAL(38,38) precision

4 participants