Skip to content

Reject out-of-range Decimal scale when reading a Field - #131154

Merged
tiandiwonder merged 1 commit into
masterfrom
fix-decimal-field-scale-bound
Nov 13, 2026
Merged

tiandiwonder merged 1 commit into
masterfrom
fix-decimal-field-scale-bound

Conversation

@tiandiwonder

@tiandiwonder tiandiwonder commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Problem

A Decimal Field read from serialized data carries its own scale, and three readers accepted it without a range check:

  • the binary Field reader (getBinaryValue / readFieldBinary in src/Core/Field.cpp), used e.g. by the BINARY settings format;
  • the text Field dump reader (readQuoted behind Field::restoreFromDump), where an exponent-form value such as Decimal64_'1e-1000' builds a scale of 1000 — reachable e.g. through a CUSTOM-flagged setting parsed by SettingFieldCustom::parseFromString;
  • decodeDecimal in src/Common/FieldBinaryEncoding.cpp (binary-encoded Fields inside Dynamic values and AggregateFunction type parameters).

An out-of-range scale is later passed to writeDecimalFractional (src/IO/WriteHelpers.h), which sizes and fills a fixed-size stack buffer from it and writes out of bounds, so the server can crash when such a value is formatted.

Solution

Reject scale > DecimalUtils::max_precision<T> with ARGUMENT_OUT_OF_BOUND in all three readers, the same bound DataTypeDecimalBase enforces. The four Decimal cases of getBinaryValue are converged into one readDecimalFieldBinary<T> helper. Rejecting at the read side means the decimal text writer is never reached with a bad scale. The serialized layout is unchanged.

Unit tests build the malformed bytes directly (the writers cannot produce an out-of-range scale): Field.ReadBinaryDecimalOutOfRangeScaleThrows, Field.RestoreFromDumpDecimalOutOfRangeScaleThrows, FieldBinaryEncoding.DecodeDecimalOutOfRangeScaleThrows and Settings.CustomFlaggedDecimalWithOutOfRangeScaleRejected, each next to a valid round-trip case. Field.ReadBinaryDeeplyNestedThrowsNotOverflow additionally covers the existing checkStackSize in getBinaryValue.

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Fixed a possible server crash when reading a Decimal value with an out-of-range scale from serialized data; such a value is now rejected with an error.

🤖 Generated with Claude Code


Workflow [PR]
Sync PR [sync-upstream/pr/131154]

Version info

  • Merged into: 26.11.1.2170-master (included in 26.11 and later)

A `Decimal` `Field` read from serialized data carries its own scale, and three
readers accepted it without a range check: the binary `Field` reader
(`getBinaryValue`), the text dump reader (`readQuoted` behind
`Field::restoreFromDump`, where an exponent-form value like
`Decimal64_'1e-1000'` builds a scale of 1000), and `decodeDecimal` in
`FieldBinaryEncoding`. An out-of-range scale later overruns a fixed-size buffer
in `writeDecimalFractional`.

Reject `scale > DecimalUtils::max_precision<T>` with `ARGUMENT_OUT_OF_BOUND` in
all three readers, as `DataTypeDecimalBase` does, and converge the four binary
`Decimal` cases into `readDecimalFieldBinary`. The serialized layout is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f39e7f6]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

This PR hardens three Decimal Field deserializers against out-of-range scales and adds focused regression coverage for the malformed-input crash. I found one remaining blocker in the text dump reader: the new guard still executes after scale = -exponent, so the most negative exponent can overflow before the check and the malformed value is not reliably rejected.

Findings
  • ❌ Blockers
    • [src/Core/Field.cpp:769] The Field::restoreFromDump decimal path still has signed-overflow UB for Decimal*_...'e-2147483648'. readDigits can return exponent == std::numeric_limits<Int32>::min(), and the code negates it in scale = -exponent before validating the range. That means the malformed input this PR is trying to harden against is still not guaranteed to fail safely.
      Suggested fix: compare exponent against -static_cast<Int32>(DecimalUtils::max_precision<T>) before negating it, or widen the computation to Int64/UInt64 and cast to UInt32 only after the bound check. Add a regression test for the INT32_MIN exponent case.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions: fix the INT32_MIN exponent path in readQuoted so malformed dump input is rejected without signed overflow, and add a regression test for that exact case.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Nov 13, 2026

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

Looks good

Comment thread src/Core/Field.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Nov 13, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing f39e7f6a4 with master 88a2a10f0 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.60, programs/clickhouse-keeper ×0.69 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 6.1 s 11.1 s +7.5 s (+207%)
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.5 s 7.4 s +5.3 s (+253%)
Compile time of recompiled translation units

8 translation units recompiled, 10 s compile time in total, 8 of them have a recent master baseline.

Job report

@clickhouse-gh clickhouse-gh Bot added the comp-decimal Decimal datatype semantics, arithmetic, casting, serialization. label Nov 13, 2026
@tiandiwonder
tiandiwonder added this pull request to the merge queue Nov 13, 2026
Merged via the queue into master with commit 401380a Nov 13, 2026
206 of 208 checks passed
@tiandiwonder
tiandiwonder deleted the fix-decimal-field-scale-bound branch November 13, 2026 09:59
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 13, 2026
@Algunenano

Copy link
Copy Markdown
Member

@tiandiwonder @leshikus Why did you ignore the AI review? It's clearly pointing to an issue that cannot be ignored: #131286

@leshikus

Copy link
Copy Markdown
Collaborator

@Algunenano the comment from the author says the issue will be fixed in a follow-up PR, - this is IMO a valid point; was there any other review?

@Algunenano

Copy link
Copy Markdown
Member

What's the point of leaving a crash pending? What's the hurry?

@tavplubix

Copy link
Copy Markdown
Member

@Algunenano the AI review comment says nothing about the crash, it's about signed-overflow UB, which is not critical because it does not allow bypassing the load-bearing scale > DecimalUtils::max_precision<T> check. The @tiandiwonder's reply looks valid: #131154 (comment)

The root cause of #131286 is the missing scale range check in another place that has nothing to do with signed-overflow UB, and the AI review comment does not help to find this crash, it's just noise.

mkmkme added a commit to Altinity/ClickHouse that referenced this pull request Nov 17, 2026
Stable 25.8 Backport of ClickHouse#131154 - Reject out-of-range `Decimal` scale when reading a `Field`
mkmkme added a commit to Altinity/ClickHouse that referenced this pull request Nov 17, 2026
Antalya 25.8 Backport of ClickHouse#131154 - Reject out-of-range `Decimal` scale when reading a `Field`
27rohan pushed a commit to 27rohan/ClickHouse that referenced this pull request Nov 18, 2026
`readDigits` added the parsed exponent to the count of digits after the point
without a check, and `readDecimalText` then computed `digits + exponent`,
`scale + exponent` and `-exponent` in `int32_t`. For an exponent close to the
`Int32` limits these overflow (undefined behaviour); in practice they wrap, so
`toDecimal64OrNull('1e2147483647', 2)` passed the "too big" check and returned
`0` instead of `NULL`, and `toDecimal64('1e2147483647', 2)` returned `0` instead
of throwing `ARGUMENT_OUT_OF_BOUND`.

The `Field` dump reader `readQuoted` had the same problem after the scale bound
was added in ClickHouse#131154: it negated an exponent of `INT32_MIN`, and for a positive
exponent beyond the precision `scaleMultiplier` saturates instead of
overflowing, so `Decimal64_'1e100'` became the maximum `Int64`.

Now `readDigits` fails with `CANNOT_PARSE_NUMBER` when the exponent does not fit
`int32_t`, `readDecimalText` does its bound arithmetic in 64 bits, and
`readQuoted` checks the exponent against `max_precision` before negating or
scaling (`ARGUMENT_OUT_OF_BOUND` / `DECIMAL_OVERFLOW`).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
mkmkme added a commit to Altinity/ClickHouse that referenced this pull request Nov 19, 2026
Antalya 26.6 Backport of ClickHouse#131154 - Reject out-of-range `Decimal` scale when reading a `Field`
mkmkme added a commit to Altinity/ClickHouse that referenced this pull request Nov 20, 2026
Stable 25.3 Backport of ClickHouse#131154 - Reject out-of-range `Decimal` scale when reading a `Field`
mkmkme added a commit to Altinity/ClickHouse that referenced this pull request Nov 20, 2026
FIPS 25.3 Backport of ClickHouse#131154 - Reject out-of-range `Decimal` scale when reading a `Field`
mkmkme added a commit to Altinity/ClickHouse that referenced this pull request Nov 20, 2026
Stable 24.8 Backport of ClickHouse#131154 - Reject out-of-range `Decimal` scale when reading a `Field`
@watson-ch

watson-ch Bot commented Nov 23, 2026

Copy link
Copy Markdown

Backport labels have been automatically added based on https://github.com/clickhouse/clickhouse-core-incidents/issues/2252

Labels added:

  • v26.8-must-backport

These labels ensure backport PRs are properly created for each affected release version. The release automation will create backport PRs as needed based on these labels.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-decimal Decimal datatype semantics, arithmetic, casting, serialization. pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.8-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants