Skip to content

Fix wrong results of decimal comparisons and casts when rescaling to the common scale overflows - #124680

Merged
Algunenano merged 6 commits into
ClickHouse:masterfrom
groeneai:decimal-wide-comparison-scale-overflow
Oct 16, 2026
Merged

Algunenano merged 6 commits into
ClickHouse:masterfrom
groeneai:decimal-wide-comparison-scale-overflow

Conversation

@groeneai

@groeneai groeneai commented Oct 8, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #122134
Related: #38223
Related: #69304

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 wrong results of comparisons, has / indexOf and casts of Decimal128 / Decimal256 values when bringing a value to a larger scale does not fit the type: toDecimal128(1, 30) < 1000000000 returned 0, and CAST(toDecimal128(1000000000, 0) AS Decimal(38, 30)) returned a wrapped value. A comparison of decimals with different scales is now exact for every width (toDecimal64(1, 18) < 100 threw DECIMAL_OVERFLOW), and such a cast, also from an integer (a UInt256 turned negative), throws DECIMAL_OVERFLOW.

Description

On 26.8.18.2, toDecimal128(1, 30) < 1000000000 returns 0 and CAST(toDecimal128(1000000000, 0) AS Decimal(38, 30)) returns -20847100.76.... The rescale to the common scale is checked with common::mulOverflow, which wraps and reports success for Int128 / Int256.

  • Comparisons with decimal_check_overflow = 1 and different scales apply the scale themselves, exactly, for every width: a product that does not fit is beyond every value of the other side, so its sign decides. Against a constant, either the constant is scaled once or the column is compared with floor(k / m); between two columns each value is checked against [min / m, max / m]. Decimal32 / Decimal64 threw DECIMAL_OVERFLOW here (00700_decimal_compare and 04523_type_pair_matrix_errors change). The Field comparison (primary key analysis) uses the same helper.
  • Casts to decimals check the same bounds for big integers, so CAST and casts to the common type behind Array / Map comparison, JOIN keys and arrayMax throw DECIMAL_OVERFLOW; accurateCastOrNull returns NULL, IN (SELECT ...) returns 0 (00700_decimal_casts_2 pinned a wrapped value). A UInt256 above Int256 max is rejected before it turns negative (toDecimal256(bitNot(toUInt256(0)), 1) was -1).
  • Non-constant has, indexOf, countEqual, indexOfAssumeSorted and mapContainsValue with decimals of different types compare as equals does, after widening both sides to Decimal256 at their own scale, instead of casting to the common type.

Not changed: greatest / least and arithmetic align the scales with the same unchecked multiply (#38223).

Performance is not tuned here (of master's CPU time: rescaled two-column comparisons up to 2.2x, wide decimal-to-decimal casts 1.5x, non-constant mixed-type has 2.4x; comparison objects +6%); optimizing is left for a separate PR.

The new test lines fail on master; the boundary controls pass on both.


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

Version info

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

…scale overflows

With `decimal_check_overflow = 1`, a comparison whose compare type is Int128 or
Int256 brings the side with the smaller scale to the common scale with
`common::mulOverflow`, which is a stub for big integers (it wraps and reports
no overflow). The wrapped product was compared, so e.g.
`toDecimal128(1, 30) < 1000000000` returned 0 and
`toDecimal128(170141184, 0) < toDecimal128(1, 30)` returned 1.
Decimal32 / Decimal64 are not affected: the builtin check fires and they throw
DECIMAL_OVERFLOW.

For a big-integer compare type with the check on and a scale difference, the
comparison now goes through `applyMixed`, which converts both sides without the
scale (keeping the narrowing and sign checks) and applies the scale exactly in
shared per-`CompareInt` kernels. Against a constant, either the constant is
scaled once (a product that does not fit `T` is beyond every value of the
column, so its sign decides), or the column is compared with `q = floor(k / m)`:
`v * m OP k` is `v OP q` for a zero remainder, and otherwise `v * m < k` iff
`v <= q`, which `v OP q` or `v OP (q + 1)` gives depending on the operator
(`=` / `!=` are then constant). Wide `/` truncates toward zero and `%` takes the
dividend's sign, so `q` is the floor after `q -= 1` for a negative remainder, and
`q + 1` cannot overflow. Each row is then one comparison in a multitarget loop.
Between two columns, a multiplicand outside `[min(T) / m, max(T) / m]` (computed
once) has a product beyond every value of the other side, so its sign decides;
that loop is compiled multitarget like `vectorConstant`. This is exact for every
stored value, including raw values at the type limits (`reinterpret`), and never
throws, so the non-throwing extremes pinned by 04512 / 04523 keep their results.
The Field-level `compare()` uses the same helper.

Kernels for Int32 / Int64 compare types, comparisons without scaling and
`decimal_check_overflow = 0` are unchanged. `common::mulOverflow` for big
integers (arithmetic, conversions) is not touched (ClickHouse#38223).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work labels Oct 8, 2026
@groeneai

groeneai commented Oct 8, 2026

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

Pre-publication review by an independent model (engine: codex; 2 findings, then 0 on the re-review of b981c745516a) plus my own review (7 findings, then 0).

# Sev Finding Verdict Evidence / action
1 ⚠️ A column compared with a scaled constant (Decimal(38, 2) column > 100) re-did the bounds check and multiplication of the constant on every row AGREE, fixed @ b981c74 the constant is scaled once (or decided by its sign)
2 ⚠️ A scaled column against a constant was 2.3-3.6x slower AGREE, fixed @ b981c74 compared with floor(k / m) (or + 1), one comparison per row; now 0.31-0.40x of master
3 ⚠️ Column against column was 1.8-2.3x slower AGREE, fixed @ b981c74 the loop is compiled multitarget like vectorConstant; now 0.86x (Int128) / 0.91x (Int256)
4 ⚠️ Comparison objects grew 18-21% from a per-type-pair dispatch AGREE, fixed @ b981c74 the exact path lives in applyMixed with shared per-CompareInt kernels; now +3%
5 ⚠️ No committed test reaches the Field comparison AGREE, fixed @ b981c74 case added to the existing DecimalSameTypeScales gtest (the Field path is not reachable from SQL with an overflowing scale difference)
6 ❌ Array / Map comparisons of differently scaled wide decimals still return wrong results DISAGREE they CAST both sides to the least supertype first (FunctionsComparison.h:1448-1454, :1725-1734) and the wrapped value comes from that cast (DataTypesDecimal.cpp:164-170, the conversion this PR leaves to #38223); the description names them
7 💡 Duplicated shape dispatch, a doc sentence, the cost sentence AGREE, fixed @ b981c74 folded into 4; doc edit reverted; cost restated from new measurements

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

Session id: cron:clickhouse-review-self-slot-58:20261008-154800

@groeneai

groeneai commented Oct 8, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes: SELECT materialize(toDecimal128(170141184, 0)) < toDecimal128(1, 30) returns 1 on master, 0 with the fix (no settings involved).
b Root cause explained? common::mulOverflow does not detect overflow for Int128 / Int256, so the rescale to the common scale wraps and the wrapped product is compared.
c Fix matches root cause? Yes: the comparison applies the rescale itself: against a constant it scales the constant once or compares the column with floor(k / m); between columns it checks per-value bounds computed once. An out-of-range product is decided by its sign.
d Test intent preserved / new tests added? New SQL test with boundary controls and raw type limits; no existing test or reference changed.
e Both directions demonstrated? Yes: the SQL test and the Field gtest case fail on master and pass with the fix; eight mutations of the fix (constant bounds removed, floor removed, bounds off by one, dispatch removed, remainder test removed, out-of-range result swapped, q + 1 removed, constant = / != removed) each fail the test.
f Fix is general across code paths? Same-type and mixed-type column comparisons share applyMixed and per-CompareInt kernels; the Field comparison uses the same helper. Arithmetic, conversions and comparisons that cast to a common type first use the same stub and are out of scope (#38223).
g Fix generalizes across inputs (params/datatypes/wrappers)? Decimal128, Decimal256, mixed with Decimal64 and integers, all four constness shapes, both signs, boundary and raw-limit values.
h Backward compatible? (maintainer-approved exception only) Yes: no setting, no new exception; only results that were wrong change; decimal_check_overflow = 0 keeps wrapping.
i Invariants and contracts preserved? Narrowing and sign checks still throw; empty columns are not converted; constant inputs give a constant result.

Session id: cron:clickhouse-impl-self-slot-57:20261008-145300

@clickhouse-gh

clickhouse-gh Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0b8aeb3]

Summary: ✅


AI Review

Summary

The PR makes rescaled Decimal comparisons exact, rejects overflowing decimal and integer casts, and fixes mixed-decimal array searches. Review of head 0b8aeb33e48f2ee6e62bd256162d41e52c7d24fc found no remaining actionable findings. Both prior bot findings are addressed.

Missing context / blind spots
  • ⚠️ Local SQL probes used the available parent build 8483f9765591, whose comparison and array-search code matches the head. The final integer-conversion optimization was reviewed statically; the head's CI regression results would complete runtime validation.
Final Verdict

Status: ✅ Approve.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 8, 2026
@Algunenano Algunenano self-assigned this Oct 8, 2026

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

Please explain the need of introducing v4 dispatch here and what it wins. The PR is meant to be fixing a bug, and while caring about performance is great, if we introduce something like this is should be explained, both in the description and in the code.

Comment thread src/Core/DecimalComparison.h Outdated

/// `common::mulOverflow` does not detect the overflow of big integers; `applyMixed` applies the scale exactly.
if constexpr (is_big_int_v<CompareInt>)
if (check_overflow && !shift.none())

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.

Please prefer if { if ...} (aka a nested if means the parent uses braces)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done in f09691e.

@clickhouse-gh clickhouse-gh Bot added the comp-decimal Decimal datatype semantics, arithmetic, casting, serialization. label Oct 8, 2026
Review feedback on ClickHouse#124680. Measured on an AVX-512 host with a release
x86-64-v3 build (one thread, `UserTimeMicroseconds`, rotated rounds):

- Column vs constant: the loop is a plain comparison that x86-64-v3 already
  vectorizes with AVX2. The x86-64-v4 variant was about 1.2x faster for
  `Decimal128` but about 1.2x slower for `Decimal256`, so the dispatch is
  removed and the existing `compareVectorConstant` / `compareConstantVector`
  helpers are used.
- Column vs column: the per-row bounds check keeps the x86-64-v3 loop scalar
  (data-dependent branches), 1.5x (`Decimal128`) / 2.2x (`Decimal256`) of
  master's CPU time. A branch-free variant vectorizes with AVX2 but is
  slower still (1.8x / 2.0x). With x86-64-v4 the bounds checks and the
  comparison vectorize (mask registers) and it runs at 1.0-1.1x of master,
  so this dispatch stays, with a comment.

Also brace the outer `if constexpr` around the nested `if`.

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

groeneai commented Oct 8, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks. I measured it (AVX-512 host, release x86-64-v3 build, one thread, CPU time relative to master) and changed the PR accordingly in f09691e:

  • Column vs column: the per-row bounds check against [min / m, max / m] makes the x86-64-v3 loop scalar with data-dependent branches, 1.5x (Decimal128) and 2.2x (Decimal256) of master. A branch-free version vectorizes with AVX2 but measured slower still (1.8x / 2.0x). For x86-64-v4, clang vectorizes the bounds checks and the comparison with AVX-512 mask registers (the products stay scalar), 1.0-1.1x of master. This dispatch stays, now with a comment in the code and a sentence in the description.
  • Column vs constant: the loop is a plain comparison that x86-64-v3 already vectorizes with AVX2. The x86-64-v4 variant was about 1.2x faster for Decimal128 but up to 1.2x slower for Decimal256, so I removed that dispatch and the existing compareVectorConstant / compareConstantVector are used. The remaining cost is one shape: a same-type column < constant with the constant rescaled is 1.2-1.3x of master, which runs it through its x86-64-v4 vectorConstant.

The nested if now has braces.

@groeneai
groeneai requested a review from Algunenano October 8, 2026 18:16
@groeneai

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - f09691e

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_release, oracle) subquery wrap oracle mismatch, not from this PR (the fuzzed query has no Decimal value): SELECT * over two unaliased subqueries that both have a column id returns the first id for both columns once it is wrapped in SELECT * FROM (...). Reproduced on a master build: unwrapped -2, wrapped -9223372036854775807 #107127 (mine, open); with it the wrapped query returns -2
PR, Mergeable Check rollup, red only because of the row above #107127 (the same)

All 152 check runs completed and Finish Workflow is green. CIDB has no FAIL or ERROR test row on this head.

Session id: cron:our-pr-ci-monitor:20261009-023006

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

🤖

Thanks. The approach is exact: I went through the floor(k / m) + remainder logic in compareScaledVectorConstant for all six operators, both operand orders and negative remainders, and the ScaleBounds check in the multiply paths. I tested the CI amd_release binary of f09691e5 against master. In the examples, X = 316912650057057350374175801345 (2^98 + 1, so X * 10^30 wraps to exactly 10^30).

The PR also fixes these, but nothing in 05339_decimal_wide_comparison_scale_overflow or the gtest covers them. All of them fail on master; please add them to the test:

-- X * 10^30 wraps to exactly 10^30 on master, so these returned a false 1.
SELECT toDecimal128(1, 30) = toDecimal128('316912650057057350374175801345', 0); -- master 1, PR 0
SELECT materialize(toDecimal128(1, 30)) = materialize(toDecimal128('316912650057057350374175801345', 0)); -- master 1, PR 0

SELECT tuple(toDecimal128(1, 30)) = tuple(toDecimal128('316912650057057350374175801345', 0)); -- master 1, PR 0
SELECT toNullable(toDecimal128(1, 30)) = toDecimal128('316912650057057350374175801345', 0); -- master 1, PR 0
SELECT has([toDecimal128(1, 30)], toDecimal128('316912650057057350374175801345', 0)); -- master 1, PR 0
SELECT indexOf([toDecimal128(1, 30)], toDecimal128('316912650057057350374175801345', 0)); -- master 1, PR 0

-- Primary key analysis uses the `Field` comparison; the gtest covers it, but not at the SQL level.
CREATE TABLE t (d Decimal(38, 0)) ENGINE = MergeTree ORDER BY d SETTINGS index_granularity = 1;
INSERT INTO t VALUES (1), (100000000000000000000), ('316912650057057350374175801345');
SELECT count() FROM t WHERE d > toDecimal128(1, 30); -- master 0, PR 2
SELECT count() FROM t WHERE d = toDecimal128(1, 30); -- master 2, PR 1

Also, the column-vs-constant floor path (compareScaledVectorConstant with scale_vector = true) is only tested for Decimal128. A Decimal256 case with a negative remainder would cover the Int256 division.

1. has and indexOf now depend on constness.

SELECT has([toDecimal128(1, 30)], toDecimal128('316912650057057350374175801345', 0)); -- 0
SELECT has(materialize([toDecimal128(1, 30)]), materialize(toDecimal128('316912650057057350374175801345', 0))); -- 1
SELECT indexOf(materialize([toDecimal128(1, 30)]), materialize(toDecimal128('316912650057057350374175801345', 0))); -- 1

Before, both were wrong; now the same expression gives different results depending on whether the arguments are constant. The description says has still wraps, which is true only for the non-constant case. Please fix has and indexOf for non-constant arguments in this PR too, and test both the constant and the non-constant forms.

2. Other comparisons of the same values are still wrong:

SELECT [toDecimal128(1, 30)] = [toDecimal128('316912650057057350374175801345', 0)]; -- 1, expected 0
SELECT [toDecimal128(1, 30)] < [toDecimal128(1000000000, 0)]; -- 0, expected 1
SELECT map(1, toDecimal128(1, 30)) = map(1, toDecimal128('316912650057057350374175801345', 0)); -- 1, expected 0
SELECT toDecimal128('316912650057057350374175801345', 0) IN (SELECT toDecimal128(1, 30)); -- 1, expected 0
SELECT count() FROM (SELECT toDecimal128('316912650057057350374175801345', 0) AS a) AS l
    JOIN (SELECT toDecimal128(1, 30) AS b) AS r ON l.a = r.b; -- 1, expected 0
SELECT greatest(toDecimal128(1, 30), toDecimal128(1000000000, 0)); -- 1, expected 1000000000
SELECT arrayMax([toDecimal128(1, 30), toDecimal128(1000000000, 0)]); -- 1, expected 1000000000

IN (toDecimal128(1, 30), toDecimal128(2, 30)) is correct, but IN (SELECT ...) and JOIN are not. After this PR, a = b and [a] = [b] (or a IN (SELECT b)) disagree. These cast both sides to the common type first, and that cast wraps: least(toDecimal128(1, 30), toDecimal128(1000000000, 0)) returns -20847100.762815390390123822295304634368. Can the fix cover these too, e.g. by making the cast to the common type check overflow for big integers?

3. Make Decimal32 / Decimal64 exact too. After this PR the result depends on the width:

SELECT toDecimal128(1, 30) < 1000000000; -- 1
SELECT toDecimal64(1, 18) < 100; -- DECIMAL_OVERFLOW
SELECT toDecimal32(1, 9) < toDecimal32(100, 0); -- DECIMAL_OVERFLOW

The new helpers are generic in T, so dropping the is_big_int_v<CompareInt> gate should make every width exact instead of throwing. Please include Decimal32 and Decimal64 in this fix and test them the same way as Decimal128 / Decimal256: values on both sides of the max / m bound, the stored limits, mixed types, constant and non-constant operands, and the column-vs-constant floor path.

4. Readability of compareScaledVectorConstant. The comment "unless Op is (not) equals" and the choice between q and q + 1 via Op::apply(T(0), T(0)) are hard to follow. A worked example would help: d < 1.5 → q = 1, r = 5 → d < 2; d <= 1.5 → d <= 1; d = 1.5 → all zeros.

5. Nit: scale_in_compare, exact_scale and the [[maybe_unused]] locals make applyMixed harder to read. A separate function for the rescaled big-integer case would keep applyMixed as it was.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Thanks for the detailed review. I'm making all of these changes in this PR and will reply point by point with the push. Two design decisions up front, in case you'd rather have them differently:

  • 2. Array and Map equality, JOIN, IN (SELECT ...) and the mixed array literal under arrayMax go through convertDecimalsBatch, whose big-integer rescale relies on the no-op common::mulOverflow. I'm adding a bounds check there (computed once per batch), so that these behave as Decimal64 already does for the same shapes: on master [toDecimal64(1, 18)] = [toDecimal64(100, 0)], the map, JOIN and arrayMax forms throw DECIMAL_OVERFLOW, and toDecimal64(100, 0) IN (SELECT toDecimal64(1, 18)) returns 0. greatest / least are not a cast: they align the scales in applyScaled of FunctionBinaryArithmetic.h (Decimal64 throws Decimal math overflow there), which is the same unchecked big-integer multiply as Incorrect results in 00700_decimal_arithm test #38223 (21 + toDecimal128('0.42', 38)), on the path of every Decimal128 / Decimal256 + and - whose scales differ. I'd fix that in a separate PR that closes Incorrect results in 00700_decimal_arithm test #38223, unless you want it here.
  • 1. For non-constant has / indexOf / countEqual with decimal elements and a decimal needle of another type, I'll compare with equals instead of casting both sides to the common type, so the result is what the constant form and = return, rather than an exception from the cast.

@Algunenano

Copy link
Copy Markdown
Member

@groeneai Yes please. And to be clear, performance is not key here. We need correct, expected behaviour first, then we can (in other PRs) optimize it if possible. But let's first build a solid base with tests so iterating it later is simpler

…ger rescale in casts

Review of ClickHouse#124680:

- Every width compares exactly when bringing one side to the common scale overflows,
  not only Decimal128 / Decimal256: `toDecimal64(1, 18) < 100` and
  `toDecimal32(1, 9) < toDecimal32(100, 0)` returned DECIMAL_OVERFLOW, now 1.
  The rescaled case moves into a separate `applyRescaled`; `applyMixed` is as on master.
  `applyRescaled` only converts the two sides; the comparison is shared per compare type
  (`compareRescaled`); `equals.cpp.o` text grows by 5.7%.
  Three lines of 00700_decimal_compare and one of 04523_type_pair_matrix_errors that
  expected DECIMAL_OVERFLOW now return the exact result.
- The rescale of a Decimal128 / Decimal256 in a cast relied on `common::mulOverflow`,
  which does not detect the overflow of big integers. A bounds check (computed once per
  batch) makes `CAST`, the casts to the common type of Array / Map comparison, JOIN keys
  and array literals throw DECIMAL_OVERFLOW as they do for Decimal64, and
  `accurateCastOrNull` return NULL. `IN (SELECT ...)` now returns 0 for a value that
  does not fit. 00700_decimal_casts_2 pinned a wrapped Decimal128 cast; it now throws,
  as the Decimal64 line next to it does.
- `has`, `indexOf`, `countEqual`, `indexOfAssumeSorted` and `mapContainsValue` with
  non-constant decimal arguments of different types compared both sides cast to the
  common type, so they disagreed with the constant form. They now compare as `equals`
  does, after widening both sides to Decimal256 at their own scale (exact). A constant
  `Nullable` needle, which `executeArrayImpl` does not unwrap, takes the same path.
- The bounds struct moves to `Core/DecimalScaleBounds.h`, shared by the comparison and
  the cast. The worked example for the `floor(k / m)` path is in the comment.
- The x86-64-v4 dispatch of the two-column loop is removed: correctness first, the
  performance work goes to a separate PR.
- The embedded documentation of `Decimal` no longer says that a comparison throws.
- Tests: the reviewer's cases (scalar, Tuple, Nullable, has / indexOf constant and
  non-constant, the primary key), Decimal32 / Decimal64 with the same matrix as
  Decimal128 / Decimal256, the column-vs-constant floor path for every width, and the
  casts.

Not changed: `greatest` / `least` align the scales in `FunctionBinaryArithmetic.h`
(`applyScaled`), the same unchecked big-integer multiply as ClickHouse#38223.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai changed the title Fix wrong results of Decimal128 / Decimal256 comparisons when rescaling to the common scale overflows Fix wrong results of decimal comparisons and casts when rescaling to the common scale overflows Oct 14, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Done in 1984e64 (one commit on top of the previous head).

  • Tests. 05339 has all your cases (scalar, materialize, Tuple, Nullable, constant and non-constant has / indexOf, the primary key) and a Decimal256 column-vs-constant case with a negative remainder.
  • 1. Non-constant has, indexOf, countEqual, indexOfAssumeSorted and mapContainsValue with decimals of different types compare as equals does (both sides widened to Decimal256 at their own scale), so the constant and non-constant forms agree. Both are tested, including a constant Nullable needle.
  • 2. The rescale in convertDecimalsImpl / convertDecimalsBatch checks the bounds for big integers. [a] = [b], [a] < [b], map = map, JOIN, arrayMax and CAST throw DECIMAL_OVERFLOW as for Decimal64, and IN (SELECT ...) returns 0. 00700_decimal_casts_2 had pinned a wrapped Decimal128 cast; it now throws. A Tuple element in has goes through the same cast and throws too. greatest / least are unchanged (Incorrect results in 00700_decimal_arithm test #38223).
  • 3. The is_big_int_v gate is gone: Decimal32 / Decimal64 compare exactly, tested with the same matrix (both sides of max / m, the stored limits, mixed types, constant and non-constant operands, the floor path). Three lines of 00700_decimal_compare and one case of 04523_type_pair_matrix_errors change from DECIMAL_OVERFLOW to the result, and the embedded Decimal docs no longer say that a comparison throws.
  • 4. The comment has your worked example.
  • 5. applyMixed is as on master. The rescaled case is applyRescaled, which converts the two sides and calls compareRescaled, shared per compare type.

Since performance is not the goal here, I removed the x86-64-v4 dispatch of the two-column loop. The description lists the cost.

Comment thread src/DataTypes/DataTypesDecimal.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 0b8aeb33e with master 0f5adf179 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 77a2418dc; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 784.04 MiB 785.18 MiB +1.15 MiB (+0.15%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

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.

Object file sizes ⚠️

18 object files changed (+5.16 MiB total), 0 added.

Object file Master PR Δ
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/greaterOrEquals.cpp.o 8.00 MiB 8.51 MiB +519.15 KiB (+6.34%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/less.cpp.o 7.93 MiB 8.43 MiB +519.01 KiB (+6.40%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/greater.cpp.o 7.94 MiB 8.45 MiB +518.98 KiB (+6.38%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/lessOrEquals.cpp.o 7.99 MiB 8.50 MiB +518.95 KiB (+6.34%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/notEquals.cpp.o 7.82 MiB 8.33 MiB +516.25 KiB (+6.45%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/isNotDistinctFrom.cpp.o 7.78 MiB 8.28 MiB +516.20 KiB (+6.48%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/equals.cpp.o 7.78 MiB 8.29 MiB +516.19 KiB (+6.48%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/isDistinctFrom.cpp.o 7.86 MiB 8.36 MiB +515.84 KiB (+6.41%)
src/CMakeFiles/dbms.dir/DataTypes/DataTypesDecimal.cpp.o 1.46 MiB 1.71 MiB +256.21 KiB (+17.17%)
src/Functions/array/CMakeFiles/clickhouse_functions_array.dir/countEqual.cpp.o 1.93 MiB 2.13 MiB +202.91 KiB (+10.26%)
src/Functions/array/CMakeFiles/clickhouse_functions_array.dir/indexOf.cpp.o 2.08 MiB 2.27 MiB +198.69 KiB (+9.34%)
src/Functions/array/CMakeFiles/clickhouse_functions_array.dir/indexOfAssumeSorted.cpp.o 1.96 MiB 2.15 MiB +190.94 KiB (+9.49%)
src/Functions/array/CMakeFiles/clickhouse_functions_array.dir/FunctionsMapMiscellaneous.cpp.o 4.93 MiB 5.10 MiB +179.44 KiB (+3.55%)
src/CMakeFiles/dbms.dir/Functions/array/has.cpp.o 841.84 KiB 934.95 KiB +93.11 KiB (+11.06%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

`convertToDecimalBatch` (CAST, `toDecimalNN`, `accurateCastOrNull` of a
non-constant or constant integer) multiplied with `common::mulOverflow`,
which never reports overflow for `Int128` / `Int256`, so
`CAST(toInt64(1000000000) AS Decimal(38, 30))` returned a wrapped value
while the scalar `convertToDecimalImpl` already threw. The checked
multiply now lives in `DecimalScaleBounds::mulOverflow` and all three
rescale sites use it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/DataTypes/DataTypesDecimal.cpp Resolved
groeneai and others added 2 commits October 14, 2026 22:02
Integer to decimal conversions widen every big-integer source to the signed
`Int256` intermediate, so a `UInt256` above `Int256::max` became negative
before any bounds check ran: `toDecimal256(bitNot(toUInt256(0)), 1)` returned
`-1` (the same through `toDecimal32/64/128`), and `2^255` at scale 0 returned
`-2^255`. The rescale and range checks then accepted the wrapped value.

`fitsIntermediate` rejects such a source before the cast in both loops of
`convertToDecimalBatch` (scale zero included) and in `convertToDecimalImpl`.
It is a compile-time `true` for every source except `UInt256`, the only
integer type the signed intermediate cannot hold.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The scaled loop of `convertToDecimalBatch` checked every row twice: the
multiplication against `DecimalScaleBounds` of the wide intermediate type, then
the product against the destination range. A cast from `Int128` paid four
`Int256` comparisons and an `Int256` multiplication per row, which made
`decimal_casts` ClickHouse#3-ClickHouse#6 1.15-1.74x slower than master (Performance Comparison,
arm_release).

The source values whose product with `m` fits the destination are
`[ceil(min / m), floor(max / m)]`. Compute that range once per block, clamped to
the source type, compare each row in the source type and multiply in the
destination type. A `UInt256` above the `Int256` maximum is above that range, so
it needs no separate check in this loop.

The results are the same as before for every integer source type, decimal width
and scale (boundary values around both limits checked against an independent
oracle). On an x86-64-v3 RelWithDebInfo build the casts take 0.39-1.03x of
master's time.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Algunenano
Algunenano added this pull request to the merge queue Oct 16, 2026
Merged via the queue into ClickHouse:master with commit 08f08e6 Oct 16, 2026
177 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 16, 2026
opensource-fork-sync Bot pushed a commit to cla7aye15I4nd/opensource-ClickHouse__ClickHouse that referenced this pull request Oct 19, 2026
`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]>
rorylshanks added a commit to rorylshanks/ClickHouse that referenced this pull request Nov 4, 2026
Two master changes made comparisons that used to throw return a result, and
the tests pinned the old exceptions:

- ClickHouse#122245 compares a string
  constant with an integer outside the range of the column type in a wider
  integer type, so `UInt64 = '-42'` is `0` instead of `TYPE_MISMATCH`.
  `05101` now uses `'42.5'`, which integer runtime types still fail to parse,
  for the exception, and checks that `'-42'` matches nothing.
- ClickHouse#124680 compares decimals of
  different scales exactly, so rescaling `Decimal(18, 2)` to the scale of
  `toDecimal64(1, 3)` no longer throws `DECIMAL_OVERFLOW`. `05103` now checks
  that the index keeps the matching row next to a value whose rescaling
  overflows.

Both are intended behaviour. The index stays conservative for them: it keeps
the granules where the conversion of the constant fails. Without the overflow
check (`decimal_check_overflow = 0`) execution rescales with wraparound, which
is why the index still keeps decimal types whose rescaling may overflow; the
comment now says so.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=113022&sha=c543bed2acf878e6046ff4920f52b901e3d77d7f&name_0=PR&name_1=Fast%20test
PR: ClickHouse#113022

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01E5v7QTSR65LdYnQEv9HJVu
lilredbot pushed a commit to JTCunning/ClickHouse that referenced this pull request Nov 4, 2026
`FunctionIfBase::scaleLiftCanOverflow` exempted every result wider than
64 bits, so `multiIf` / `CASE` with a `Decimal128` result was compiled even
when a branch had to be lifted to a larger scale. The compiled lift is an
unchecked 128-bit multiply (`nativeCastWithDecimalScale`), so a value that
does not fit wraps around. Since ClickHouse#124680 the interpreted rescale throws
`DECIMAL_OVERFLOW` for the same input, so the result depended on whether
the expression had been compiled yet (`min_count_to_compile_expression`).

For a 16-byte result the gate now checks the branch's lowest storage value
against `DecimalScaleBounds<Int128>` (the helper the interpreter uses;
`common::mulOverflow` does not detect an `Int128` overflow) and declines
compilation when the lift can overflow. Same-scale `Decimal128` and lifts
that cannot overflow (`Decimal64` by up to 19 digits, `Decimal32` by up to
28) stay compiled. `Decimal256` is never compiled, and `if` with two
decimal branches of different scales is rejected before JIT.

ClickHouse#126516

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

Manerone commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

Backporting to v26.10 as #129166 depends on 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-clickhouse robot-clickhouse 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 #124680 to 26.10: Fix wrong results of decimal comparisons and casts when rescaling to the common scale overflows
leshikus pushed a commit that referenced this pull request Nov 13, 2026
…nd casts when rescaling to the common scale overflows
@groeneai

Copy link
Copy Markdown
Collaborator Author

The new v26.3-must-backport here (for #133349; it expands to 26.3, 26.8 and 26.9) has two gaps:

  1. This PR still carries pr-backports-created from the 26.10 backport, and receive_prs_for_backport in ci/tools/cherry_pick.py searches with -label:pr-backports-created, so the robot skips it. Nothing has been opened in the 10 hours since the label was added, while the robot opened other 26.3 backports today (e.g. Backport #133828 to 26.3: Mask the key of keyed SipHash functions in logged queries #133880).
  2. Fix DECIMAL_OVERFLOW when a decimal is compared with a constant that does not fit its scale #126603 (the fix for canBeSafelyCast decimal rule: key =/IN throw DECIMAL_OVERFLOW #126339, a regression of this PR) only has v26.10-must-backport; on 26.10 both went in together (Backport #124680 to 26.10: Fix wrong results of decimal comparisons and casts when rescaling to the common scale overflows #129268, Backport #126603 to 26.10: Fix DECIMAL_OVERFLOW when a decimal is compared with a constant that does not fit its scale #129323). Without it, this PR makes =, != and IN with a constant that does not fit the key's scale throw DECIMAL_OVERFLOW on Decimal128/Decimal256 sorting keys (canBeSafelyCast decimal rule: key =/IN throw DECIMAL_OVERFLOW #126339), and those queries return the correct result on 26.3.71.2, 26.8.46.4 and 26.9.38.6 today. The same key path already throws there for narrower decimals: d IN (SELECT toDecimal32(300000000, 0)) on a Decimal(9, 1) sorting key gives DECIMAL_OVERFLOW on those three releases, and 0 on an unindexed column and on 26.10.12.5 / 26.11.1.2932.

So the backport needs v26.3-must-backport on #126603 as well, and pr-backports-created removed from both PRs. #126603's cherry-picks will conflict on test 05339_decimal_wide_comparison_scale_overflow (added here) until this PR's backport is merged into each branch; on 26.10 the robot's retry then resolved that by itself (#129265).

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. groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore 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.3-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Integer to Decimal128 / Decimal256 conversion silently wraps instead of raising DECIMAL_OVERFLOW

6 participants