Repository navigation
Fix wrong results from JIT-compiled float to integer and Decimal conversions - #117590
Conversation
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.
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
| 12 | Severity: ❌ blocker / One pre-existing observation, disclosed rather than fixed, from finding 2. The compiled |
|
Workflow [PR], commit [239469c] Summary: ✅
AI ReviewSummaryThis PR looks reasonable on the production side: it closes the main Findings
Final VerdictChanges 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 ReportMeasured on commit 239469c.
Changed lines: Changed C/C++ lines covered: 15/22 (68.18%) · Uncovered code |
Pre-PR validation gate (click to expand)
Also run: 50 randomized runs and 50 more with Session id: cron:clickhouse-impl-slot-5:20260901-174000 |
|
cc @antaljanosbenjamin, could you review this? It declines JIT compilation for float to integer and float to |
|
|
||
| /// 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 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes8 object files changed (+44.41 KiB total), 0 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units8 translation units recompiled, 51 s compile time in total, 8 of them have a recent master baseline. |
|
From my own Claude agent: Findings
💡 Nits
▎ 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
Tests
|
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.
CI finish ledger -
|
| 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
…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.
|
Pushed the three wording fixes. Two more changes ride along in the same push, both from the same objection:
No functional change in the push. |
|
@groeneai @Manerone — ClickGap found the following in this PR:
Close anything that's wrong or already addressed. |
|
Confirmed, and not already addressed: the two Measurements, scope and the release check are in #118958. I am preparing a fix off master; nothing to reopen here. |
Backport #117590 to 26.8: Fix wrong results from JIT-compiled float to integer and `Decimal` conversions
`__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]>
…ed float to integer and `Decimal` conversions
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
UInt8columnsqrt(c0) <= CAST(min2(c0, -c0) AS UInt8)atc0 = 230returns false though
CAST(-230. AS UInt8)is 26 on x86-64. It clears on restart. Reproduced on 26.8.3.3and 26.9.1.485.
nativeCast(src/DataTypes/Native.cpp:202) lowers a float source with an integer destination tofptosi/fptoui, which is poison unless the value fits, so the compiled expression is undefined andthe optimizer may fold the
uitofp(fptoui(x))round trip the comparison's promotion creates.Decimalreaches the same lowering; the interpreted semantics cannot be expressed in IR: iteither 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 gatesreaching it held identical predicates and now share one helper.
Stops compiling: float to integer or
Decimal,Boolexcepted. Unchanged:Decimalto 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
Decimalconversions is 2.50x slower (26.9.1.485 and26.8.3.3, 12 timings per arm,
CompiledFunctionExecutereading which arm compiled). The performancesuite runs with
compile_expressionsoff, 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
__floattisfand__floattidfand stays.Noticed, not addressed:
avgWeightedreaches the same lowering with no observable divergence (seeRelated),bitNotand__bitSwapLastTwo(#117613) reach it through unary arithmetic, where theinterpreted answer is also architecture dependent, and integer to
DecimalandDecimalto aninteger wrap where the interpreter raises.
@Manerone for review, as @ PedroTadim asked.
Changelog category (leave one):
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
Decimaltype 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_TYPEforNaNorInfandDECIMAL_OVERFLOWonDecimaloverflow where anarbitrary 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
26.9.1.953-master(included in26.9and later)26.8.15.7