Repository navigation
Fix wrong values from JIT-compiled if/multiIf with Decimal result - #103809
Conversation
… integer literal branch After PR ClickHouse#88770 enabled JIT compilation for Decimal types, expressions like `if(cond, decimal_col, int_literal)` (and the symmetric form, plus `multiIf` with mixed branches) silently returned a value `10^scale` too small whenever the JIT path was taken. Root cause: the analyzer's automatic CAST insertion does not always wrap the non-Decimal branch of `if` / `multiIf` — it can leave the integer literal as its original type while pinning the function's result type to Decimal. In the slow path, the runtime `if` implementation handles this correctly via `castColumn`. In the JIT path, `FunctionIfBase::compileImpl` calls `nativeCast` to convert each branch to `result_type`, but `nativeCast` deliberately does not perform `Decimal` scale conversion — its existing scale handling covers only `DateTime` / `DateTime64` / `Time` / `Time64`, and the documented reason is that JIT-compiled aggregate functions like `avg` rely on `nativeCast` to preserve the raw underlying integer of a Decimal accumulator. The two contracts collide: `if` needs a value-preserving conversion (lift integer `1` to the stored Decimal value `10^S`), while `avg` needs the raw storage cast. Fix: add a new helper `nativeCastWithDecimalScale` that mirrors `nativeCast` for non-`Decimal` cases but emits the proper `* 10^scale` / `/ 10^scale` IR when one side of the conversion is `Decimal` with a non-trivial scale. Use it from `FunctionIfBase::compileImpl` instead of plain `nativeCast`. The existing `nativeCast` is left untouched, so `avg` and other JIT-compiled aggregates keep their current semantics. The helper also covers `Decimal -> Decimal` with different scales, `Float -> Decimal`, and `Decimal -> Float`, all of which would have produced wrong values in `if` for the same reason once the analyzer started reaching those paths. Reproducer (from den-crane): SET min_count_to_compile_expression = 0; WITH materialize(1::Decimal(18, 7)) AS r, materialize(1) AS k SELECT sum(if(k != 1, r, 1)); -- before: 0.0000001 (wrong) -- after: 1 (matches `compile_expressions = 0`) Closes ClickHouse#103808.
|
Pre-PR validation gate self-check (from
Session id: |
|
cc @alexey-milovidov @Algunenano @rschu1ze — could you review? This fixes a data-correctness regression introduced by #88770 (JIT compilation for The fix adds a scale-aware cast helper for |
|
Workflow [PR], commit [c0ab771] Summary: ✅ AI ReviewSummaryThis PR fixes a real JIT correctness issue for ClickHouse Rules
Final Verdict
|
| llvm::APInt v(to_native_type->getIntegerBitWidth(), 1); | ||
| for (UInt32 i = 0; i < to_scale; ++i) | ||
| v *= 10; | ||
| auto * factor_fp = llvm::ConstantFP::get(value->getType(), static_cast<double>(v.getZExtValue())); |
There was a problem hiding this comment.
v.getZExtValue() is only valid when v fits in 64 bits, but here v is 10^scale in the decimal storage width. For Decimal128 with larger scales (e.g. scale 38), this conversion truncates/asserts and the JIT multiplier/divider becomes incorrect, so if/multiIf can still return wrong values for high-scale decimals.
Please construct the floating constant without narrowing through uint64_t (for example, build 10^scale directly as double/APFloat, or convert APInt to APFloat first) in both Float -> Decimal and Decimal -> Float branches.
There was a problem hiding this comment.
Fixed in e747670d6f66. Replaced both getZExtValue() narrowing sites (Float→Decimal multiplier and Decimal→Float divider) with a shared pow10_fp_const helper that constructs the floating-point constant via APFloat::convertFromAPInt(v, /*IsSigned=*/false, rmNearestTiesToEven) — this preserves all bits of 10^scale regardless of width, so the resulting double factor is correct for Decimal128 scale ≥ 20 and Decimal256 at any scale.
Numeric demo of the original bug: (uint64_t)((__uint128_t)(10^38) & ((1<<64)-1)) = 687399551400673280 ≈ 6.87e17, off from 1e38 by ~1.45e20×. With the new helper the correct 1e38 (as nearest-rounded double) is produced.
One nuance worth flagging: the Float ↔ Decimal branches of nativeCastWithDecimalScale are not reachable today from natural if / multiIf because the analyzer maps if(decimal, float) to a Variant(Decimal, Float64) result, and canBeNativeType excludes Variant, so FunctionIfBase::isCompilableImpl returns false and the JIT path is skipped. The fix is therefore correctness of the helper as written + forward-protection for any future caller; a SQL-level regression test that triggers the buggy path through if / multiIf isn't expressible until that analyzer constraint changes.
For coverage I extended 04143_if_decimal_int_literal_jit.sql with Decimal128 (scale = 20, 30, 37) and Decimal256 (scale = 60, 73) cases on the reachable integer-literal-to-Decimal path. This exercises pow10_int_const at 128 and 256-bit widths (already correct via APInt arithmetic, so it's just defense-in-depth coverage).
cc @Algunenano
PR review (`clickhouse-gh` bot, ClickHouse#103809 (comment)) flagged that `nativeCastWithDecimalScale` constructed the floating-point multiplier / divider for `Float` <-> `Decimal` conversions via `v.getZExtValue()` on an `APInt`. The `APInt` is sized to the destination `Decimal` storage width (up to 256 bits), so for `Decimal128` with `scale >= 20` or `Decimal256` with even larger scales, `10^scale` does not fit in 64 bits and the call drops the high bits, producing a wrong scale factor. For `Decimal128` with scale 38 the resulting factor is `6.87e17` instead of `1e38`, off by `~1.45e20`. Fix: build the floating-point constant by converting `APInt` -> `APFloat` through `APFloat::convertFromAPInt` (which uses the full multi-word -> float machinery), instead of narrowing through `uint64_t`. The conversion is applied at both call sites (`Float` -> `Decimal` multiplier and `Decimal` -> `Float` divider) via a shared `pow10_fp_const` lambda. Note on coverage: today the `Float` <-> `Decimal` paths inside `nativeCastWithDecimalScale` are not reachable from natural `if` / `multiIf` because the analyzer maps `if(decimal, float)` to a `Variant` result type (`Variant(Decimal, Float64)`), and `Variant` is not a native-compilable type in `canBeNativeType`, so `FunctionIfBase::isCompilableImpl` returns false and JIT compilation is skipped. The fix is therefore correctness for the helper as written and forward-protection for any future caller that exercises those branches; SQL-level coverage of the exact buggy path is not possible through `if` / `multiIf` until that constraint changes. The test 04143 is extended with `Decimal128` (`scale = 20, 30, 37`) and `Decimal256` (`scale = 60, 73`) cases on the reachable integer-literal-to- `Decimal` path, which exercises `pow10_int_const` at 128 and 256-bit widths (and which is already correct via `APInt` arithmetic). PR review: ClickHouse#103809 (comment)
|
Pre-PR validation gate self-check for the follow-up commit
Session id: |
Algunenano
left a comment
There was a problem hiding this comment.
In general it looks good, but I see some issues with lack testing, specially for the branches for floating points. @groeneai please add tests for the different floating point types and ranges mentioned in the code, specially confirming the assertions:
- "this matches the precision of the non-JIT path which performs the same
value * 10^scalemultiplication inFloat64". - "so it stays correct when
10^to_scaleexceeds 64 bits (Decimal128withto_scale >= 20,Decimal256with even larger scales)"
We need to make sure the current behaviour without JIT is tested, and that the one with JIT matches exactly in each case.
Also look for other corner cases that we should test with both too based on the different branches in nativeCastWithDecimalScale
Per-branch JIT-vs-interpreter parity test for `nativeCastWithDecimalScale`, the helper added in PR ClickHouse#103809 that `FunctionIfBase::compileImpl` calls to correctly lift integer (and forward-protect float) branches to a `Decimal` result type when JIT-compiling `if`/`multiIf`. Each block prints the same expression twice with `compile_expressions = 1` (JIT) and `compile_expressions = 0` (interpreter); both must match. Coverage: - `Integer -> Decimal` with `to_scale = 0` and `to_scale > 0`, every signed and unsigned integer width from `Int8`/`UInt8` through `Int64`/`UInt64`, including the negative-value / max-magnitude edges - `Integer -> Decimal128` with `to_scale >= 20` (`pow10_int_const` factor exceeds 64 bits) and `Integer -> Decimal256` with `to_scale >= 50` (factor exceeds 128 bits) - `Decimal -> Decimal` for same scale (precision widen only), scale increase and scale decrease, including the 64-bit and 128-bit factor thresholds and signed-divide negative cases - `Nullable` wrappers exercising every recursion arm (`Nullable -> Nullable`, `Nullable -> T`, `T -> Nullable`) - `multiIf` with mixed integer literals and high-scale `Decimal128` / `Decimal256` else branches - The original `materialize(...)` reproducer from issue ClickHouse#103808 with `Decimal(18, 7)`, `Decimal(38, 30)` and `Decimal(76, 73)` Branches NOT exercised because the analyzer promotes the result type to `Variant` and `canBeNativeType` excludes `Variant`, so `FunctionIfBase::isCompilableImpl` returns `false` and the helper is never called from JIT for them: `Float32`/`Float64 <-> Decimal` and `Date`/`Date32 <-> Decimal`. The header comment notes this and explains that the helper code paths for those types are kept correct so the helper is forward-compatible if the analyzer ever stops promoting to `Variant`. The high-bit-width side of `pow10_fp_const` is exercised indirectly through `pow10_int_const` on the reachable integer multiplier path. Verified locally: 1/1 single run + 20/20 with full setting randomization.
|
@Algunenano — added a dedicated per-branch parity test in commit 46ae3eb ( Each case prints the same expression twice with Coverage of every reachable branch in
Verified locally: 1/1 single run, 20/20 with full setting randomization (test is unaffected by randomized settings since each case pins On the PR HEAD: |
|
@groeneai The tests look good but I have 2 comments:
|
The previous test version invoked `if`/`multiIf` with constant condition and constant branches. The analyzer constant-folded each expression to a single `COLUMN Const(String)` at planning time, so `FunctionIfBase::compileImpl` was never called and the JIT path through `nativeCastWithDecimalScale` was silently bypassed. Verified via `EXPLAIN actions = 1`: without `materialize` the entire `toString(if(...))` expression collapses to one constant column; with `materialize` on the condition the action graph contains an explicit `FUNCTION if(...)` node and `system.events.CompileFunction` increments per distinct compiled signature. Wrap each `toBool(N)` condition in `materialize(...)` so the function is evaluated per row. Demonstrated FAIL/PASS in both directions: with the master binary (no fix) the rebuilt test reports `materialized_dec38_30:jit = 0.000000000000000000000000000001` (raw integer `1` instead of `10^30`); with the PR branch binary all rows match between `compile_expressions = 1` and `compile_expressions = 0`. 20/20 stable runs under randomization. Drop the Dec -> Dec scale-increase / scale-decrease cases. They were never exercising the JIT path (constant-folded), and once `materialize` is added `FunctionIf::executeImpl` rejects them at planning time with `NOT_IMPLEMENTED: "Conditional functions with different Decimal scales"` (called via `executeDryRunImpl` from `ActionsDAG::updateHeader`, regardless of `compile_expressions`). The Dec -> Dec scale-conversion arm of `nativeCastWithDecimalScale` is unreachable from `if`/`multiIf` typing; only reachable through explicit `cast(...)` which uses different machinery. Same for the Dec -> integer narrowing arm. Documented in the file header. Replace the unreachable `int8 -> Decimal(76, 75)` (analyzer promotes to `Variant(Decimal(76, 75), Int8)` because Int8 needs precision 3 + scale 75 = 78 > 76) with `int8 -> Decimal(76, 73)` which fits and exercises the 256-bit-factor `pow10_int_const` path. Add explicit 128-bit-factor cases (`int8 -> Decimal(38, 35)`, `int16 -> Decimal(38, 33)`, `int32 -> Decimal(38, 28)`) that stay on Decimal128 storage so the 128-bit `APInt` factor path is covered separately from the 256-bit one. Tighten Nullable cases to use identical scales across the two `if` arms so they pass the interpreter's planning-time check (`T -> Nullable(T)` and `Nullable(T) -> Nullable(T')` with `T.scale == T'.scale` are reachable; mixed-scale Nullable Decimals are unreachable for the same reason as plain Dec -> Dec scale change). Reference for review: addresses @Algunenano's 2026-05-06 request on PR ClickHouse#103809 to verify the new tests actually exercise the JIT paths rather than being silently constant-folded.
|
@Algunenano addressed in c0ab771. Verified the concern was real. With the previous test version, Fix: every per-branch case now wraps the Coverage trade-off found and documented in the file header. Some branches of
What is now genuinely exercised through
Replaced the previously-unreachable Verification:
PR HEAD: |
LLVM Coverage Report
Changed lines: 54.84% (51/93) | lost baseline coverage: 2 line(s) · Uncovered code |
Cherry pick #103809 to 26.2: Fix wrong values from JIT-compiled if/multiIf with Decimal result
…If with Decimal result
Cherry pick #103809 to 26.3: Fix wrong values from JIT-compiled if/multiIf with Decimal result
…If with Decimal result
Cherry pick #103809 to 26.4: Fix wrong values from JIT-compiled if/multiIf with Decimal result
…If with Decimal result
Backport #103809 to 26.2: Fix wrong values from JIT-compiled if/multiIf with Decimal result
Backport #103809 to 26.3: Fix wrong values from JIT-compiled if/multiIf with Decimal result
Backport #103809 to 26.4: Fix wrong values from JIT-compiled if/multiIf with Decimal result
…d if/multiIf with Decimal result
…3809 Backport ClickHouse#103809 to 26.4: Fix wrong values from JIT-compiled if/multiIf with Decimal result
Both new mixed-scale multiIf rows kept the widest-scale Decimal in the final else slot, so the else call site in FunctionIfBase::compileImpl only ever did an identity cast for this shape. It was already covered for integer branches (materialized_dec18_7, materialized_dec38_30), but not for a Decimal branch that must be widened. Swap the last two branches of the Decimal128 variant, so its else is the smaller-scale Nullable(Decimal(9, 4)), lifted by 10^21. The variant keeps every arm it covered before: the sign of the widening cast, factors wider than 64 bits and the Nullable -> Nullable arm, each still reddening only its own rows when broken. Reverting only the else call site of ClickHouse#103809 now reddens that row, and reverting only the then call site reddens the other three lifted lines. On 26.3.9.8 (before ClickHouse#103809) the jit row returns 0.0000000000000000000025 instead of 2.5. Co-Authored-By: Claude Opus 5.5 <[email protected]>
04205_jit_decimal_cast_branches_parity had no row with two Decimal branches of different scales, and its header said such branches cannot reach the JIT from if/multiIf. That holds for if, which rejects them with NOT_IMPLEMENTED at planning time, but not for multiIf: its result type takes the largest branch scale (getLeastSupertype), and FunctionIfBase::compileImpl lifts every branch to it through the Decimal -> Decimal arm of nativeCastWithDecimalScale. A regression of the ClickHouse#103809 scale lift for the ClickHouse#103390 shape was therefore invisible. Add the ClickHouse#103390 query verbatim and one wider variant as jit/no_jit pairs. The variant has a Decimal128 result (factors 10^21 and 10^23, wider than 64 bits), a negative non-constant branch and a Nullable branch, so it covers the sign of the widening cast, the factor width and the Nullable -> Nullable arm, which the issue query cannot. Its branches are Decimal32, so every lift stays overflow-free. Both queries have two conditions: a single-condition multiIf is rewritten to if by optimize_multiif_to_if and then throws. A CompiledFunctionExecute check compares both jit queries with a compiled control, so the rows cannot pass on the interpreter, while the check still holds in builds without the embedded compiler. It reads the last QueryFinish row per log_comment, which keeps it stable under retries and AST-fuzzer re-executions. Replace the false header bullet with the true statement (no branch is narrowed; only multiIf reaches the larger-scale arm), list the arm as exercised, and narrow the Nullable comment's "identical scales". On 26.3.9.8 (before ClickHouse#103809) the new jit rows return 0.015/0.025 and -0.000000000000000000000015/0.0000000000000000000025 from compiled code; on master they match the interpreter. Related: ClickHouse#103390 Related: ClickHouse#103809 Co-Authored-By: Claude Opus 5.5 <[email protected]>
After PR #88770 enabled JIT compilation for
Decimaltypes, expressions likeif(cond, decimal_col, int_literal)(and the symmetric form, plusmultiIfwith mixed branches) silently returned a value10^scaletoo small whenever the JIT path was taken. This is a data-correctness regression in 26.x, originally reported in #103808.Reproducer (from @den-crane):
Root cause. The analyzer's automatic
CASTinsertion does not always wrap the non-Decimalbranch ofif/multiIf— it can leave the integer literal as its original type while pinning the function's result type toDecimal. The non-JIT path resolves this at runtime viacastColumn. The JIT path, inFunctionIfBase::compileImpl, callsnativeCastto convert each branch toresult_type, butnativeCastdeliberately does not performDecimalscale conversion. Its existing scale handling covers onlyDateTime/DateTime64/Time/Time64; the inline comment explains that JIT-compiled aggregate functions likeavgrely onnativeCastto preserve the raw underlying integer of aDecimalaccumulator. So the two contracts collide:ifneeds a value-preserving conversion (lift integer1to the storedDecimalvalue10^S).avgneeds the raw storage cast (treatDecimalasInt128for accumulation).Fix. Add a new helper
nativeCastWithDecimalScaleinsrc/DataTypes/Native.cpp. It mirrorsnativeCastfor non-Decimalcases but emits the proper* 10^scale// 10^scaleIR when one side of the conversion isDecimalwith a non-trivial scale.FunctionIfBase::compileImplnow uses this helper. The existingnativeCastis left untouched, soavgand other JIT-compiled aggregates keep their current semantics.The helper also covers
Decimal -> Decimalwith different scales,Float -> Decimal, andDecimal -> Float, all of which produce wrong values iniffor the same reason whenever the analyzer reaches those paths.Validation.
tests/queries/0_stateless/04143_if_decimal_int_literal_jit.sqlcoversif,multiIf, both branches, allDecimalwidths,Float -> Decimal, and a sanity row withcompile_expressions = 0.01852_jit_if,01072_nullable_jit,02723_jit_aggregation_bug_48120,02024_compile_expressions_with_short_circuit_evaluation,02790_fix_coredump_when_compile_expression,00905_compile_expressions_compare_big_dates.avg(Decimal)andsum(Decimal)still produce correct results withcompile_expressions = 1.Closes #103808.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a data-correctness regression in 26.x where JIT-compiled
ifandmultiIfwith aDecimalresult type and a non-Decimal(integer or float) literal in one branch silently returned a value10^scaletoo small. The slow (non-JIT) path was unaffected. Workaround on affected versions:SET compile_expressions = 0.Documentation entry for user-facing changes
Version info
26.5.1.34326.4.2.10,26.3.10.58,26.2.18.9