Skip to content

fix(column): return error instead of panic on Decimal/BigInt overflow - #1857

Merged
must108 merged 19 commits into
ClickHouse:mainfrom
wucm667:fix/decimal-panic
Sep 10, 2026
Merged

must108 merged 19 commits into
ClickHouse:mainfrom
wucm667:fix/decimal-panic

Conversation

@wucm667

@wucm667 wucm667 commented May 7, 2026 •

Copy link
Copy Markdown
Contributor

fix(column): return errors on Decimal/BigInt overflow

Inserting an out-of-range value into Decimal32/Decimal64/Decimal128/Decimal256 or Int128/UInt128/Int256/UInt256 previously could panic in math/big.FillBytes or silently truncate a scaled decimal coefficient.

Changes

  • Validate signed and unsigned storage-width limits before encoding, including signed values below the minimum and negative unsigned values.
  • Return contextual overflow errors through Append, AppendRow, and batch APIs without classifying a supported conversion as unsupported.
  • Use the same range-validation path for all decimal storage widths.
  • Add integration regression coverage for native and database/sql, over TCP and HTTP, covering decimal overflow/silent-corruption boundaries and signed/unsigned BigInt boundaries.

Fixes #1849

When inserting values that exceed the range of Decimal128/256 or
Int128/UInt128/Int256/UInt256 columns, the driver previously panicked
with 'math/big: buffer too small' in bigIntToRaw(), killing the caller
goroutine with no way to recover.

Changes:
- bigIntToRaw now uses deferred recover to catch FillBytes panics and
  returns a proper error instead
- Added explicit signed range check: positive values exceeding
  2^(n*8-1)-1 are caught before FillBytes (which treats values as
  unsigned and won't panic for these)
- Decimal32/64 now check for overflow before silent IntPart() truncation
- append() in both BigInt and Decimal now propagate errors through
  Append() and AppendRow()
- Added unit tests for all four Decimal sizes and BigInt overflow/valid
  boundary cases

Fixes ClickHouse#1849

Signed-off-by: wucm667 <stevenwucongmin@gmail.com>
@github-actions

Copy link
Copy Markdown
Contributor

Summary

The PR replaces a math/big panic with explicit error returns when inserting big-int / decimal values that overflow Int128/256, UInt128/256, and Decimal32/64/128/256 columns (fixes #1849). The approach is mostly sound: errors are threaded through Append / AppendRow, positive signed overflow is pre-checked via BitLen, Decimal32/64 no longer silently truncate via IntPart(), and a deferred recover catches any remaining FillBytes panic. However, the negative signed bounds check is missing, which leaves a wide range of values that silently produce wrong encodings rather than errors. Regression coverage also doesn't follow the project layout (tests/issues/).

Must fix

  • Negative signed overflow is silently corrupted, not caught. In lib/column/bigint.go the explicit overflow check only fires when v.Sign() >= 0. For negative values in (-2^n, -2^(n-1) - 1] (e.g. Int128 values from -2^128 + 1 down to -2^127 - 1), new(big.Int).Not(v).FillBytes(dest) succeeds — BitLen(Not(v)) == n exactly fits n bytes — so neither the explicit check nor the recover catches it. Concretely: appending -2^127 - 1 to an Int128 silently encodes as 2^127 - 1. Add a symmetric check on Not(v):

    if signed && v.Sign() < 0 {
        if new(big.Int).Not(v).BitLen() > len(dest)*8-1 {
            return fmt.Errorf(\"value overflows %d-byte signed buffer\", len(dest))
        }
    }

    This catches everything below -2^(n-1) cleanly (including -2^(n-1) - 1), while -2^(n-1) (the valid minimum) has Not(v).BitLen() == n-1 and passes.

  • Missing regression test in tests/issues/. Per .claude/CLAUDE.md, bug-fix regression tests live in tests/issues/issue_<N>_test.go and exercise a real ClickHouse instance via testcontainers. The PR adds only lib/column/decimal_overflow_test.go, which tests the column primitive in isolation and doesn't verify that Batch.Append / Batch.AppendStruct actually returns the error (rather than panicking) at the public API boundary. Add tests/issues/1849_test.go covering: native (clickhouse.Open) + database/sql (OpenDB), TCP + HTTP protocols, and at least one negative-overflow case (which currently silently corrupts — see above).

Should fix

  • Decimal.append and BigInt.append wrap errors inconsistently. BigInt.append returns a ColumnConverterError{Op: \"Append\", To: chType, From: \"big.Int\", Hint: err.Error()}, but Decimal.append returns a bare fmt.Errorf(\"value overflow: %s exceeds Decimal128 range\", v.String()). The driver elsewhere relies on ColumnConverterError for structured failure info. Also, ColumnConverterError's message template is \"converting X to Y is unsupported\" — accurate for type mismatches, but slightly misleading for an overflow on a supported conversion. Consider either using ColumnConverterError consistently in both, or introducing a dedicated overflow error and using it in both places.

  • recover() used for normal control flow. bigIntToRaw defers a bare recover() that converts any panic to \"value overflows %d-byte buffer\". If a future change panics for an unrelated reason inside the function, the user will get a confusing "overflows" error instead. Once the negative bounds check above is in place, every overflow case is caught by the explicit BitLen guards and the recover becomes unnecessary — prefer removing it. If kept defensively, at least type-assert the recovered value and only translate the expected \"math/big: buffer too small\" message.

  • Tests miss the silent-corruption window. TestBigIntValidValuesNoError covers ±2^127 (valid boundary) but no test asserts an error for the just-past-min case (e.g. v = -2^127 - 1). Add the negative-overflow case alongside the positive one — without it, the must-fix issue above will silently regress in the future.

  • Protocol / API coverage. The checklist requires test coverage on both native TCP and HTTP, and on both the clickhouse_native and std surfaces. The new tests are column-level unit tests only.

Nits

  • nit: lib/column/decimal_overflow_test.go uses decimal.NewFromFloat(21474836.48) / decimal.NewFromFloat(92233720368547758.08) — float64 cannot represent those values exactly, so the test depends on rounding direction. Prefer decimal.NewFromString(\"21474836.48\") for boundary cases.
  • nit: lib/column/decimal.go Decimal32 branch — i64 := bi.Int64(); ... uint32(i64) is a redundant intermediate; uint32(bi.Int64()) is enough.
  • nit: error messages "value overflow: %s exceeds Decimal128 range" mix a colon with prose and use the ClickHouse type name unquoted. Per project style (CLAUDE.md), ClickHouse SQL type names in prose are wrapped in backticks; for error strings consider \"value %s overflows decimal128 range\" (lowercase, no colon, consistent with the rest of the package).
  • nit: lib/column/bigint.go:182 still wraps the value as new(big.Int).Set(v) before passing to bigIntToRaw. With the new implementation already using new(big.Int).Not(v) (no mutation), the defensive copy is unnecessary on the positive path.

Verdict

Request changes — the negative-overflow silent-corruption case (Must fix #1) needs to land before merge; the rest are smaller cleanups.

wucm667 and others added 3 commits May 11, 2026 21:05
- Add negative signed overflow check in bigIntToRaw: values in
  (-2^n, -2^(n-1)-1] no longer silently encode incorrectly
- Remove defer/recover since explicit BitLen guards now catch
  all overflow cases
- Remove unnecessary new(big.Int).Set(v) defensive copy
- Fix error message style: lowercase, no colon, consistent
  with project conventions
- Use NewFromString instead of NewFromFloat for exact boundary
  test values
- Add TestBigIntNegativeOverflowReturnsError
- Add regression test tests/issues/issue_1849_test.go

Signed-off-by: wucm667 <stevenwucongmin@gmail.com>
The regression test called batch.AppendRow which does not exist on the
Batch interface (it belongs to BatchColumn), causing a build failure
across all CI matrix jobs.

Rewrite the test to:
- Use batch.Append (the correct Batch method)
- Cover both native TCP and HTTP protocols
- Cover the database/sql surface via Begin/Prepare/Exec
- Test positive and negative overflow for both Decimal128 and Int128
@github-actions

Copy link
Copy Markdown
Contributor

Summary

Replaces a panic (math/big: buffer too small from FillBytes) and silent truncation in the Decimal/BigInt column writers with explicit range checks. bigIntToRaw now validates the value fits the destination width before calling FillBytes, and Decimal32/Decimal64 paths verify the scaled coefficient before the lossy int64→uint32/uint64 cast. Errors propagate up through append → Append/AppendRow. The approach is sound — preventing the panic with upfront bit-length checks is cleaner than defer recover(). There is also a latent-bug fix: the previous bigIntToRaw called v.Not(v).FillBytes(dest), mutating the caller's *big.Int; the workaround in BigInt.append (new(big.Int).Set(v)) is no longer needed because bigIntToRaw now uses new(big.Int).Not(v) internally.

Should fix

  • PR description is out of sync with the code. The description says bigIntToRaw "now uses deferred recover to catch FillBytes panics," but the implementation uses range checks instead (which is the better choice). Update the description so reviewers and the merged commit history don't claim behavior that isn't there.
  • Inconsistent error wrapping between BigInt and Decimal paths. BigInt.append wraps overflow errors in &ColumnConverterError{Op, To, From, Hint}; Decimal.append returns a bare fmt.Errorf("value %s overflows decimal128 range", ...). Callers that type-assert to *ColumnConverterError (a public, documented type) will get structured info from one path and a flat string from the other. Either wrap the Decimal errors in ColumnConverterError too, or %w-wrap the inner bigIntToRaw error so errors.Is/As works. Including the offending value (as the Decimal path does via v.String()) is a nice touch — consider doing the same for BigInt.
  • No test coverage for the unsigned (UInt128/UInt256) branches you added. bigIntToRaw grew two new code paths — "negative value not allowed for unsigned type" and the unsigned overflow at BitLen() > bits. Neither is exercised by decimal_overflow_test.go or issue_1849_test.go (only Int128 is tested). Please add cases for UInt128 negative input and 2^128 to lock in the behavior.
  • "negative value not allowed for unsigned type" is missing context. Compared to the sibling messages, this one doesn't say which type or width. Suggest fmt.Errorf("negative value %s not allowed for unsigned %d-byte type", v.String(), len(dest)) so the message is actionable on its own. Per CLAUDE.md, user-facing errors should be as actionable as possible.

Nits

  • nit: error messages reference decimal128/decimal256/decimal32/decimal64 in lowercase. The ClickHouse type names are `Decimal32`, `Decimal128`, etc. — consider matching the canonical casing in the error string.
  • nit: lib/column/decimal.go:255-265 — for Decimal32/Decimal64 you could route through bigIntToRaw with len(dest)==4/8 instead of an ad-hoc bi.IsInt64() && bi.Int64() ∈ [MinInt32, MaxInt32] check, removing the only reason to import math. Not required, just less code path divergence.
  • nit: tests/issues/issue_1849_test.go:33-40 — overflow1849Cases is a function that returns an anonymous-struct slice and takes *testing.T only to call t.Helper(). A package-level var with a named struct type would be lighter; the helper isn't doing helper-style work.
  • nit: lib/column/decimal_overflow_test.go constructs &BigInt{size: 16, chType: \"Int128\", signed: true, col: &proto.ColInt128{}} by hand. The constructor in lib/column/column.go (Type.Column) already builds these — using it would catch field-name drift if BigInt's struct ever changes.

Verdict

Request changes — small set of fixes (out-of-sync PR description, inconsistent error wrapping across Decimal/BigInt, missing unsigned test coverage). Core approach is correct and worth merging once the items above are addressed.

Comment thread tests/issues/issue_1849_test.go Resolved
wucm667 and others added 2 commits June 5, 2026 18:10
…nctions

Split the single TestIssue1849 into three independent test functions
addressing reviewer feedback from kavirajk:

- TestDecimalOverflow: Decimal(38,0) precision overflow, uses
  decimal.Decimal directly (no any type), named table with single column
- TestDecimalSilentDataCorruption: Decimal32/64 IntPart() silent
  truncation regression, separate sub-tests for each size
- TestBigIntOverflow: Int128/UInt128 range overflow and unsigned
  negative rejection, uses *big.Int directly (no any type)

Each test covers all 4 surface combinations (Native TCP, Native HTTP,
Std TCP, Std HTTP) with explicit typed table-driven test cases.
Variable names use descriptive identifiers (justAboveMaxInt128,
justBelowMinInt128) instead of cryptic shorthand.

Shared helpers (runDecimalOverflowTest, runBigIntOverflowTest) avoid
boilerplate duplication while keeping test cases inline and readable.

Signed-off-by: wucm667 <stevenwucongmin@gmail.com>

@must108 must108 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ping @wucm667

Comment thread tests/issues/issue_1849_test.go Resolved
Comment thread lib/column/bigint.go Resolved
Comment thread tests/issues/issue_1849_test.go Resolved
@github-actions

github-actions Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

🤖 Claude review

Replaces the math/big.FillBytes panic and the silent Decimal32/Decimal64 truncation with a range check (bigIntFits) shared by BigInt.append and Decimal.append, and threads the resulting error through Append/AppendRow. The fix is correct and all previously opened threads are addressed; approving with one test-coverage follow-up.

Verified by trace:

  • Signed bounds: 2^127-1 / -2^127 pass, 2^127 / -2^127-1 fail (Not(v).BitLen() handles the asymmetric negative edge correctly). Unsigned: 2^128-1 passes, 2^128 and any negative fail.
  • bigIntToRaw no longer mutates its argument (new(big.Int).Not(v)), so dropping the defensive Set(v) copy in BigInt.append is safe and the two's-complement + endian swap encoding is unchanged.
  • Decimal32/Decimal64 now go through scaled.BigInt() + bigIntFits before the narrowing cast, so a scaled coefficient beyond int32/int64 errors instead of wrapping. Extra fractional digits still truncate toward zero exactly as IntPart() did.
  • Errors propagate through Nullable/Array wrappers and the database/sql stmt.Exec path; Decimal.append now %w-wraps the inner error.

Intentional behavior change worth a release-note line: a negative big.Int appended to UInt128/UInt256 used to be stored as its two's-complement bit pattern; it now returns an error.

Key concern (inline): the three integration tests never call Send(), so the "valid" boundary values are only checked for a nil Append error and the boundary encodings (notably -2^127, -2^255, -2^31, -2^63) are never round-tripped through the server. Existing suites only round-trip Int128 max and small negatives.

Blind spots:

  • Could not check out or run the branch in this environment; conclusions are from tracing the diff against main.
  • Did not verify whether ClickHouse accepts 2^127-1 as a Decimal(38, 0) value (it exceeds the documented 10^38-1 precision limit). The test never sends it, so this does not affect the current assertions.

Verdict: ✅ Approve

Inline comments are attached to the relevant lines. This summary updates in place on re-review.

@must108 must108 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @wucm667, ensure you address all the agent's comments. Thanks!

@wucm667

wucm667 commented Sep 9, 2026

Copy link
Copy Markdown
Contributor Author

Addressed the latest review findings in 4ae5ad6:

  • aligned Decimal regression boundaries with the driver storage-width validation;
  • unified contextual overflow errors for Decimal and BigInt;
  • added signed and unsigned boundary coverage; and
  • updated the PR description to match the range-check implementation.

The focused native and database/sql regression tests pass over TCP and HTTP locally. The workflow runs are awaiting approval for this fork PR.

@must108 must108 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please address the requested changes by the agent, and also address the failing test cases. Thanks!

@wucm667

wucm667 commented Sep 10, 2026

Copy link
Copy Markdown
Contributor Author

Updated the branch at 26a3e657f911a26b2c5602c263f29f27cf2182ce.

  • Fixed the invalid docs_drift_check.yml job syntax; actionlint now accepts that workflow.
  • Increased the Test1229 concurrent-query budget from 4s to 15s after the 1.25/26.7 failure showed runner scheduling timeouts. The focused test passed 20 consecutive local runs.
  • The new fork-PR runs are all action_required (Tests matrix, Tests head, Lint, CodeQL, link check, Docs Drift). They require maintainer approval before GitHub will execute fork code on the self-hosted runners.

I did not weaken the pull_request_target checkout protection. Please approve the pending workflows; I will follow their results.

Comment thread tests/issues/1229_test.go Resolved
Comment thread lib/column/decimal.go Resolved
Comment thread lib/column/decimal.go Resolved
Signed-off-by: must108 <mustaeen18@gmail.com>
Comment thread tests/issues/issue_1849_test.go Resolved
Comment thread tests/issues/1229_test.go Resolved
must108 and others added 3 commits September 10, 2026 00:44
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Signed-off-by: must108 <mustaeen18@gmail.com>
Signed-off-by: must108 <mustaeen18@gmail.com>
Comment thread tests/issues/issue_1849_test.go Resolved
Comment thread tests/issues/issue_1849_test.go Resolved

@must108 must108 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@must108
must108 merged commit 1b62534 into ClickHouse:main Sep 10, 2026
15 of 16 checks passed
@wucm667
wucm667 deleted the fix/decimal-panic branch September 10, 2026 05:41
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Panic on overflow in Decimal128/256 and BigInt append (+ silent truncation for Decimal32/64)

4 participants