Skip to content

Report an integer operand that does not fit the decimal result width - #118721

Merged
alexey-milovidov merged 18 commits into
masterfrom
decimal-integer-operand-overflow-117237
Oct 9, 2026
Merged

alexey-milovidov merged 18 commits into
masterfrom
decimal-integer-operand-overflow-117237

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 8, 2026 •

Copy link
Copy Markdown
Member

Closes: #117237

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):

Arithmetic between a Decimal and an integer that does not fit the native width of the decimal result now raises DECIMAL_OVERFLOW instead of silently wrapping the integer operand.

Description

SELECT toDecimal32(1.5, 4) * 9223372036854775807;  -- -1.5 (the multiplier narrowed to -1)
SELECT toDecimal32(1.5, 4) + 9223372036854775807;  --  0.5 (the addend narrowed to -1)
SELECT intDiv(toDecimal32(1.5, 4), -9223372036854775807); -- 1

DecimalBinaryOperation computes in the native signed width of the decimal result (Int32 for Decimal(5, 4)) and static_casts both operands into it, so an integer operand beyond that width wrapped and every row of the result was silently wrong - for constants and for columns alike. Comparing the same pair already reports Can't compare decimal number due to overflow, and the documented contract of Decimal is that excessive digits in the integer part raise an exception.

The narrowing is checked now, under the existing decimal_check_overflow switch: the operation template already has a check_overflow parameter, chosen from that setting, so decimal_check_overflow = 0 keeps the previous behaviour. Only the conversions that can lose information are checked, so a narrower integer into a wider native type costs nothing, and a wider decimal (toDecimal128(1.5, 4) * 9223372036854775807) still computes the product.

Index analysis evaluates key expressions at the endpoints of key ranges, which may lie outside what the query reads. A DECIMAL_OVERFLOW there must only make the range unanalyzable, not fail the query. master now handles this generally (#123535, #117355): KeyCondition::applyMonotonicFunctionsChainToRange treats any non-fatal exception at an endpoint as "cannot analyze", so this PR no longer changes KeyCondition and only keeps the regression test 05331_decimal_integer_overflow_key_analysis.


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

Version info

  • Merged into: 26.10.1.1903-master (included in 26.10 and later)

```sql
SELECT toDecimal32(1.5, 4) * 9223372036854775807;  -- -1.5 (the multiplier narrowed to -1)
SELECT toDecimal32(1.5, 4) + 9223372036854775807;  --  0.5 (the addend narrowed to -1)
SELECT intDiv(toDecimal32(1.5, 4), -9223372036854775807); -- 1
```

`DecimalBinaryOperation` computes in the native signed width of the decimal
result (`Int32` for `Decimal(5, 4)`) and `static_cast`s both operands into it,
so an integer operand beyond that width wrapped and every row of the result was
silently wrong - for constants and for columns alike. Comparing the same pair
already reports `Can't compare decimal number due to overflow`, and the
documented contract of `Decimal` is that excessive digits in the integer part
raise an exception.

The narrowing is checked now, under the existing `decimal_check_overflow`
switch: the operation template already has a `check_overflow` parameter chosen
from that setting, so `decimal_check_overflow = 0` keeps the previous behaviour.
Only the conversions that can lose information are checked, so a narrower
integer into a wider native type costs nothing, and a wider decimal
(`toDecimal128(1.5, 4) * 9223372036854775807`) still computes the product.

Closes: #117237

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [acba390]

Summary: ✅


AI Review

Summary

This PR makes mixed Decimal/integer arithmetic reject out-of-width integer operands with DECIMAL_OVERFLOW, keeps the pre-existing opt-out via decimal_check_overflow = 0, and adds regressions for the previously reported DateTime64/Time64, nullable-divisor, and key-analysis edge cases. I re-checked the current PR head, the final diff, the prior inline threads, and the full CI summary; the earlier review findings are fixed in the current code, CI is all green, and I did not find any new correctness, safety, or performance issues that warrant an inline comment.

Final Verdict

✅ No blocking issues found in the current PR head.

LLVM Coverage Report

Measured on commit acba390.

Metric Baseline Current Δ
Lines 88.30% 88.30% +0.00%
Functions 91.80% 92.10% +0.30%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 89/101 (88.12%) · Uncovered code

Full report · Diff report

@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 Sep 8, 2026
alexey-milovidov and others added 2 commits September 16, 2026 12:56
…mal_check_overflow = 0`

`04340_intdiv_variable_constant_monotonicity` and `04651_intdiv_const_variable_monotonicity_decimal_float` deliberately feed an integer operand that does not fit the native width of the `Decimal` result, to check that key analysis does not claim monotonicity for the wrapped quotient. Under the default `decimal_check_overflow = 1` that operand now raises `DECIMAL_OVERFLOW` instead of wrapping, so the probes failed in Fast test. The wrap still exists with the check disabled and the monotonicity guard must still hold there, so the probes keep their coverage under `decimal_check_overflow = 0`.

CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118721&sha=6188c9929e6cbd74f903cb756974f401f61a348b&name_0=PR&name_1=Fast%20test
PR: #118721

Co-Authored-By: Claude Fable 5.1 <[email protected]>
alexey-milovidov and others added 3 commits October 2, 2026 08:22
…d in subtraction

`executeDateTime64Subtraction` and `executeTime64Subtraction` stored constant
operands in `UInt64`, so a pre-epoch value was widened to a huge unsigned number
and the new narrowing check raised `DECIMAL_OVERFLOW`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…erflow = 0`

These tests (added on master) rely on an integer operand silently wrapping when
narrowed into the native width of a `Decimal32`, which now raises
`DECIMAL_OVERFLOW` by default. Also add the reference for the pre-epoch
`DateTime64` / `Time64` subtraction cases of `05158`.

Fast test: https://github.com/ClickHouse/ClickHouse/actions/runs/35801691935/job/106993726178

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

clickhouse-gh Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit acba390770c6aeb22fcb34fe429d79f5525e6577 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

…onstants

In the constant-constant decimal path, the operands were narrowed with
`castConstantToNative` before the `right_nullmap` check, so
`intDiv(9223372036854775807, nullIf(toDecimal32(2, 0), toDecimal32(2, 0)))`
raised `DECIMAL_OVERFLOW` instead of returning `NULL`. Narrow them only when
the divisor is not `NULL`.

In `executeTime64Subtraction`, a plain `Time` constant was read as `UInt32`,
but `Time` is backed by `Int32`, so a negative value turned into a huge
positive one in mixed `Time` / `Time64` subtraction. Read it as `Int32`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 2 commits October 4, 2026 17:23
…r row is `NULL`

With a constant left operand and a `Nullable` divisor column (or the reverse),
the constant was narrowed into the decimal result width before the divisor null
map was consulted, so `intDiv(9223372036854775807, materialize(CAST(NULL, 'Nullable(Decimal32(0))')))`
raised `DECIMAL_OVERFLOW` instead of returning `NULL`. Fill the result with
defaults when all divisor rows are `NULL`, as the const/const branch already does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
lneves12 pushed a commit to lneves12/ClickHouse that referenced this pull request Oct 5, 2026
parseDateTimeBestEffortImpl dereferences in.position() in the
num_digits == 0 branch with no eof() check. The enclosing
while (!in.eof()) loop only guarantees a readable byte at the top of an
iteration, and the alphabetical-month branch both leaves num_digits == 0
and can consume the last byte of the value, so a value such as '1-Jan'
reaches that read with the position already at the end of the buffer.

Since 0bd3c24 ("Remove zero byte", ClickHouse#85063) ColumnString no longer
stores a trailing terminator, so getDataAt() returns a span ending
exactly at the value. The byte read is therefore the first byte of the
next row, or the uninitialized right padding of the chars array when the
value is the last row. When that byte is one of ' ', 'Z', '.', '+' or
'-', the code advances the position past working_buffer.end();
BufferBase::available() is an unclamped size_t(end - pos), so it wraps,
eof() never becomes true again, and the parser keeps consuming the
neighbouring rows.

The consequence differs by caller. The conversion family re-checks
isAllRead(), so parseDateTimeBestEffort*, parseDateTime64BestEffort* and
toDateTime with date_time_input_format = 'best_effort' reject a valid
value (NULL, zero, or CANNOT_PARSE_TEXT). addMonths and the rest of the
add-interval family over a String argument do not re-check, so they
return date and time fields taken from the following row.

Guarding the read with eof() restores the control flow the terminator
used to produce: '\0' fell through to readAlpha, which returned zero
characters and broke out of the loop. eof() attempts a refill first, so a
value straddling a chunk boundary in a refillable ReadBuffer keeps
parsing; a plain pointer comparison would have stopped early there.

Reported by the memory sanitizer as
use-of-uninitialized-value src/IO/parseDateTimeBestEffort.cpp:703:26 in
Unit tests (msan, function_prop_fuzzer) on PR ClickHouse#116042 (914a539) and
PR ClickHouse#118721 (906e40f), and at the same column in 2024 as issue ClickHouse#61771.
PR ClickHouse#61694 added this same guard to the comma branch of this loop; the
num_digits == 0 branch was not part of that change.

Related: ClickHouse#61771
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (no conflicts) and pushed 050cdee8907. The PR's tests (05158, 04833, 04340, 04651, 05227) pass locally on the merged tree.

The two red jobs on abb18b7a don't look caused by this PR:

@groeneai, please investigate these failures and fix them in a separate PR. If a fix is already in progress, link it here.

@groeneai

groeneai commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator

Reproduced on a master debug build (468fbe0bb0dd), so it is not caused by this PR. The aborting part all_4_4_0 does not hold 0..9: it holds 10 NULLs, written through the async insert queue by the fuzzed INSERT INTO t_intdiv_mono__fuzz_43 SELECT toDecimal64(divide(number, toFixedString(NULL, 7)), 4) FROM numbers(10) (server.log, 20:54:53.794), which the generated reproducer drops. Minimal:

CREATE TABLE t (a Nullable(Int64)) ENGINE = MergeTree ORDER BY a
SETTINGS index_granularity = 2, allow_nullable_key = 1;
INSERT INTO t SELECT NULL FROM numbers(10);
SELECT count() FROM t WHERE intDiv(a, -3) = -2; -- aborts in debug

It is neither Decimal nor IN specific: intDiv(a, -3) = -2 aborts, while intDiv(a, 3) = 2, negate(a) = -2 and a IN (2) do not. Release builds 26.3, 26.6, 26.8 and a 26.9 master build return the correct 0; 25.8 returns 6. #121089 does not cover it (it only exempts null-aware set atoms over a bare key), so I'll fix it in a separate PR and link it here.

01035_avg: the fix is #124000 (makes the test four times cheaper; opened for the same TSan timeout on #116101).

huldarchen pushed a commit to huldarchen/ClickHouse that referenced this pull request Oct 5, 2026
The test inserted 1,000,000 rows of 18 wide computed columns (Int256,
UInt256, Decimal256 defaults, about 79 MiB compressed) and scanned them
four times. Under tsan with s3 storage it exceeded the 180 s budget of
the targeted lane (192 s on ClickHouse#116101, 248 s on ClickHouse#118721) and ran over
180 s 20 times on master in 30 days in `amd_tsan, s3 storage, parallel`.

Insert 250,000 rows instead and regenerate reference lines 2-5. The
assertions stay exact averages over the same expressions and types:
8 and 16 bit columns still wrap, and a local-disk read still uses at
least 2 streams (32 marks, above the 24-mark concurrent-read minimum).
The new values match a direct recomputation from numbers(250000).

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

groeneai commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator

The fix for the Inconsistent KeyCondition behavior failure is #124111: for a decreasing function of a Nullable key, index analysis turned a granule of only NULLs into the whole range and dropped the NULLs of a [x, NULL] granule. On 26.8 the same defect returns wrong results for intDiv(a, -3) IN (NULL) with transform_null_in = 1.

The AST fuzzer failure on 050cdee has a different trigger (... IN divide(a, nan), STID 5182-6d6b): it also aborts debug builds on a non-Nullable key, and #124111 does not change it.

… key endpoint

Index analysis evaluates a key expression at the endpoints of the key ranges, both in
the `plus`/`minus` monotonicity probe and when `applyMonotonicFunctionsChainToRange`
applies the chain (the latter evaluates the whole index column at once and is reached
without a probe for a single-point range). With the narrowing check of this PR, mixed
`Decimal`/integer arithmetic raises `DECIMAL_OVERFLOW` for an endpoint beyond the native
width of the result, which failed the whole query even when another condition
restricted it to a safe slice of the key:

    SELECT * FROM t WHERE a < 2 AND a + toDecimal32(1, 0) BETWEEN 1 AND 3

Treat such an overflow in `applyMonotonicFunctionsChainToRange` as "this range cannot be
analyzed", the same as a non-monotonic function. The cached whole-column result in
`applyFunction` used to be left as a null column when the function threw, so the next
lookup dereferenced it; now the failure is cached explicitly and reported again.

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

Copy link
Copy Markdown
Member Author

🕵 Pushed fc621ef09e5, which addresses the AI review. Index analysis no longer fails with DECIMAL_OVERFLOW when a key range endpoint does not fit into the native width of the Decimal result (KeyCondition::applyMonotonicFunctionsChainToRange treats it as "cannot analyze"). It also fixes the null cache entry applyFunction left behind after such an exception. New test: 05331_decimal_integer_overflow_key_analysis.

Thanks @groeneai for #124111 and #124000. The remaining red job on 050cdee8907 is AST fuzzer (amd_debug, targeted), Inconsistent KeyCondition behavior (STID: 5182-6d6b), on ... IN divide(a, nan): https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118721&sha=050cdee89076393df1eb4fe8bed1243f20993df8&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29
divide(a, nan) has a Float64 result, so it never reaches the Decimal narrowing this PR changes, and you reported that it aborts on a non-Nullable key on master as well.

@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118721&sha=050cdee89076393df1eb4fe8bed1243f20993df8&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

@groeneai

groeneai commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator

divide(a, nan) aborts the same way on master (debug build at 44b568f4e45) with a plain key, no Nullable and no set involved:

CREATE TABLE t (a UInt64) ENGINE = MergeTree ORDER BY a SETTINGS index_granularity = 2;
INSERT INTO t SELECT number FROM numbers(10);
SELECT count() FROM t WHERE divide(a, nan) = 0; -- Inconsistent KeyCondition behavior

matchesExactContinuousRange asks each function of the chain for monotonicity with Null points and requires is_always_monotonic (KeyCondition.cpp:6313). For variable / constant the answer is "always monotonic" (FunctionBinaryArithmetic.h:4110): a nan constant passes the == 0 check and reads as a negative divisor, because accurateLess(0, nan) is false. Every key value maps to NaN, so the claimed exact range cannot hold.

The fix is already in progress: #118720. Its constant.isNaN() branch declines monotonicity before that return, whatever the points are. I ran its CI amd_debug binary (4b8c55f25aa) on the 10 shapes that abort on master: =, < and IN over divide(a, nan), the fuzzer's lowCardinalityKeys(toLowCardinality(5)) IN divide(a, nan) on a copy of the carrier table, -nan, a DESC key, and Float64 and Nullable keys. All of them return the correct count. Its test does not cover x / nan in index analysis yet; the query above would.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed 4b39c168e50: fixed the Build (arm_tidy) failure (performance-move-const-arg in KeyCondition::applyFunction, a redundant std::move into ColumnWithTypeAndName) and merged master. The PR's tests (05158, 05331, 04833, 04340, 04651, 05227) pass locally on the merged tree.

Thanks @groeneai for tracking down divide(a, nan). It is unrelated to this PR and is being fixed in #118720.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed: merged master and disabled parallel replicas in the EXPLAIN of 05331_decimal_integer_overflow_key_analysis (the plan has no Granules line under parallel replicas, which failed the ParallelReplicas job).

@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118721&sha=4b39c168e50772946cab8542f2a6071a471ec270&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%2C%20old_compatibility%29 (Logical error: Invalid binary search result in MergeTreeSetIndex, query SELECT count() FROM merge('t.*') WHERE intDiv(a, -2) IN toUInt256(3) over Decimal keys) and provide a fix in a separate PR. If the fix is already in progress, link it here. It is not specific to this PR: the same exception hit AST fuzzer runs of #101264, #121116, #119302, #118606, #113515, #116252, #113909 and #97302 in the last 60 days.

@groeneai

groeneai commented Oct 7, 2026

Copy link
Copy Markdown
Collaborator

The trigger in this run is not a Decimal key. The aborting child is t_intdiv_mono__fuzz_13 (a UInt16), which merge('t.*') reads as UInt64 (server.log: intDiv(_CAST(column 0, 'UInt64'), -2) in 1-element set). Index analysis skips a widening integer cast on primary-key bounds and evaluates intDiv on the UInt16 index column, where the dividend becomes Int16 (65535 -> -1), so a mark range comes out reversed. With default settings it drops rows on master:

CREATE TABLE t (a UInt16) ENGINE = MergeTree ORDER BY a;
INSERT INTO t SELECT number FROM numbers(65536);
SELECT count() FROM t WHERE intDiv(CAST(a, 'UInt64'), -2) = -100; -- 0, expected 2

The fix is in progress: #116699.

The other runs have different triggers:

@groeneai

groeneai commented Oct 7, 2026

Copy link
Copy Markdown
Collaborator

The 1969-12-31 part of #121116 is fixed in #124470: the monotonicity factors of toMonth, toDayOfMonth, toHour and three other date-part functions saturated a local 1969-12-31 into 1970-01-01. The #121116 carrier itself still also needs #121265.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks @groeneai. So the Invalid binary search result in MergeTreeSetIndex failure on 4b39c168e50 comes from the UInt16 child of merge('t.*') (a widening cast skipped on primary-key bounds, fixed in #116699), not from the Decimal narrowing in this PR, and the related 1969-12-31 saturation is fixed in #124470. The latest commit cc11abb187d passes CI. The only red jobs are the expected xfail results in "Bugfix validation" (the new tests fail on the old binary). Nothing else to change here.

…rand-overflow-117237

Conflicts in `KeyCondition.cpp` resolved in favor of `master`: #123535 and #117355 made
`KeyCondition::applyMonotonicFunctionsChainToRange` treat any non-fatal exception at a range endpoint
as "cannot analyze" and `applyFunction` cache a failure sentinel for every exception. That subsumes
this PR's `DECIMAL_OVERFLOW`-only handling, so the PR's `applyMonotonicFunctionsChainToRangeImpl`
split is dropped from `KeyCondition.cpp` and `KeyCondition.h`.

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

Copy link
Copy Markdown
Member Author

🕵 Merged master and pushed acba390770c. The conflicts were in KeyCondition.cpp. master (#123535, #117355) now makes KeyCondition::applyMonotonicFunctionsChainToRange treat any non-fatal exception at a range endpoint as "cannot analyze", and applyFunction caches a failure sentinel for every exception. That covers the DECIMAL_OVERFLOW-only handling this PR had, so I took master's KeyCondition.cpp/KeyCondition.h. The PR now only changes FunctionBinaryArithmetic.h and tests. The PR's tests (05158, 05331_decimal_integer_overflow_key_analysis, 04833, 04340, 04651*, 05227) pass locally on the merged tree. I updated the description to match.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Perfect.

@alexey-milovidov alexey-milovidov self-assigned this Oct 9, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 9, 2026
Merged via the queue into master with commit 2fb963f Oct 9, 2026
153 checks passed
@alexey-milovidov
alexey-milovidov deleted the decimal-integer-operand-overflow-117237 branch October 9, 2026 04:06
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 9, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 9, 2026
Since ClickHouse#118721 an integer constant that does not fit the native width of a
Decimal result raises DECIMAL_OVERFLOW by default, so the
`Array(Decimal(9, 0)) * 9223372036854775807` lines failed in the merge queue
with Code 407 instead of comparing the hoisted and the original form. The
wrap that makes the hoist wrong is still reachable with
`decimal_check_overflow = 0`, which is how ClickHouse#118721 adjusted the sibling test
05227; do the same here.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

3 participants