Skip to content

Fix DECIMAL_OVERFLOW when a decimal is compared with a constant that does not fit its scale - #126603

Merged
Algunenano merged 3 commits into
ClickHouse:masterfrom
groeneai:decimal-key-scale-overflow
Oct 19, 2026
Merged

Algunenano merged 3 commits into
ClickHouse:masterfrom
groeneai:decimal-key-scale-overflow

Conversation

@groeneai

@groeneai groeneai commented Oct 18, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #126339
Related: #124680

Changelog category (leave one):

  • Improvement

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

Fixed DECIMAL_OVERFLOW thrown by =, !=, IN, NOT IN and non-Nullable IS [NOT] DISTINCT FROM when a decimal is compared with a decimal constant that does not fit its type at its scale, e.g. d IN (toDecimal128(1000000000, 0)) for d Decimal(38, 30), on sorting and partition keys, minmax and set indexes, EmbeddedRocksDB keys and unindexed columns. Such a constant now equals no value of the column instead of throwing.

Description

On 26.9.19.9, d IN (SELECT toDecimal32(300000000, 0)) on a Decimal(9, 1) sorting key throws DECIMAL_OVERFLOW, while the same filter on an unindexed column returns 0. Since #124680 the overflow is detected for Decimal128 / Decimal256 as well, so the queries of #126339 now throw on master.

Three places rescale a constant only to compare it:

  • canBeSafelyCast called Decimal(P1, S1) -> Decimal(P2, S2) safe whenever P1 <= P2 && S1 <= S2, although raising the scale shrinks the range. Key analysis then took a throwing cast. A pair is now safe only when the scaled native range fits; other pairs take the existing accurateOrNull probe.
  • The strict Field conversion that builds a literal IN set used the throwing convertDecimals. It now returns Null, and an unrepresentable element of a Tuple / Array / Map makes the whole value Null instead of a NULL element. This also fixes tuple(NULL::Nullable(Decimal64(1))) IN (tuple(33.33::Decimal64(2))) with transform_null_in = 1, which returned 1.
  • isNotDistinctFrom cast both operands to the common type although only the Nullable branch uses it.

Not changed: a Nullable operand of <=>, CASE and transform still cast and throw like [a] = [b] (#124680); an integer literal still throws ARGUMENT_OUT_OF_BOUND, as on releases.

Side effects: an INSERT of tuple(1000) into Variant(Tuple(Nullable(Int8)), Tuple(String)) now keeps the value instead of storing (NULL), and a MongoDB IN list element that matches nothing is dropped instead of disabling the pushdown.

Index analysis of a 1M-element rescaled IN (SELECT ...) set now takes the probe: 1254 ms vs 980 ms (debug build). It must travel with any backport of #124680.

The new test lines fail on master.


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

Version info

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

groeneai and others added 2 commits October 18, 2026 15:34
`canBeSafelyCast` reported `Decimal(P1, S1) -> Decimal(P2, S2)` as safe
whenever `P1 <= P2` and `S1 <= S2`. Raising the scale multiplies the stored
integer by `10^(S2 - S1)`, so `Decimal(38, 0)` holding `10^9` does not fit
`Decimal(38, 30)`, and declared precision does not bound stored values. Index
analysis (`KeyCondition` for sorting/partition keys and minmax/set skip
indexes, and the KV storage key `IN` set) trusts "safe" and takes a throwing
cast, so a valid filter such as `d = toDecimal128(1000000000, 0)` on a
`Decimal(38, 30)` key failed with `DECIMAL_OVERFLOW` while the same filter on
an unindexed column returns the right answer. Since ClickHouse#124680 the overflow is
detected for Decimal128/256 too, which turned the wrapped key value into an
exception; Decimal32/64 `IN (subquery)` threw already on released versions.

The pair is now safe only when every value of the source native integer,
scaled up, fits the target native integer; other pairs take the callers'
existing `accurateOrNull` probe, which declines an unrepresentable constant.

Closes ClickHouse#126339

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…a decimal constant that does not fit

The strict `Field` conversion that builds a literal `IN` set rescaled a
decimal with the throwing `convertDecimals`, so a member that does not fit
the column's type at its scale failed the query instead of being skipped. It
now uses `tryConvertDecimals` and returns Null, and in strict mode a Null
element of a `Tuple`, `Array` or `Map` that comes from a non-NULL source makes
the whole value unconvertible, so such a member is never kept as a NULL one.

`isNotDistinctFrom` / `isDistinctFrom` cast both operands to their common
type even when the result was only used for `Nullable` operands; the cast now
happens only in that branch, and other operands are compared exactly by
`FunctionComparison`.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 0 findings on f6ac813b25ca) plus my own review (2 nits, 0 blocking).

# Sev Finding Verdict Evidence / action
1 💡 A Nullable operand of <=> is still cast to the common type and throws DECIMAL_OVERFLOW (FunctionsNullSafeCmp.h) DISAGREE same path as [a] = [b], map = map and JOIN ON a <=> b, which #124680 kept throwing as Decimal64 does (05339, "the cast to the common type"); stated in the description
2 💡 An Array-of-decimal sorting key compared with an array constant of a lower scale is no longer pruned (KeyCondition.cpp, the probe cannot target an Array) AGREE, noted results unchanged; the probe already declines every other unsafe Array pair

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-8:20261018-182600

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes: the #126339 queries plus literal IN / NOT IN / isNotDistinctFrom against a Decimal(38, 30) column throw DECIMAL_OVERFLOW on master on every run; no randomization involved.
b Root cause explained? #124680 made an overflowing Decimal128 / Decimal256 rescale throw. canBeSafelyCast ignored the range lost to the scale-up, the strict IN conversion used the throwing rescale, and isNotDistinctFrom cast both sides needlessly.
c Fix matches root cause? Yes: an exact range check in canBeSafelyCast, a non-throwing rescale returning Null in the strict conversion (also for composite elements), and the cast moved into the only branch that uses it. No try/catch.
d Test intent preserved / new tests added? 11 lines in 05339_decimal_wide_comparison_scale_overflow and 1 in 04077_in_strict_decimal_inside_composites; each fails on master and passes here.
e Both directions demonstrated? Yes: both tests [ FAIL ] on master and [ OK ] with the fix; per-site mutations redden their lines; 50 randomized runs of each test OK.
f Fix is general across code paths? Key, partition, minmax, set and EmbeddedRocksDB analysis; literal IN / NOT IN / globalIn and single-element Tuple / Array / Map members; isDistinctFrom and isNotDistinctFrom. A 1196-row A/B shows no throw and no disagreement with = / !=.
g Fix generalizes across inputs (params/datatypes/wrappers)? Decimal32 to Decimal256, signs, cross-width and narrowing constants, Nullable / composite wrappers, transform_null_in 0 and 1. A Nullable <=> and integer literals keep their release behaviour.
h Backward compatible? (maintainer-approved exception only) Yes: no setting, format or stored data; only queries that threw change. Non-strict conversions are unchanged.
i Invariants and contracts preserved? The strict contract (out-of-range is Null, also inside composites) now holds; a real NULL element stays NULL; the Nullable <=> branch is unchanged.

Session id: cron:clickhouse-impl-slot-4:20261018-161400

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @Algunenano @yariks5s, could you review this and add the can be tested label so CI runs? It fixes the DECIMAL_OVERFLOW that #124680 exposed: canBeSafelyCast now calls a decimal rescale safe only when the scaled native range fits, the strict literal IN conversion returns Null for a constant that does not fit, and isNotDistinctFrom casts to the common type only in its Nullable branch.

@clickhouse-gh

clickhouse-gh Bot commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5f7528a]

Summary: ✅


AI Review

Summary

The PR prevents DECIMAL_OVERFLOW during decimal constant comparisons by checking the scaled native range, rejecting unrepresentable strict conversions without turning them into NULL elements, and avoiding unused casts in non-Nullable null-safe comparisons. No actionable findings were identified at head 5f7528afde811791bc59f36e9cb3d67b7383fb3e.

Final Verdict

Status: ✅ Approve.

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-decimal Decimal datatype semantics, arithmetic, casting, serialization. labels Oct 18, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 18, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 5f7528afd with master 504275109 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 8982f784f; 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.

Compile time of recompiled translation units

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

Job report

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Looks good, thanks!

@alexey-milovidov alexey-milovidov self-assigned this Oct 19, 2026
@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements and removed pr-bugfix Pull request with bugfix, not backported by default labels Oct 19, 2026
@Algunenano
Algunenano enabled auto-merge October 19, 2026 17:16
@Algunenano
Algunenano added this pull request to the merge queue Oct 19, 2026
Merged via the queue into ClickHouse:master with commit 133b54e Oct 19, 2026
178 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 19, 2026
@Manerone

Manerone commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

Backporting to v26.10 as #129166 needs it

@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 4, 2026
robot-ch-test-poll4 added a commit that referenced this pull request Nov 4, 2026
Cherry pick #126603 to 26.10: Fix `DECIMAL_OVERFLOW` when a decimal is compared with a constant that does not fit its scale
robot-clickhouse added a commit that referenced this pull request Nov 4, 2026
…ompared with a constant that does not fit its scale
robot-clickhouse added a commit that referenced this pull request Nov 4, 2026
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 4, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 4, 2026
Backport #126603 to 26.10: Fix `DECIMAL_OVERFLOW` when a decimal is compared with a constant that does not fit its scale
leshikus pushed a commit that referenced this pull request Nov 13, 2026
…ompared with a constant that does not fit its scale
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-decimal Decimal datatype semantics, arithmetic, casting, serialization. pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-improvement Pull request with some product improvements 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.10-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

canBeSafelyCast decimal rule: key =/IN throw DECIMAL_OVERFLOW

7 participants