Skip to content

Do not JIT-compile a multiIf Decimal128 scale lift that can overflow - #129166

Merged
Manerone merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-jit-multiif-decimal128-scale-lift-overflow
Nov 4, 2026
Merged

Manerone merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-jit-multiif-decimal128-scale-lift-overflow

Conversation

@groeneai

@groeneai groeneai commented Nov 4, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #126516
Related: #124680
Related: #126979

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 JIT-compiled multiIf and CASE returning a wrapped, wrong value instead of throwing DECIMAL_OVERFLOW when a Decimal branch is lifted to a larger scale of a Decimal128 result. Closes #126516.

Description

On 26.10.2.103, SELECT multiIf(number = 0, materialize(toDecimal128(1000000000, 0)), number = 1, toDecimal128(1, 0), toDecimal128(1, 30)) FROM numbers(1) returns -20847100.762815390390123822295304634368 instead of throwing DECIMAL_OVERFLOW; on master #124680 made the interpreted cast throw, but a JIT-compiled multiIf/CASE (compile_expressions, on by default) still returns the wrapped value, so the result depends on how often the expression already ran.

Root cause: FunctionIfBase::scaleLiftCanOverflow exempted every result wider than 64 bits, so the compiled code lifted a branch into Decimal128 with an unchecked 128-bit multiply.

Change: for a 16-byte result the gate now declines a branch whose lowest storage value, multiplied by 10^(result scale - branch scale), does not fit Int128 (DecimalScaleBounds, the check the interpreter uses). Such expressions run interpreted and raise the error. Same-scale Decimal128 and lifts that cannot overflow (e.g. Decimal64 by up to 19 digits) stay compiled.

Other compiled lifts: if with two decimal scales is rejected before JIT (NOT_IMPLEMENTED), compiled CAST/arithmetic/comparison exclude decimals, and Decimal256 is never compiled.

Price (debug build, 100M rows): a lift that is now declined went from 1.26 s compiled to 2.81 s interpreted with short_circuit_function_evaluation = 'disable'; at default settings that shape is not compiled on either binary (6.68 s vs 6.69 s); a same-scale control is unchanged.

Validation: new test 05497_jit_multiif_decimal128_scale_lift_overflow fails on master and passes 50/50 with randomized settings; it also asserts which shapes stay compiled via CompiledFunctionExecute.


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

Version info

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

groeneai and others added 2 commits November 4, 2026 02:36
`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]>
…iled

The test checked the Decimal32 gap-28 lift by value only, which the
interpreter returns identically, so dropping the Int32 arm of the
16-byte block in scaleLiftCanOverflow (or giving a Decimal32 branch the
Int64 lowest) over-declined every Decimal32 lift with a gap of 20..28
and the test stayed green. Assert the compile state of that shape
against the control.

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

groeneai commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (1 finding, fixed)
Finding Verdict
⚠️ The test pinned the compile state of the widest safe Decimal64 lift but not of the Decimal32 one (gap 28), so an over-decline of Decimal32 branches would pass unnoticed. AGREE, fixed: added 05497_d32_kept compared with the compiled control.

Re-review of the fix: no further findings.

@groeneai

groeneai commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. multiIf(number = 0, materialize(toDecimal128(1000000000, 0)), number = 1, toDecimal128(1, 0), toDecimal128(1, 30)) with compile_expressions = 1, min_count_to_compile_expression = 0: master returns -20847100.76... every time.
b Root cause explained? scaleLiftCanOverflow exempted results wider than 64 bits, so a Decimal128 lift was compiled as an unchecked 128-bit multiply that wraps; since #124680 the interpreter throws for the same input.
c Fix matches root cause? Yes. The compile decision is the only place that can prove a lift safe (compiled code cannot raise); the gate now covers 16-byte results with the interpreter's own DecimalScaleBounds check.
d Test intent preserved / new tests added? New test 05497_jit_multiif_decimal128_scale_lift_overflow; no existing test changed.
e Both directions demonstrated? Yes. Fails on master (5 missing DECIMAL_OVERFLOW, declined shapes compiled), passes with the fix; six mutants of the gate (old exemption, over-decline, mulOverflow on Int128, off-by-one, dropped or widened Decimal32 arm) all fail it. 50/50 randomized runs pass.
f Fix is general across code paths? Yes. FunctionIfBase is the only caller of the unchecked lift; if with two decimal scales is rejected before JIT, compiled CAST/arithmetic/comparison exclude decimals, Decimal256 is never compiled (checked).
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Decimal32/Decimal64/Decimal128 branches, Nullable, table columns through CASE, exact boundaries (gap 19/20 for Decimal64, 28/29 for Decimal32) at the lowest value, each side asserted by compile state; same-scale stays compiled.
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change; only the compile decision moves, and results change from a wrong value to the interpreter's error.
i Invariants and contracts preserved? Yes. A compiled lift never overflows the result storage, otherwise the expression is interpreted; results of 64 bits or less take the unchanged checks in the same order.

Session id: cron:clickhouse-impl-slot-7:20261104-030400

@clickhouse-gh

clickhouse-gh Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5f76d2a]

Summary: ✅


AI Review

Summary

The change prevents JIT compilation of potentially overflowing Decimal128 scale lifts in multiIf and CASE, routing them through checked interpreted conversions while retaining compilation for safe lifts. No actionable findings were identified at 5f76d2a0553c819172a3639540f34b3166382ba6.

Missing context / blind spots
  • ⚠️ No local ClickHouse build was available to independently repeat the author's reported before/after JIT runs. The new regression test passed Fast test; the dedicated bugfix validation jobs were dropped, as reported by Finish Workflow. A completed JIT-enabled validation run would close this independent execution gap.
Final Verdict

Status: ✅ Approve. No code changes requested; the source analysis, focused regression coverage, and author's reported before/after results support the fix.

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

groeneai commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator Author

cc @Manerone @george-larionov, could you review this and add the can be tested label so CI runs? scaleLiftCanOverflow exempted results wider than 64 bits, so compiled multiIf/CASE lifted a Decimal branch into a Decimal128 result with an unchecked 128-bit multiply that wraps; the gate now declines such a lift with the interpreter's DecimalScaleBounds<Int128> check, so it runs interpreted and throws DECIMAL_OVERFLOW.

@clickhouse-gh clickhouse-gh Bot added comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... can be tested Allows running workflows for external contributors labels Nov 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

✅ No significant changes.

Binary sizes

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

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

Compile time of recompiled translation units

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

Job report

@Manerone Manerone self-assigned this Nov 4, 2026
@Manerone

Manerone commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

@groeneai ping me for JIT compilation related issues and PRs

@Manerone
Manerone added this pull request to the merge queue Nov 4, 2026
@groeneai

groeneai commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator Author

Noted, I'll cc you on JIT compilation issues and PRs from now on.

Merged via the queue into ClickHouse:master with commit 22cb845 Nov 4, 2026
545 of 549 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 4, 2026
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 4, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 5, 2026
Backport #129166 to 26.10: Do not JIT-compile a `multiIf` `Decimal128` scale lift that can overflow
leshikus pushed a commit that referenced this pull request Nov 13, 2026
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-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... 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-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.

JIT multiIf wraps Decimal128 results instead of throwing DECIMAL_OVERFLOW

5 participants