Skip to content

Fix wrong results from JIT-compiled float to integer and Decimal conversions - #117590

Merged
Manerone merged 17 commits into
ClickHouse:masterfrom
groeneai:fix-jit-float-to-integer-cast-117442
Sep 8, 2026
Merged

Manerone merged 17 commits into
ClickHouse:masterfrom
groeneai:fix-jit-float-to-integer-cast-117442

Conversation

@groeneai

@groeneai groeneai commented Sep 1, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #117442
Related: #80550

Once JIT-compiled, a comparison whose right side converts a float to an integer can evaluate against
the pre-conversion value. On a UInt8 column sqrt(c0) <= CAST(min2(c0, -c0) AS UInt8) at c0 = 230
returns false though CAST(-230. AS UInt8) is 26 on x86-64. It clears on restart. Reproduced on 26.8.3.3
and 26.9.1.485.

nativeCast (src/DataTypes/Native.cpp:202) lowers a float source with an integer destination to
fptosi/fptoui, which is poison unless the value fits, so the compiled expression is undefined and
the optimizer may fold the uitofp(fptoui(x)) round trip the comparison's promotion creates.
Decimal reaches the same lowering; the interpreted semantics cannot be expressed in IR: it
either throws on input the destination cannot hold or converts it to an architecture dependent
value. Compilation is declined, as division already does (src/Functions/DivisionUtils.h:177). The two gates
reaching it held identical predicates and now share one helper.

Stops compiling: float to integer or Decimal, Bool excepted. Unchanged: Decimal to number,
integer to Decimal, and float to float. No other function's compilability changes.

Declined conversions are interpreted; surrounding expressions still compile. On a release binary a
query whose whole compilable work is float to Decimal conversions is 2.50x slower (26.9.1.485 and
26.8.3.3, 12 timings per arm, CompiledFunctionExecute reading which arm compiled). The performance
suite runs with compile_expressions off, so no test there moves.

The libcalls test loses its float to big integer JIT arm, which this change turns into a duplicate of
its interpreted arm; the reverse direction still reaches __floattisf and __floattidf and stays.

Noticed, not addressed: avgWeighted reaches the same lowering with no observable divergence (see
Related), bitNot and __bitSwapLastTwo (#117613) reach it through unary arithmetic, where the
interpreted answer is also architecture dependent, and integer to Decimal and Decimal to an
integer wrap where the interpreter raises.

@Manerone for review, as @ PedroTadim asked.

Changelog category (leave one):

  • Backward Incompatible Change

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Fixed wrong results from JIT-compiled conversions of a floating point value to an integer or Decimal
type when the value does not fit the destination: a comparison against the converted value could be
evaluated against the pre-conversion value, so the same query could flip between repeated executions.
Such conversions are now evaluated by the interpreter, which also means they raise
CANNOT_CONVERT_TYPE for NaN or Inf and DECIMAL_OVERFLOW on Decimal overflow where an
arbitrary value was previously returned, and that an expression consisting mostly of such conversions
becomes slower. Closes #117442.


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

Version info

  • Merged into: 26.9.1.953-master (included in 26.9 and later)
  • Backported to: 26.8.15.7

groeneai and others added 5 commits September 1, 2026 12:36
nativeCast in src/DataTypes/Native.cpp lowers a floating point source and an
integer destination to a bare fptosi/fptoui. In LLVM those instructions produce
poison when the value does not fit the destination, so the compiled expression
is undefined and the optimizer may fold the uitofp(fptoui(x)) round trip that a
float comparison introduces. The comparison then runs against the
pre-conversion value:

  CREATE TABLE t (c0 UInt8) ENGINE = Memory;
  INSERT INTO t VALUES (230), (250);
  SELECT cbrt(c0) <= CAST(min2(c0, -c0) AS UInt8) FROM t WHERE c0 = 230;
  -- executions 1-3: 1
  -- execution  4+:  0

CAST(-230. AS UInt8) is 26 and cbrt(230) is about 15.17, so the answer is 1.
Once the expression is compiled the comparison is made against -230. instead,
and stays wrong until the compiled expression cache is dropped, which is why the
reporter saw a query flip between repeated executions. Printing the conversion
on its own still shows 26: the wrongness needs the round trip, not a bad cast
value.

The interpreted implementation cannot be matched in IR. ConvertImpl throws
CANNOT_CONVERT_TYPE on non-finite input, and IR cannot throw; beyond Int64 range
its answer is architecture dependent because the conversion is
NO_SANITIZE_UNDEFINED and has no defined result there. Declining compilation is
what division already does for the same reason, see the compilable = false in
src/Functions/DivisionUtils.h. No narrower predicate is correct either: NaN and
Inf are poison for every integer destination, and no native integer type covers
a float type's finite range.

The two compilability gates that reach the lowering held byte-identical
predicates, so the condition is factored into one file-local helper rather than
duplicated. Bool stays compilable because it is reached through nativeBoolCast,
a comparison against zero. Decimal destinations are included because Decimal is
stored as an integer and the scale multiplication happens in floating point.
Decimal to Number and integer to Decimal are unaffected.

The surrounding expression still compiles: an uncompilable child becomes an
input of the compiled function, so only the conversion itself is interpreted.

Two existing tests keep passing with unchanged references but stop exercising a
compiled path, and are annotated accordingly.
The transcendental left hand side was not required to reproduce the divergence,
so a reader should not have to know cbrt(230) to check the expected values.
toFloat64(c0) / 10 gives 23 and 25 against converted values of 26 and 6, and the
reference is unchanged.

Co-Authored-By: Claude Opus 5 <[email protected]>
The test covered the wrong-results half of the change but not the behaviour it
advertises: a non-finite float reaching an integer destination raises
`CANNOT_CONVERT_TYPE` instead of returning a compiled value. Nothing pinned
that, so re-admitting float to integer compilation later would undo it
silently.

Add that assertion and the `toDecimal32` overflow one, which fills the last of
the four (compilability gate x destination kind) cells. Both fail before the
change, returning `0` and `-4501299.2` where they must raise.

The non-finite value is built from the column rather than written as a literal
`inf`: a literal is constant folded, so the exception would be raised at
planning time on both paths and the assertion would prove nothing.

The comment on `isCompilableNumericConversion` said `ConvertImpl` truncates
modulo 2^N. That is wrong twice: a `Decimal` destination raises
`DECIMAL_OVERFLOW` rather than wrapping, and an out of range float to integer
`static_cast` is undefined in C++, not a portable modulo. Generated code is
unchanged.

The test now links the issue it regresses.

Co-Authored-By: Claude Opus 5 <[email protected]>
The error codes and the C++-undefined narrowing are already in the commit that
introduced the predicate, so stating them again above it only duplicates that
text. Keep why the lowering is refused and why `Bool` is exempt.

Comment text only: the preprocessed token stream of the file is identical
before and after (9783 tokens either side), so generated code is unchanged.

Co-Authored-By: Claude Opus 5 <[email protected]>
… test

Converting a float the destination cannot hold is undefined in C++ and the
result differs per architecture: x86-64 truncates to a byte where AArch64
saturates `FCVTZU` to zero, so the two comparisons the reference pinned were
true only on x86-64. Assert that the compiled and the interpreted evaluation
agree instead, which pins no value.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 1, 2026
@groeneai

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex) plus my own cold review of the
resulting code, repeated once per fix round. Three fix rounds, each re-reviewed from the resulting
commit; the fourth review round returned no findings from the independent model.

# Sev Finding Verdict Evidence / action
1 ❌ The regression test pinned undefined behaviour: its reference asserted the result of converting a finite out-of-range float to UInt8, which differs per architecture, so it would fail on every ARM stateless check AGREE, fixed Raised independently by my cold review and by the gate. The interpreter reaches that conversion through the unchecked static_cast in convertNumericGeneral; on x86-64 LLVM substitutes a signed convert (byte 26) while on AArch64 FCVTZU is legal and saturating (0), so the pinned comparison was true only on x86-64. The same file documents this above ToDate32Transform. The value pinning is gone; the out-of-range case is now witnessed by asserting the compiled and the interpreted evaluation of the same expression agree, which pins no value. The three expected-error assertions were already portable and are unchanged
2 ❌ The Bool exception JIT-compiles Nullable(Float) -> Bool and drops the null flag (FunctionsConversion.cpp:3371) DISAGREE Not caused or widened here. The base predicate already returned true for number to number, and Bool is DataTypeUInt8, so float to Bool was admitted identically before this change through the same removeNullable. The flag is discarded in FunctionCast::compile, untouched here, which serves every CAST(Nullable(X) AS Y) with a non-nullable result. Pre-existing and class-wide; disclosed below
3 ⚠️ This description understated the architecture dependence, placing it "beyond Int64 range", and gave the value 26 unqualified AGREE, fixed The dependence begins as soon as the value does not fit the destination, as this change's own reproducer shows. The phrasing came from misreading the in-tree comment cited in finding 1, which is about a huge value converted to Int64, not about Int64 being the boundary
4 ⚠️ The new test omitted the promised non-finite exception and the toDecimal* gate, and the two annotated legacy blocks add no oracle AGREE, fixed Added a non-finite toUInt8 assertion (CANNOT_CONVERT_TYPE) and a toDecimal32 overflow assertion (DECIMAL_OVERFLOW), both built from the table column so they cannot be constant folded, both verified to fail without the fix and checked against a wrong error code and against no code at all. Declined for the 128-bit destination: poison but not folded today, so there is no deterministic wrong value to assert
5 ⚠️ The helper comment carried the interpreter's error codes, a refuted IR alternative and the narrowing argument, i.e. context belonging in the commit message AGREE, fixed It was the only run of five or more added comment lines in the C++ diff, and both removed clauses were already in the two earlier commit messages. Trimmed to the two clauses that justify a non-obvious property (why the lowering is refused, why Bool is exempt). Verified comment-only: the preprocessed token stream is identical either side
6 ⚠️ The new test does not pin that surrounding expressions stay JIT-compiled DISAGREE CompiledFunctionExecute is a per-query counter with no attribution to a call site, so it cannot show that the comparison compiled while the conversion did not, and 02252_jit_profile_events.sql already guards that regression once for the suite (at the cost of four no-* tags). The test's own job, witnessing the conversion fix, is discriminating in both halves
7 💡 The helper comment described all interpreted float conversions as truncating modulo 2^N AGREE, fixed Wrong on both counts: a Decimal destination throws, and for an integer destination the result is an out-of-range static_cast, not a portable modulo. The same conflation was in my description draft and is fixed there too
8 💡 Replace the pinned comparison with one against zero (the gate's suggested remedy for finding 1) DISAGREE Zero is exactly what AArch64 saturates to, so that comparison carries the same divergence it was meant to remove. Only the remedy is declined; the finding is fixed as described in row 1
9 💡 The float arm of the Number to Decimal branch in convertCompileImpl, and its twin in FunctionCast::compile, are unreachable now AGREE, noted Kept: it keeps the two compile paths symmetric and the diff minimal, and costs nothing at runtime since compile runs only after isCompilable
10 💡 04240_jit_float_to_big_int_libcalls no longer exercises the JIT libcalls it is named for AGREE, noted Annotated rather than deleted. Every value in it is in range so its reference is unchanged, and covering the interpreted fallback under compile_expressions = 1 is still worth keeping
11 💡 The new test does not link the issue it regresses, and carries no no-fasttest tag AGREE / DISAGREE Issue URL added as the first line. Tag declined: the test does not fail untagged, because the interpreted results equal the reference and the interpreted path raises both expected errors

| 12 | ⚠️ | Decimal to an integer stays JIT-compiled and diverges from the interpreter in the same way: the compiled path divides by the scale factor and narrows without a range check, where the interpreter raises DECIMAL_OVERFLOW if the whole part does not fit | AGREE / DISAGREE | Found by my cold review this round; no earlier round or gate raised it. Agreed on the mechanism and disclosed in the description, declined as a fix. It is not caused or widened here (that branch admitted compilation before and after), it is outside this change's scope of a floating point source, and it is the exact sibling of the integer to Decimal case already declined on the same grounds, so fixing one and not the other would be incoherent. A correct widening also has to compare the decimal's native width against the destination's and handle a negative value with an unsigned destination, which is not a small fix. Bool is unaffected: both the compiled path and ConvertImpl take the Bool branch before their decimal branch |
| 13 | 💡 | The new second table has no leading DROP TABLE IF EXISTS where the first one does | DISAGREE | Unreachable: the test runner creates a fresh randomly named database per test invocation and no stateless job pins one, so repeated runs cannot collide. 1992 of the 13342 tables created across 0_stateless/*.sql carry no such guard either |

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal
per finding.

One pre-existing observation, disclosed rather than fixed, from finding 2. The compiled CAST path
extracts the null flag of a Nullable input and uses it only when the result type is itself nullable;
with cast_keep_nullable = 0 the internal review measured a NULL returning a value under JIT against
error 349 without it. I have not reproduced that independently, so I report it rather than assert it.
It predates this change, is not specific to Bool or to float sources, and fixing it means declining
a broad class of CAST compilation, well outside a small fix for this issue.

@clickhouse-gh clickhouse-gh Bot closed this Sep 1, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 1, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [239469c]

Summary: ✅


AI Review

Summary

This PR looks reasonable on the production side: it closes the main CAST / toXxx JIT gates for Float -> integer and Decimal destinations. The remaining problem is in the new proof tests: two added CompiledFunctionExecute assertions are still query-wide and can stay green when only a child node compiles, so they do not actually verify the compilation-state contracts they were added to defend.

Findings

⚠️ Majors

  • [tests/queries/0_stateless/05055_jit_float_to_integer_cast.sql:58] The new CompiledFunctionExecute block does not prove that CAST(... AS Bool) or the surrounding comparison are still JIT-compiled. The counter is query-wide, and both probes still contain a separately compilable toFloat64(number) child, so the assertion can stay green even if the target node falls back to the interpreter.
    Suggested fix: make the node under test the only compilable node in the query, or switch to a per-node oracle instead of a query-wide profile event.
  • [tests/queries/0_stateless/04240_jit_float_to_big_int_libcalls.sql:46] The new 04240_int128 probe has the same attribution problem. materialize(2::Int128) + materialize(0::Int128) is itself a compilable child, so the counter can remain non-zero even if the Int128 -> Float64 conversion under test stops compiling.
    Suggested fix: use a shape whose child cannot compile independently, or a per-node signal that attributes compilation to the cast itself.
Final Verdict

Changes requested: the fix path itself is plausible, but the two new compilation-state assertions are not yet proving what the PR description and comments claim.

LLVM Coverage Report

Measured on commit 239469c.

Metric Baseline Current Δ
Lines 88.80% 88.80% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.20% 81.10% -0.10%

Changed lines: Changed C/C++ lines covered: 15/22 (68.18%) · Uncovered code

Full report · Diff report

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

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. One query, no repetition and no restart, using min_count_to_compile_expression = 0 so the expression is compiled on its first execution. Also reproduced on official 26.8.3.3 and 26.9.1.485 from builds.clickhouse.com.
b Root cause explained? Yes. nativeCast emits fptosi/fptoui for a float source with an integer destination; those are poison unless the value fits, so the compiled expression is undefined and the optimizer may fold the uitofp(fptoui(x)) round trip introduced by the comparison's promotion. Printing the conversion alone still shows the correct value, so the round trip is required.
c Fix matches root cause? Yes. The conversion is no longer compiled, so no poison is emitted. No widened bound, no no-random-* tag and no check added at the site of the wrong answer.
d Test intent preserved / new tests added? New test 05055_jit_float_to_integer_cast, covering all four combinations of the two compilability gates (CAST, toXxx) and the two destination kinds (integer, Decimal), and pinning the one visible behaviour change in row (h). The finite out-of-range case is asserted by arm agreement rather than by a pinned value, for the CAST spelling; the toXxx spelling is covered there by the non-finite input, which raises portably. Two existing tests keep passing with byte-identical references and no query removed or weakened; each gained one comment line saying the Float -> direction is now interpreted.
e Both directions demonstrated? Yes. The new test fails on the pre-fix binary and passes on the fixed one. Pre-fix it returns a value everywhere it must raise: CAST(-toFloat64(c0) * 1e9 AS Decimal32(2)) and toDecimal32(-toFloat64(c0) * 1e9, 2) both yield -4501299.2, and toUInt8 of a non-finite float yields 0. For the finite out-of-range case, whose converted value is undefined and architecture dependent, the test asserts instead that the compiled and the interpreted evaluation of the same expression agree: that count is 0 with the fix and 1 pre-fix, with CompiledFunctionExecute = 1 on the compiled arm and 0 on the interpreted one, so the disagreement is genuinely the compiled path.
f Fix is general across code paths? Yes. Both compilability gates that reach the lowering, convertIsCompilableImpl for the toUInt8/toDecimal32 family and FunctionCast::isCompilable for CAST, held identical predicates and now share one helper, so one cannot be fixed without the other. Fixed at the gate, not guarded at the lowering. Three further sites that reach the same instruction are dispositioned in the description.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes, measured against the interpreted arm as oracle: CAST and toUInt8 forms, Float32 source, Nullable(UInt8), UInt16 and UInt128 destinations all diverged before and agree now. Controls unchanged on every arm: in-range float to UInt8, an integer source, and a signed destination wide enough to hold the value. Boundaries -1 -> 255, -256 -> 0, -257 -> 255, 300 -> 44, +/-1e20 -> 0, NaN -> CANNOT_CONVERT_TYPE.
h Backward compatible? (maintainer-approved exception only) Yes. No setting is declared or defaulted, so no SettingsChangesHistory.cpp entry is owed; no serialization or on-disk format change. One visible change, stated in the description: NaN/Inf to an integer now raises CANNOT_CONVERT_TYPE and a float to Decimal overflow now raises DECIMAL_OVERFLOW, both matching the interpreted behaviour where the previous answer was undefined. Both are asserted by the new test, so re-admitting the compilation later cannot undo them silently.
i Invariants and contracts preserved? Yes. The types.empty(), canBeNativeType, getName() != "CAST", argument_types.size() != 2 and removeNullable guards are unchanged ahead of the new predicate, and Decimal to Decimal still returns false. Expression codegen only: no lock, lifetime, serialized format or restart re-entry path is touched.

Also run: 50 randomized runs and 50 more with compile_expressions forced on, both green; an 8-way self-parallel run, 48 of 48; and a 364-test sweep over jit|compile and cast|convert|decimal on both binaries, whose failure sets match apart from two tests that are flaky on both because test_shard_localhost is hardcoded to port 9000.

Session id: cron:clickhouse-impl-slot-5:20260901-174000

@groeneai

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author

cc @antaljanosbenjamin, could you review this? It declines JIT compilation for float to integer and float to Decimal conversions, because nativeCast lowers those to fptosi/fptoui, which is poison unless the value fits, so a compiled comparison against the converted value could be evaluated against the pre-conversion value instead. @ Manerone is already nominated in the description.

Comment thread src/Functions/FunctionsConversion.cpp Outdated

/// Whether a numeric conversion `from` -> `to` can be JIT-compiled.
///
/// Float to integer or `Decimal` lowers to `fptosi` / `fptoui`, poison unless the value fits, where

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.

This helper closes the CAST / toXxx conversion gates, but the same fptosi / fptoui lowering is still reachable through unary arithmetic. FunctionUnaryArithmetic::compileImpl still does nativeCast(..., result_type) for float-input ops with an integral result (src/Functions/FunctionUnaryArithmetic.h:485), and __bitSwapLastTwo is a concrete behavioral mismatch: the interpreter throws BAD_ARGUMENTS for every non-UInt8 input (src/Functions/bitSwapLastTwo.cpp:25-30), while the JIT path first narrows the float to UInt8 and then returns a byte.

So the new invariant is not actually upheld system-wide yet: a JIT-compiled query can still return a value where the interpreted query raises. I think the unary-arithmetic JIT gate needs to reject float inputs when the op's result type is integral, or at minimum __bitSwapLastTwo needs to opt out of compilation and get a focused JIT parity test.

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.

Confirmed on the mechanism, kept out of scope here.

Measured on this PR's binary: SELECT __bitSwapLastTwo(toFloat64(c0)) FROM t returns 1, 1 with compile_expressions = 1 and raises BAD_ARGUMENTS with compile_expressions = 0. A binary built from this PR's base answers identically on both arms, so the divergence is pre-existing on master and untouched by this change.

I also measured how wide the class is, using a shape that really does get compiled (f(-toFloat64(c0)), two compilable nodes in the DAG). Of the 11 unary arithmetic ops that accept a float and produce an integral result, only __bitSwapLastTwo diverges: __bitWrapperFunc and factorial reject the float on both arms, and intExp2, intExp10, roundAge, roundDuration, bitCount, sign, abs and negate agree on both arms.

I am not folding it in because the interpreted contract is itself unresolved in-tree. bitSwapLastTwo.cpp:28-30 says of that BAD_ARGUMENTS: "Should be a logical error, but this function is callable from SQL. Need to investigate this." So the choice between making the compiled path throw as well (compilable = std::is_same_v<A, ResultType>, which keeps the UInt8 BoolMask use compiled) and rejecting the argument type in getReturnTypeImpl is a decision about __bitSwapLastTwo itself, not part of the CAST / toXxx gate this PR closes. I am raising it separately and will link the fix here.

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 separately in #117613, as promised above.

It gates BitSwapLastTwoImpl::compilable on std::is_same_v<A, ResultType>, so the compiled domain
equals the domain apply accepts. On the broader suggestion of gating the driver: I enumerated all 14
FunctionUnaryArithmetic instantiations, and __bitSwapLastTwo is the only one whose apply can throw
while compilable was unconditionally true, so a check in compileImpl would remove JIT coverage
without fixing anything further.

`05055_jit_float_to_integer_cast` witnessed the non-finite conversion only through
`toUInt8`, which is gated by `convertIsCompilableImpl`. `CAST(... AS UInt8)` is gated
by `FunctionCast::isCompilable`, the other gate this change closes, and had no
non-finite witness of its own.

That assertion holds on every architecture, because the interpreter rejects inf and
nan with an explicit check instead of an undefined narrowing conversion. Against the
pre-fix binary the compiled path returns `0` for both rows rather than raising, so
the assertion reddens if compilation is re-admitted.

Also drops an inaccurate claim from the comment above the arms comparison. The
in-tree note it cited is about a huge value converted to `Int64`; -230.0 to `UInt8`
stays inside `Int32` range and does not saturate. Built for x86-64 and for AArch64
at `-O3`, the interpreted byte is 26 on both and the pre-fix compiled arm answers 0
on both, so that comparison already reddens portably.
Comment thread src/Functions/FunctionsConversion.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 239469c52 with master 3594fb131 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 8396165e8; 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.

Object file sizes

8 object files changed (+44.41 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/StorageFileCluster.cpp.o 346.41 KiB 371.27 KiB +24.86 KiB (+7.18%)
src/CMakeFiles/dbms.dir/Storages/StorageFile.cpp.o 1.08 MiB 1.10 MiB +21.23 KiB (+1.92%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

@Manerone

Manerone commented Sep 3, 2026

Copy link
Copy Markdown
Contributor

From my own Claude agent:

Findings

⚠️ Majors

  • tests/queries/0_stateless/04240_jit_float_to_big_int_libcalls.sql:9-17 — this test exists to cover issue JIT: toUInt128(Float64 expr) fails with Could not find symbol __fixunsdfti (CANNOT_COMPILE_CODE) #105031, the JIT float→128/256-bit integer libcalls. After this PR that entire block under --- JIT --- is evaluated by the interpreter, so it
    is now byte-identical work to the --- no JIT --- block below it and exercises __fixsfti / __fixdfti / __fixunsdfti not at all. A comment was added, but the coverage is gone: JIT: toUInt128(Float64 expr) fails with Could not find symbol __fixunsdfti (CANNOT_COMPILE_CODE) #105031 could regress with this test still green. Relatedly, the symbol
    registrations at src/Interpreters/JIT/CHJIT.cpp:467-470 appear to have lost their only emitter. Please resolve this explicitly rather than leaving a test that claims coverage it cannot provide — either name the path that still emits a float→i128
    conversion and keep a test that reaches it, or delete those query lines (and consider the now-unreachable registrations) as part of this PR. The 128-bit → Float half still covers __floattidf and should stay.

💡 Nits

  • Changelog entry — accurate as far as it goes, but it omits the two consequences a user actually notices, both under the default compile_expressions = 1. Suggested replacement:

▎ Fixed wrong results from JIT-compiled conversions of a floating point value to an integer or Decimal type when the value does not fit the destination: a comparison against the converted value could be evaluated against the pre-conversion value, so
the same query could flip between repeated executions. Such conversions are now evaluated by the interpreter, which also means they now raise CANNOT_CONVERT_TYPE for NaN/Inf and DECIMAL_OVERFLOW on Decimal overflow where an arbitrary value was
previously returned, and that expressions consisting mostly of such conversions become slower. Closes #117442.

  • src/DataTypes/Native.cpp:312-325 — nativeCastWithDecimalScale still emits CreateFPToSI for Float → Decimal, the same defect one file away. I checked that its only caller, FunctionIfBase, cannot reach it today: if(Decimal32(2), Float64) resolves to
    Variant(Decimal(9, 2), Float64), which is not a native type, so the branch is dead. Since this PR is what establishes the invariant, a one-line comment or chassert there would stop it from quietly coming back through a future caller.

Tests

  • ⚠️ The Bool carve-out is the only non-constexpr branch the new predicate introduces, and nothing pins it. I confirmed by hand that it behaves correctly, but a "simplification" that drops isBool from the gate would silently stop compiling CAST(float
    AS Bool), and dropping the matching early return in convertCompileImpl would reintroduce fptosi. One line in 05055 — CAST(-toFloat64(c0) * 1e30 AS Bool) and the NaN form, compiled and interpreted — would close it.

That arm asserted that a compiled float to 128-bit or 256-bit integer conversion
resolves `__fixsfti`, `__fixdfti`, `__fixunssfti` and `__fixunsdfti`. Since this
pull request declines to compile a float source with an integer destination, the
arm ran interpreted and duplicated the `--- no JIT ---` block below it, so it
could no longer catch a regression of issue ClickHouse#105031.

Measured with gdb breakpoints on the eight libcall symbols while running the
arm's queries: on master the first stop is `__fixdfti`, on this branch none of
the four `__fix*ti` breakpoints is reached and the first stop is `__floattisf`
from the reverse direction, which stays compiled and keeps its arm.
`Bool` is the one float to integer destination this pull request keeps
compilable, because it is lowered as `value != 0` instead of as a conversion.
Nothing asserted that, so dropping the `Bool` early return in the compile path
would silently lower it as `fptoui` again: measured on master, the compiled
`fptoui` of both `-2.3e32` and a `NaN` to `UInt8` is 0, so the new rows would
read `false` instead of `true`.
`nativeCastWithDecimalScale` lowers a float source with a `Decimal` destination
to `fptosi`, which is poison unless the value fits, the same defect this pull
request removes from the conversion functions. Its only caller, `FunctionIfBase`,
cannot reach it: `if` and `multiIf` over a `Decimal` and a `Float64` branch give
`Variant(Decimal(9, 2), Float64)` by default, which is not a native type, and
with `use_variant_as_common_type = 0` they raise `NO_COMMON_TYPE`. The assertion
keeps a future caller from reintroducing the defect quietly.
The JIT arm also claimed the 256-bit rows, but `canBeNativeType` caps a native
integer at 16 bytes, so those queries were always interpreted and duplicated the
`--- no JIT ---` block: measured `CompiledFunctionExecute > 0` is 1 for
`Int128 -> Float64` and 0 for `Int256 -> Float64`. The arm now holds the 128-bit
rows only.

Its rows compare a compiled value against an interpreted one, so they pass on any
result the interpreter also produces. The added row pins that the 128-bit
conversion is still compiled, comparing it against a 64-bit control rather than
asserting a count, so it holds in a build without the embedded compiler too.
The value rows say nothing about which shape compiles, so they would pass if the
gate stopped admitting `Bool`, or if it admitted the integer destinations again
and returned the interpreted value by luck. Each added shape has a single
compilable child, so a declined `CAST` leaves nothing to compile: measured
through the same channel, `CAST(toFloat64(number) AS Bool)` reports
`CompiledFunctionExecute > 0` as 1 and `CAST(toFloat64(number) AS UInt8)` as 0.
…tible

`FunctionIfBase` described `nativeCastWithDecimalScale` as lifting float branches
to a `Decimal` result, and 04205 called its float paths correct and ready for an
analyzer that stops promoting to `Variant`. Both now contradict the assertion in
the helper: that direction is lowered as `fptosi`, which is poison unless the
value fits, so it has to stay unreachable rather than become reachable later.
@groeneai

groeneai commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 5e5caacd9e3235dfcca742fd0842ed09344c873f

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_release, oracle) / Identity WHERE (NOT(NOT p)) oracle mismatch not reachable from this diff: the reference query is SELECT count(id) FROM tab__fuzz_3 WHERE hasPhrase(message, 'uick brow') and the variant wraps the same predicate in not(not(...)), with no CAST, no float or Decimal conversion and no if / multiIf anywhere. This diff changes only the JIT float-to-integer and Decimal conversion paths. This job's mismatch has 38 error runs across 37 distinct PRs in 30 days against 1682 successes, on head branches with no shared subject #117200 (external, open), which reverts the correctness oracles and removes the amd_release, oracle job itself

171 praktika nodes, 147 OK and 0 dropped; Config Workflow, Style check, CH Inc sync and
Finish Workflow all success; 1 failing check-run and 0 incomplete. The six
Bugfix validation (functional tests, amd64/aarch64) rows CIDB reports at this head are the
expected inversion: the three new regression tests are supposed to fail against the pre-fix
binary, and both jobs report success.

Session id: cron:our-pr-ci-monitor:20260903-220000

@clickhouse-gh clickhouse-gh Bot added the comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. label Sep 4, 2026
Comment thread src/DataTypes/Native.cpp Resolved
Comment thread src/Functions/FunctionIfBase.h Resolved
…poison

`is poison` names an LLVM term without saying what goes wrong at the call site.
State the property directly: `fptosi` / `fptoui` have no defined result once the
value leaves the destination range, which is why a compiled cast can disagree
with `ConvertImpl` rather than raise, and why `nativeCastWithDecimalScale`
asserts on a float source instead of lowering one.

In `FunctionIfBase::compileImpl` the added sentence about float branches goes
away entirely; the only change left on that line is dropping `/float` from the
list of branches the helper lifts, which this fix makes inaccurate.

No functional change.
The block had grown a clause about what `ConvertImpl` does instead, which is
motivation rather than a local invariant and repeated the commit message.
The row it labels does not lift anything: `if(k != 1, toDecimal64(1.5, 4), 2.5::Float64)`
resolves to `Variant(Decimal(18, 4), Float64)`, measured, and `canBeNativeType`
rejects `Variant`, so the expression never reaches the compiler. It stays as a
value pin. Leaving the old label would send the next reader of the new assertion
in `nativeCastWithDecimalScale` to a test that claims the opposite.
@groeneai

groeneai commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

Pushed the three wording fixes. Two more changes ride along in the same push, both from the same objection:

  • FunctionsConversion.cpp: the doc comment on isCompilableNumericConversion carried the same poison phrasing, so it is reworded the same way and trimmed back to the rule the predicate encodes (33dd488).
  • 04143_if_decimal_int_literal_jit.sql:48 labelled a row as a float to Decimal branch lift. Measured, that row resolves to Variant(Decimal(18, 4), Float64) and is never compiled, so the label now says that instead; it contradicted the assertion this PR adds (239469c).

No functional change in the push.

@clickhouse-gh clickhouse-gh Bot added comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... and removed comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. labels Sep 7, 2026
@Manerone
Manerone added this pull request to the merge queue Sep 8, 2026
Merged via the queue into ClickHouse:master with commit 4fc9c8a Sep 8, 2026
174 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 8, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@groeneai @Manerone — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

@groeneai

groeneai commented Sep 9, 2026

Copy link
Copy Markdown
Collaborator Author

Confirmed, and not already addressed: the two Decimal branches of isCompilableNumericConversion do diverge from the interpreter, and this PR changed neither of them (the same divergence reproduces on a pre-merge master binary, so it is pre-existing rather than introduced here).

Measurements, scope and the release check are in #118958. I am preparing a fix off master; nothing to reopen here.

@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 29, 2026
@robot-clickhouse robot-clickhouse added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 29, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 29, 2026
Backport #117590 to 26.8: Fix wrong results from JIT-compiled float to integer and `Decimal` conversions
CurtizJ pushed a commit to CurtizJ/ClickHouse that referenced this pull request Oct 1, 2026
`__bitSwapLastTwo` accepts only `UInt8`, but the compiled path answered for
any argument type, so the same query returned a value or raised
`BAD_ARGUMENTS` depending only on whether the expression got JIT-compiled:

    CREATE TABLE t (c0 UInt8) ENGINE = Memory;
    INSERT INTO t VALUES (230), (250);

    SELECT __bitSwapLastTwo(toFloat64(c0)) FROM t
        SETTINGS compile_expressions = 1, min_count_to_compile_expression = 0;
    -- returned 1, 1
    SELECT __bitSwapLastTwo(toFloat64(c0)) FROM t
        SETTINGS compile_expressions = 0;
    -- Code: 36 BAD_ARGUMENTS

`BitSwapLastTwoImpl<A>::ResultType` is `UInt8` for every `A`, and
`FunctionUnaryArithmetic::compileImpl` casts the argument to the result type
before calling `Op::compile`, so a `Float64` argument was lowered with
`fptoui double to i8` and the swap ran on the narrowed byte. The op is not in
the cast skip list, and `compile`'s own `isIntegerTy` guard cannot fire
because the cast has already made the value an integer. The interpreter never
gets that far: `apply` throws for any `A` other than `UInt8`.

Gate `compilable` on the domain `apply` accepts. `Op<T0>::compilable` is
consulted by both `isCompilableImpl` and `compileImpl`, and `T0` is the type
`apply` receives, so the compiled domain now equals the non-throwing
interpreted domain. This follows c441505 ("Cover all input types in
JIT intExp2"), which narrowed the same member from `true` to a type predicate
for the same reason. `UInt8` keeps its JIT coverage; wider and big integers
lose the same divergence.

`bitNot` reaches the same lowering for float arguments and is left alone: its
`apply` never throws, so there is no defined interpreted answer for the
compiled path to contradict. The only in-tree caller, `MergeTreeIndexSet`,
builds its `ExpressionActions` with the default `ExpressionActionsSettings`
(`can_compile_expressions = false`) and passes a `UInt8` `BoolMask`, so the
skip-index path is unaffected either way.

Related: ClickHouse#117590 (comment)
Related: ClickHouse#117442

Co-Authored-By: Claude Opus 5 <[email protected]>
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Oct 2, 2026
…ed float to integer and `Decimal` conversions
@fm4v fm4v added pr-backward-incompatible Pull request with backwards incompatible changes and removed pr-bugfix Pull request with bugfix, not backported by default labels Oct 3, 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... groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-backward-incompatible Pull request with backwards incompatible changes 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 v26.8-must-backport

Projects

None yet

6 participants