Repository navigation
Fix wrong results of decimal comparisons and casts when rescaling to the common scale overflows - #124680
Conversation
…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]>
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
Severity: ❌ blocker / Session id: cron:clickhouse-review-self-slot-58:20261008-154800 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-self-slot-57:20261008-145300 |
|
Workflow [PR], commit [0b8aeb3] Summary: ✅
AI ReviewSummaryThe PR makes rescaled Missing context / blind spots
Final VerdictStatus: ✅ Approve. |
Algunenano
left a comment
There was a problem hiding this comment.
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.
|
|
||
| /// `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()) |
There was a problem hiding this comment.
Please prefer if { if ...} (aka a nested if means the parent uses braces)
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]>
|
Thanks. I measured it (AVX-512 host, release
The nested |
CI finish ledger - f09691eEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
All 152 check runs completed and Session id: cron:our-pr-ci-monitor:20261009-023006 |
Algunenano
left a comment
There was a problem hiding this comment.
🤖
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 1Also, 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))); -- 1Before, 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 1000000000IN (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_OVERFLOWThe 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.
|
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:
|
|
@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]>
Decimal128 / Decimal256 comparisons when rescaling to the common scale overflows|
Done in 1984e64 (one commit on top of the previous head).
Since performance is not the goal here, I removed the x86-64-v4 dispatch of the two-column loop. The description lists the cost. |
Build profile diff (arm_release)Comparing Binary sizes
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 Object file sizes
|
| 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.
`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]>
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]>
`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]>
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
`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]>
|
Backporting to v26.10 as #129166 depends on it |
Backport #124680 to 26.10: Fix wrong results of decimal comparisons and casts when rescaling to the common scale overflows
…nd casts when rescaling to the common scale overflows
|
The new
So the backport needs |
Closes: #122134
Related: #38223
Related: #69304
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed wrong results of comparisons,
has/indexOfand casts ofDecimal128/Decimal256values when bringing a value to a larger scale does not fit the type:toDecimal128(1, 30) < 1000000000returned0, andCAST(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) < 100threwDECIMAL_OVERFLOW), and such a cast, also from an integer (aUInt256turned negative), throwsDECIMAL_OVERFLOW.Description
On 26.8.18.2,
toDecimal128(1, 30) < 1000000000returns0andCAST(toDecimal128(1000000000, 0) AS Decimal(38, 30))returns-20847100.76.... The rescale to the common scale is checked withcommon::mulOverflow, which wraps and reports success forInt128/Int256.decimal_check_overflow = 1and 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 withfloor(k / m); between two columns each value is checked against[min / m, max / m].Decimal32/Decimal64threwDECIMAL_OVERFLOWhere (00700_decimal_compareand04523_type_pair_matrix_errorschange). TheFieldcomparison (primary key analysis) uses the same helper.CASTand casts to the common type behindArray/Mapcomparison,JOINkeys andarrayMaxthrowDECIMAL_OVERFLOW;accurateCastOrNullreturnsNULL,IN (SELECT ...)returns0(00700_decimal_casts_2pinned a wrapped value). AUInt256aboveInt256max is rejected before it turns negative (toDecimal256(bitNot(toUInt256(0)), 1)was-1).has,indexOf,countEqual,indexOfAssumeSortedandmapContainsValuewith decimals of different types compare asequalsdoes, after widening both sides toDecimal256at their own scale, instead of casting to the common type.Not changed:
greatest/leastand 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
has2.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
26.11.1.92-master(included in26.11and later)