Repository navigation
Cherry pick #103809 to 26.3: Fix wrong values from JIT-compiled if/multiIf with Decimal result - #104241
Merged
Conversation
… integer literal branch After PR #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 #103808.
PR review (`clickhouse-gh` bot, #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: #103809 (comment)
Per-branch JIT-vs-interpreter parity test for `nativeCastWithDecimalScale`, the helper added in PR #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 #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.
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 #103809 to verify the new tests actually exercise the JIT paths rather than being silently constant-folded.
Fix wrong values from JIT-compiled if/multiIf with Decimal result
robot-ch-test-poll
merged commit May 6, 2026
651fe2e
into
backport/26.3/103809
151 of 153 checks passed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Original pull-request #103809
Do not merge this PR manually
This pull-request is a first step of an automated backporting.
It contains changes similar to calling
git cherry-picklocally.If you intend to continue backporting the changes, then resolve all conflicts if any.
Otherwise, if you do not want to backport them, then just close this pull-request.
The check results does not matter at this step - you can safely ignore them.
Troubleshooting
If the conflicts were resolved in a wrong way
If this cherry-pick PR is completely screwed by a wrong conflicts resolution, and you want to recreate it:
pr-cherrypicklabel from the PRYou also need to check the Original pull-request for
pr-backports-createdlabel, and delete if it's presented thereThe PR source
The PR is created in the CI job