Skip to content

Fix wrong values from JIT-compiled if/multiIf with Decimal result - #103809

Merged
Algunenano merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-decimal-jit-scale-if
May 6, 2026
Merged

Algunenano merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-decimal-jit-scale-if

Conversation

@groeneai

@groeneai groeneai commented Apr 30, 2026 •

Copy link
Copy Markdown
Collaborator

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. This is a data-correctness regression in 26.x, originally reported in #103808.

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

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. The non-JIT path resolves this at runtime via castColumn. The JIT path, in 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; the inline comment explains that JIT-compiled aggregate functions like avg rely on nativeCast to preserve the raw underlying integer of a Decimal accumulator. So the two contracts collide:

  • if needs a value-preserving conversion (lift integer 1 to the stored Decimal value 10^S).
  • avg needs the raw storage cast (treat Decimal as Int128 for accumulation).

Fix. Add a new helper nativeCastWithDecimalScale in src/DataTypes/Native.cpp. It 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. FunctionIfBase::compileImpl now uses this helper. 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 produce wrong values in if for the same reason whenever the analyzer reaches those paths.

Validation.

  • Test tests/queries/0_stateless/04143_if_decimal_int_literal_jit.sql covers if, multiIf, both branches, all Decimal widths, Float -> Decimal, and a sanity row with compile_expressions = 0.
  • Verified the test FAILS without the patch (8+ wrong values) and PASSES with the patch (50/50 stress-runs with randomized settings).
  • Existing JIT regression tests still pass: 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) and sum(Decimal) still produce correct results with compile_expressions = 1.

Closes #103808.

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 a data-correctness regression in 26.x where JIT-compiled if and multiIf with a Decimal result type and a non-Decimal (integer or float) literal in one branch silently returned a value 10^scale too small. The slow (non-JIT) path was unaffected. Workaround on affected versions: SET compile_expressions = 0.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.5.1.343
  • Backported to: 26.4.2.10, 26.3.10.58, 26.2.18.9

… 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.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate self-check (from .claude/skills/fix-ci-failure/SKILL.md):

  • (a) Deterministic repro? Yes. With SET min_count_to_compile_expression = 0; SET compile_expressions = 1; the den-crane reproducer (SELECT sum(if(k != 1, r, 1))) returns 0.0000001 every run on master.
  • (b) Root cause explained? Yes — FunctionIfBase::compileImpl calls nativeCast which only does CreateIntCast for integer-to-integer LLVM casts. For UInt8 -> Decimal(P, S) that means widening the bits without applying the * 10^S factor, so the integer literal 1 becomes the stored Decimal value 1 (i.e. 10^-S) instead of 10^S (i.e. 1.0). PR Continuation of #73509. #88770 introduced this when it made Decimal JIT-compilable; before that, if with mixed Decimal/integer arguments fell through to the non-JIT path and was correct. The intentional design choice in nativeCast (preserving raw bits for avg) made it impossible to fix in-place without breaking aggregate functions, hence the new helper.
  • (c) Fix matches root cause? Yes — nativeCastWithDecimalScale performs exactly the missing * 10^scale / / 10^scale IR emission. No bounds-widening, no tag flips, no test gymnastics. FunctionIfBase is the only call site; nativeCast itself is unchanged so avg/sum accumulator semantics are preserved.
  • (d) Test intent preserved? / new tests added? New regression test 04143_if_decimal_int_literal_jit.sql covers if, multiIf, both branches, Decimal32 / Decimal64 / Decimal128 / Decimal(38, 11), Float -> Decimal, and includes a compile_expressions = 0 sanity block.
  • (e) Both directions demonstrated? Yes. With the patch reverted (git stash) and rebuilt, the new test produces 8 wrong values (0.0000001, 0.0001, 0.00000000001, ...). Restoring the patch turns it green: 30/30 stress-runs with randomized settings, plus 6/6 existing JIT tests (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).
  • (f) Fix is general, not a narrow patch? The same defective code path was present for Decimal -> Decimal (different scales), Float -> Decimal, and Decimal -> Float whenever they reach FunctionIfBase::compileImpl. The new helper handles all of them, plus Nullable wrappers. Every type combination supported by if's isCompilableImpl either gets the proper scale-aware path or falls through to the original nativeCast (which already covers DateTime / DateTime64 / Time / Time64 scale lifts).

Session id: cron:clickhouse-ci-task-worker:20260430-204500.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @alexey-milovidov @Algunenano @rschu1ze — could you review?

This fixes a data-correctness regression introduced by #88770 (JIT compilation for Decimal types). Issue: #103808.

The fix adds a scale-aware cast helper for if / multiIf while keeping nativeCast's raw-bit semantics intact for avg / sum accumulators.

@clickhouse-gh

clickhouse-gh Bot commented May 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c0ab771]

Summary: ✅


AI Review

Summary

This PR fixes a real JIT correctness issue for if/multiIf with Decimal result types by routing branch casts through nativeCastWithDecimalScale and adds focused regression/parity coverage, including high-scale Decimal128/Decimal256 cases. Verdict: no new blocker or major issue found in the current PR state.

ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ✅
Compilation time ✅
No large/binary files ✅
Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label May 1, 2026
Comment thread src/DataTypes/Native.cpp Outdated
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()));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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)
@groeneai

groeneai commented May 1, 2026

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate self-check for the follow-up commit e747670d6f66:

  • (a) Deterministic repro? The bug as described by the bot (FP-narrowing in pow10_fp_const) is in code that is currently unreachable from natural if / multiIf: the analyzer maps if(decimal, float) to Variant(Decimal, Float64), canBeNativeType excludes Variant, and FunctionIfBase::isCompilableImpl therefore returns false. So the buggy path cannot be triggered from SQL today. The bug itself was demonstrated numerically: getZExtValue() of 10^38 (as a 128-bit APInt) returns 687399551400673280 ≈ 6.87e17, off from 1e38 by ~1.45e20×. For scale 30 it returns 5.08e18 instead of 1e30, off by ~1.97e11×.
  • (b) Root cause explained? Yes. nativeCastWithDecimalScale constructed the floating-point scale factor as static_cast<double>(v.getZExtValue()) where v is an APInt sized to the Decimal storage width (up to 256 bits). For Decimal128 with scale ≥ 20 (so 10^scale > 2^63), getZExtValue() keeps only the lower 64 bits and silently drops the high bits, producing a wildly wrong multiplier / divider.
  • (c) Fix matches root cause? Yes. The new pow10_fp_const helper builds the same APInt at the same width and converts it to APFloat via APFloat::convertFromAPInt(v, /*IsSigned=*/false, rmNearestTiesToEven) — the multi-word → float path that LLVM already provides. Two call sites updated through the shared helper. nativeCast and other helpers are untouched.
  • (d) Test intent preserved? / new tests added? Original tests retained. Test 04143_if_decimal_int_literal_jit extended with Decimal128 (scale = 20, 30, 37) and Decimal256 (scale = 60, 73) cases on the reachable integer-literal-to-Decimal path, plus matching compile_expressions = 0 sanity rows. These exercise pow10_int_const at 128-bit / 256-bit widths (which is APInt arithmetic, already correct, but the wide-bit path was previously not covered). The bot-flagged FP path cannot be reached from SQL today, so an end-to-end regression test for the exact bug isn't expressible — covered only by the numeric demonstration above and by the helper's correctness on inspection.
  • (e) Both directions demonstrated? PARTIAL — see (a). Direct test (50 / 50 stable runs of 04143_if_decimal_int_literal_jit.sql with the new high-scale cases): pass. Numerical reproduction of the OLD truncation: confirmed (off by ~1.45e20× at scale 38). A SQL-level FAIL/PASS demonstration of the FP path requires either a gtest that drives nativeCastWithDecimalScale directly, or a future change that lifts the Variant constraint on if(decimal, float).
  • (f) Fix is general, not a narrow patch? Yes. The shared pow10_fp_const helper is used at both buggy sites (Float → Decimal multiplier and Decimal → Float divider) and would handle any new FP↔Decimal call site. The fix targets the upstream cause (APInt narrowing) rather than guarding against the symptom — it preserves all bits regardless of width up to 256.

Session id: cron:clickhouse-ci-task-worker:20260501-051500.

@Algunenano Algunenano added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label May 5, 2026

@Algunenano Algunenano left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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^scale multiplication in Float64".
  • "so it stays correct when 10^to_scale exceeds 64 bits (Decimal128 with to_scale >= 20, Decimal256 with 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.
@groeneai

groeneai commented May 5, 2026

Copy link
Copy Markdown
Collaborator Author

@Algunenano — added a dedicated per-branch parity test in commit 46ae3eb (tests/queries/0_stateless/04205_jit_decimal_cast_branches_parity.sql).

Each case prints the same expression twice with SETTINGS compile_expressions = 1 and SETTINGS compile_expressions = 0; the reference file demands the JIT and interpreter outputs match line for line, so any future divergence in nativeCastWithDecimalScale shows up in the diff with the case label intact.

Coverage of every reachable branch in nativeCastWithDecimalScale:

  • Integer -> Decimal, to_scale = 0: Int8, Int64 (min), UInt8 (255), UInt64 (max)
  • Integer -> Decimal, to_scale > 0: Int8/UInt8/Int16/UInt16/Int32/UInt32/Int64 sources, both signs, into Decimal(9, 4), Decimal(18, 4), Decimal(18, 7), Decimal(38, 11)
  • Integer -> Decimal128, to_scale >= 20 — exercises pow10_int_const with a factor wider than 64 bits: Decimal(38, 20), Decimal(38, 30), Decimal(38, 37)
  • Integer -> Decimal256, to_scale >= 50 — exercises pow10_int_const with a factor wider than 128 bits: Decimal(76, 50), Decimal(76, 75)
  • Decimal -> Decimal, same scale, precision widen: Decimal(9, 4) -> Decimal(18, 4), Decimal(18, 4) -> Decimal(38, 4), Decimal(38, 4) -> Decimal(76, 4)
  • Decimal -> Decimal, scale increase: Decimal(9, 4) -> Decimal(18, 7) (positive + negative), Decimal(18, 4) -> Decimal(38, 30) (factor > 64 bits), Decimal(38, 4) -> Decimal(76, 50) (factor > 128 bits)
  • Decimal -> Decimal, scale decrease (signed divide): cast(... :: Decimal(18, 8) AS Decimal(18, 2)), cast(... :: Decimal(38, 30) AS Decimal(38, 4)) with negative magnitude
  • Nullable arms: Nullable -> Nullable, Nullable -> T, T -> Nullable, plus a NULL-picking case
  • Identity arm (from == to): Decimal(18, 4), Decimal(76, 60)
  • multiIf with high-scale Decimal(38, 30) / Decimal(76, 60) else branch and integer-literal then-branches (the original failure mode from if() with integer literal and joined Decimal column silently returns rescaled wrong value (regression in 26.x) #103808)
  • Materialized inputs (constants are folded before JIT, so materialization is required for the helper to actually run): Decimal(18, 7), Decimal(38, 30), Decimal(76, 73), plus a materialized Int64 -> Decimal(38, 30) source
  • A multi-row multiIf over a MergeTree table where each row picks a different branch

Verified locally: 1/1 single run, 20/20 with full setting randomization (test is unaffected by randomized settings since each case pins compile_expressions per-query, taking priority over the runner injection).

On the Float <-> Decimal paths in the helper. I tried many if(Float, Decimal) shapes; the analyzer always resolves the result to Variant(Decimal, Float) (similarly Variant(Date, Decimal) for Date/Date32). canBeNativeType excludes Variant, so FunctionIfBase::isCompilableImpl returns false and nativeCastWithDecimalScale is never called for those types from JIT today. I cannot exercise those helper branches through SQL if/multiIf, so the test header comment documents it and explains the helper's Float <-> Decimal arms are kept correct (pow10_fp_const uses APFloat::convertFromAPInt, no getZExtValue narrowing) so the helper stays forward-compatible if the analyzer ever stops promoting to Variant. The high-bit-width side of the same pow10_fp_const algorithm is exercised through the reachable pow10_int_const cases above (e.g. Decimal(38, 30) and Decimal(76, 50)/(76, 75) with Integer source), which would also catch any 64-bit-narrowing regression in the shared scale-factor construction.

PR HEAD: 46ae3eb905ee. Ready for re-review.

@Algunenano

Copy link
Copy Markdown
Member

@groeneai The tests look good but I have 2 comments:

  • The float <> Decimal paths use variant because use_variant_as_common_type is enabled by default. Disabling it leads to an error, which is fine. The paths are not exercised but since we have tests that's fine so if they are exercised in the future the test will check for any misbehaviour.
  • All the new test aren't using materialize() so I'm not sure if they are exercising the paths. With all const values the analyzer is free to optimize and not call if at all. Let's check and add it please

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.
@groeneai

groeneai commented May 6, 2026

Copy link
Copy Markdown
Collaborator Author

@Algunenano addressed in c0ab771.

Verified the concern was real. With the previous test version, EXPLAIN actions = 1 showed each toString(if(toBool(N), ..., ...)) collapsing to a single COLUMN Const(String) at planning time — FunctionIfBase::compileImpl was never invoked and nativeCastWithDecimalScale was silently bypassed. Confirmed by re-running the rebuilt test against the master binary (no fix): the materialized_* cases (which DO use materialize() correctly) reported 0.000000000000000000000000000001 instead of 1, exactly the #103808 bug — but the previously-added per-branch cases continued to match compile_expressions = 1 vs 0 because both sides were constant-folded.

Fix: every per-branch case now wraps the if/multiIf condition in materialize(...). With this, the action graph contains an explicit FUNCTION if(materialize(...), ..., ...) node and system.events.CompileFunction / CompiledFunctionExecute increment per distinct compiled signature. EXPLAIN actions = 1 confirmed for representative cases (Int -> Decimal scale lift, multiIf with Decimal else, Nullable Decimal vs typed-NULL).

Coverage trade-off found and documented in the file header. Some branches of nativeCastWithDecimalScale are not reachable from if/multiIf once materialize defeats const-folding:

  • Dec -> Dec scale conversion (both increase and decrease): FunctionIf::executeImpl rejects two Decimal arguments with different scales at planning time with NOT_IMPLEMENTED: "Conditional functions with different Decimal scales", called via executeDryRunImpl from ActionsDAG::updateHeader regardless of compile_expressions. The previous test cases (dec9_4_to_dec18_7, dec18_4_to_dec38_30, dec38_4_to_dec76_50) were silently constant-folded and never exercised the JIT path either; once materialize is added the planner refuses them outright. I dropped these cases and documented the limitation. The Dec -> Dec scale-multiplier and -divider arms in nativeCastWithDecimalScale are still correctness-valid (forward-protection if the analyzer ever inserts implicit casts) but only reachable through explicit cast(...) which uses different machinery, so if-parity testing of them is impossible.
  • Dec -> integer narrowing: same situation — supertype always picks the wider Decimal type.
  • Float <-> Decimal, Date <-> Decimal: unchanged (Variant promotion documented previously).

What is now genuinely exercised through if/multiIf + materialize:

  • Int -> Decimal to_scale = 0 (widen only) — Int8/UInt8/Int64/UInt64 -> Decimal9/18/38
  • Int -> Decimal to_scale > 0, factor <= 64 bits — small precisions
  • Int -> Decimal to_scale > 0, factor > 64 bits but <= 128 bits — Decimal128 storage with to_scale >= 20 (added explicit cases: int8 -> Decimal(38, 35), int16 -> Decimal(38, 33), int32 -> Decimal(38, 28))
  • Int -> Decimal to_scale > 0, factor > 128 bits — Decimal256 storage; either direct (int32 -> Decimal(76, 50), int8 -> Decimal(76, 73)) or via precision-headroom promotion (if(bool, Decimal(38, 30), Int32) -> Decimal(76, 30) because Int32 needs 10 digits + scale 30 = 40 > 38)
  • Dec -> Dec same scale, widen integer storage — all three width transitions (32 -> 64, 64 -> 128, 128 -> 256)
  • Identity (from_type == to_type)
  • Nullable wrappers (T -> Nullable(T), Nullable(T) -> Nullable(T') with identical scales)
  • multiIf with mixed Int + Decimal arms
  • Materialized columns from a subquery (the original if() with integer literal and joined Decimal column silently returns rescaled wrong value (regression in 26.x) #103808 reproducer for Decimal(18, 7), Decimal(38, 30), Decimal(76, 73))
  • Multi-row table with materialized integer keys

Replaced the previously-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.

Verification:

  • Single run: passes
  • --test-runs 20 with full settings randomization: 20/20 passes
  • Both directions demonstrated: master binary (no fix) -> JIT cases produce wrong values (0.000...001 instead of 1); PR branch binary -> JIT and non-JIT match for every row
  • system.events.CompileFunction increments during the test (5+ distinct compiled signatures per run)

PR HEAD: c0ab7718403. cc @rschu1ze

@clickhouse-gh

clickhouse-gh Bot commented May 6, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 91.10% 91.10% +0.00%
Branches 76.60% 76.60% +0.00%

Changed lines: 54.84% (51/93) | lost baseline coverage: 2 line(s) · Uncovered code

Full report · Diff report

@Algunenano
Algunenano added this pull request to the merge queue May 6, 2026
Merged via the queue into ClickHouse:master with commit 6ef7b50 May 6, 2026
165 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label May 6, 2026
robot-ch-test-poll added a commit that referenced this pull request May 6, 2026
Cherry pick #103809 to 26.2: Fix wrong values from JIT-compiled if/multiIf with Decimal result
robot-clickhouse added a commit that referenced this pull request May 6, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label May 6, 2026
robot-ch-test-poll added a commit that referenced this pull request May 6, 2026
Cherry pick #103809 to 26.3: Fix wrong values from JIT-compiled if/multiIf with Decimal result
robot-clickhouse added a commit that referenced this pull request May 6, 2026
robot-ch-test-poll added a commit that referenced this pull request May 6, 2026
Cherry pick #103809 to 26.4: Fix wrong values from JIT-compiled if/multiIf with Decimal result
robot-clickhouse added a commit that referenced this pull request May 6, 2026
Algunenano added a commit that referenced this pull request May 6, 2026
Backport #103809 to 26.2: Fix wrong values from JIT-compiled if/multiIf with Decimal result
alexey-milovidov added a commit that referenced this pull request May 6, 2026
Backport #103809 to 26.3: Fix wrong values from JIT-compiled if/multiIf with Decimal result
alexey-milovidov added a commit that referenced this pull request May 6, 2026
Backport #103809 to 26.4: Fix wrong values from JIT-compiled if/multiIf with Decimal result
@robot-clickhouse robot-clickhouse added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label May 6, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…3809

Backport ClickHouse#103809 to 26.4: Fix wrong values from JIT-compiled if/multiIf with Decimal result
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 30, 2026
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]>
evillique pushed a commit to evillique/ClickHouse that referenced this pull request Sep 30, 2026
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]>
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 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-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

if() with integer literal and joined Decimal column silently returns rescaled wrong value (regression in 26.x)

4 participants