Skip to content

Fix Float32 and BFloat16 conversion to 128- and 256-bit integers - #126191

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-float32-bfloat16-to-wide-integer
Oct 17, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-float32-bfloat16-to-wide-integer

Conversation

@groeneai

@groeneai groeneai commented Oct 16, 2026 •

Copy link
Copy Markdown
Collaborator

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 wrong results when converting Float32 values to Int128, UInt128, Int256, UInt256, Decimal128 or Decimal256, and BFloat16 values to the four wide integer types: a negative fraction such as toInt128(toFloat32(-0.5)) returned -18446744073709551616, values of magnitude 2^63 or more were clamped to about 2^63, and negative BFloat16 values wrapped around.

Description

On 26.8.16.41, toInt128(toFloat32(-0.5)) returns -18446744073709551616 and CAST(toFloat32(1.5) AS Decimal(38, 20)) returns 0.09223372036854775808.

Found by the AST fuzzer oracle on #111005 (CI report): the Float32 set {10} cast into a Decimal(38, 31) key became 9.2e-13, so index analysis pruned the part holding id = 10.

wide::integer is built from a builtin by wide_integer_from_builtin. For float and BFloat16 the generic template is an exact match and wins over the double overload; it narrows through int64_t (uint64_t for BFloat16) and sign-extends from the sign of the float. So |x| >= 2^63 gives about +-2^63, a value in (-1, 0) gives -2^64, and a negative BFloat16 wraps.

Now values with |x| < 2^63 are truncated to int64_t and sign-extended from the truncated value; the rest go through the existing double overload, as does an 8-byte long double (arm64 macOS). A Float32/BFloat16 converts exactly like the same value as Float64: checked for all 2^32 Float32 and 2^16 BFloat16 bit patterns into all four wide types (master is wrong for 2,172,649,469 and 24,832 of them).

Price for in-range Float32 (x86-64-v3): 1.26x (Int128) and 1.79x (Int256) in a bare conversion loop, 1.00x and 1.57x in a ConvertImpl-shaped loop.

03212_variant_dynamic_cast_or_default.reference pinned the (-1, 0) value; two lines go. Draft #107923 makes the same 03212 change by widening Float32 in convertToDecimalImpl, which covers only Decimal targets, not toInt128/toInt256.

The exact CI query (partition key xxHash32(id) % 3) also needs #112966: with this fix alone the cast is right, but the partition pruner still drops the row.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.129-master (included in 26.11 and later)

groeneai and others added 2 commits October 16, 2026 02:33
The generic `wide_integer_from_builtin` template is an exact match for
`float` and `BFloat16`, so it wins over the `double` overload and stores
`to_Integral(rhs)`, a narrowing through `int64_t` (`uint64_t` for
`BFloat16`), then sign-extends from the sign of the floating-point value:

- `|x| >= 2^63` becomes `+-2^63`: `toInt128(toFloat32(1e20))` returned
  9223372036854775808, `CAST(toFloat32(1.5) AS Decimal(38, 20))` returned
  0.09223372036854775808.
- a negative value in (-1, 0) truncates to 0 but gets all-ones upper limbs:
  `toInt128(toFloat32(-0.5))` returned -18446744073709551616.
- a negative `BFloat16` wraps through `uint64_t`: `toInt128(toBFloat16(-5))`
  returned 18446744073709551611.

Values with `|x| < 2^63` (a bit test on the float, false for NaN and
infinities) are now truncated to `int64_t` and sign-extended from the
truncated value; the rest go through the `double` overload, as does an
8-byte `long double` (arm64 macOS) instead of being narrowed through
`int64_t`. So a `Float32`/`BFloat16` converts exactly like the same value
as `Float64` (checked for every bit pattern).
`03212_variant_dynamic_cast_or_default` pinned the (-1, 0) garbage for
`toDecimal128OrDefault`/`toDecimal256OrDefault`.

Price for in-range Float32 on x86-64-v3: 1.26x (Int128) and 1.79x (Int256)
in a bare conversion loop, 1.00x and 1.57x in a `ConvertImpl`-shaped loop
with its finiteness check. `|x| >= 2^63` now costs what the same value
costs from Float64 (~90 ns per element).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`UInt128`/`UInt256` targets were only checked for `abs(x) >= 2^63`. Add one
line comparing them with the `Float64` path for a `Float32` in (-1, 0)
(master gives 2^N - 2^64) and a negative `BFloat16` (master gives 2^64 - 5,
no sign extension). `BFloat16` -> `Decimal` is not implemented, so the
header comment now names only `Float32` for the `Decimal` targets.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

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

Round 1 (head 1cab476e8956): 2 major, 2 nit.

  • ⚠️ BFloat16 -> Decimal128/Decimal256 is rejected (NOT_IMPLEMENTED), so the changelog and test comment overclaimed it. AGREE: wording narrowed.
  • ⚠️ Unsigned wide targets were tested only for |x| >= 2^63. AGREE: one line compares UInt128/UInt256 of a negative Float32 fraction and a negative BFloat16 with the Float64 result; all four comparisons are red on master.
  • 💡 The exact 2^63 boundary has no in-tree line (on x86 master it already equals the Float64 value). Noted.
  • 💡 A cheaper range check in the double overload would allow a single path and speed up Float64 too. Noted; a separate change.

Round 2 (head 25cbf173c919): 0 findings.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. 05401 through clickhouse local on master 2cb89c8b71c1: every line is wrong on every run. Same values on official 26.8.16.41 and 26.3.42.3.
b Root cause explained? The generic wide_integer_from_builtin template is an exact match for float/BFloat16, narrows through int64_t (uint64_t for BFloat16) and sign-extends from the float's sign: +-2^63 for abs(x) >= 2^63, -2^64 for (-1, 0), wrap for negative BFloat16.
c Fix matches root cause? Yes. Fixed in the conversion primitive that every caller uses (ConvertImpl, Decimal column loops, accurate casts, index analysis), no caller-side guard.
d Test intent preserved / new tests added? New 05401, each query red on master, signed and unsigned targets. 03212 reference loses two lines that pinned the (-1, 0) value.
e Both directions demonstrated? Yes: master prints the wrong values on all 7 lines, the fix matches the reference; 50/50 randomized runs pass.
f Fix is general across code paths? All construction paths share the template; double keeps its overload; an 8-byte long double (arm64 macOS) now goes through double (checked with -mlong-double-64); integral types keep the unchanged body.
g Fix generalizes across inputs (params/datatypes/wrappers)? Exhaustive over all 2^32 Float32 and 2^16 BFloat16 bit patterns into Int128/UInt128/Int256/UInt256: identical to the Float64 path. SQL checks over Nullable, LowCardinality, Array, accurate and OrDefault casts, Decimal128/Decimal256, and boundaries.
h Backward compatible? (maintainer-approved exception only) Yes. Only wrong results change; no setting, format or stored state.
i Invariants and contracts preserved? A wide integer built from a float equals the one built from that float as double (proven exhaustively); noexcept and constant evaluation of in-range values are kept.

Session id: cron:clickhouse-impl-slot-41:20261016-031100

@clickhouse-gh

clickhouse-gh Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [25cbf17]

Summary: ✅


AI Review

Summary

PR #126191, reviewed at 25cbf173c919e3fb55880783c9ec2e406c90b24b, corrects Float32 and BFloat16 conversions to wide integers and the affected Float32 conversions to wide decimals. The focused regression test and updated existing test pass in CI. No actionable findings remain.

Final Verdict

Status: ✅ Approve.

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

Copy link
Copy Markdown
Collaborator Author

cc @thevar1able @Algunenano, could you review this and add can be tested (I cannot add labels right now)? For float and BFloat16, wide_integer_from_builtin took the generic template, which narrows through int64_t and sign-extends from the float: toInt128(toFloat32(-0.5)) gave -2^64 and magnitudes of 2^63 or more were clamped. In-range values now truncate through int64_t; the rest use the existing double overload.

@clickhouse-gh clickhouse-gh Bot added the comp-data-types Type system & core datatypes used across query planning/execution. label Oct 16, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 16, 2026
@Algunenano Algunenano self-assigned this Oct 16, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 16, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 25cbf173c with master 6bb427c9a (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of e5791b213; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 785.87 MiB 784.71 MiB -1.16 MiB (-0.15%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

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 ⚠️

969 object files changed (-2.73 MiB total), 4 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/DataTypes/TypeFunctions.cpp.o new 1.00 MiB +1.00 MiB
src/CMakeFiles/dbms.dir/Interpreters/Aggregator.cpp.o 25.56 MiB 26.43 MiB +895.89 KiB (+3.42%)
src/CMakeFiles/dbms.dir/DataTypes/TypeMatchers.cpp.o new 692.78 KiB +692.78 KiB
src/CMakeFiles/dbms.dir/DataTypes/FunctionSignature.cpp.o new 417.14 KiB +417.14 KiB
src/Functions/array/CMakeFiles/clickhouse_functions_array.dir/arrayDotProduct.cpp.o 1.75 MiB 1.55 MiB -201.52 KiB (-11.24%)
src/CMakeFiles/dbms.dir/Functions/FunctionsConversion_impl2.cpp.o 1.31 MiB 1.14 MiB -174.78 KiB (-13.07%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/FunctionsBitmap.cpp.o 2.58 MiB 2.41 MiB -167.40 KiB (-6.35%)
src/CMakeFiles/dbms.dir/Functions/FunctionsConversion_impl1.cpp.o 1.12 MiB 986.07 KiB -160.78 KiB (-14.02%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/vectorFunctions.cpp.o 3.29 MiB 3.43 MiB +148.59 KiB (+4.41%)
src/Functions/array/CMakeFiles/clickhouse_functions_array.dir/arrayCumSumNonNegative.cpp.o 603.16 KiB 466.82 KiB -136.34 KiB (-22.60%)
src/Functions/array/CMakeFiles/clickhouse_functions_array.dir/arrayCumSum.cpp.o 673.15 KiB 538.16 KiB -134.99 KiB (-20.05%)
src/Functions/array/CMakeFiles/clickhouse_functions_array.dir/arrayAggregation.cpp.o 1.29 MiB 1.16 MiB -134.86 KiB (-10.22%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/FunctionsCodingIP.cpp.o 1.27 MiB 1.13 MiB -133.67 KiB (-10.32%)
src/Functions/array/CMakeFiles/clickhouse_functions_array.dir/arrayDifference.cpp.o 592.61 KiB 478.05 KiB -114.56 KiB (-19.33%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/FunctionsJSON.cpp.o 4.26 MiB 4.37 MiB +111.80 KiB (+2.57%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/FunctionsHashingMisc.cpp.o 5.53 MiB 5.61 MiB +83.25 KiB (+1.47%)
src/Functions/array/CMakeFiles/clickhouse_functions_array.dir/arrayDistance.cpp.o 10.19 MiB 10.11 MiB -78.98 KiB (-0.76%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/FunctionsConversion_reg.cpp.o 6.83 MiB 6.75 MiB -78.39 KiB (-1.12%)
src/CMakeFiles/dbms.dir/Functions/FunctionsConversion_impl3.cpp.o 1.87 MiB 1.80 MiB -76.37 KiB (-3.98%)
src/CMakeFiles/dbms.dir/Functions/IFunction.cpp.o 555.11 KiB 631.16 KiB +76.05 KiB (+13.70%)

719 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

4202 translation units recompiled, 20573 s compile time in total, 4196 of them have a recent master baseline.

Translation units without a recent master baseline:

  • programs/keeper/Keeper.cpp (clickhouse-keeper): 7.8 s
  • src/DataTypes/TypeFunctions.cpp: 6.9 s

Job report

@alexey-milovidov alexey-milovidov 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.

Thanks!

@alexey-milovidov alexey-milovidov self-assigned this Oct 17, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 17, 2026
Merged via the queue into ClickHouse:master with commit 2cdf4c6 Oct 17, 2026
524 of 528 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 17, 2026
huldarchen pushed a commit to huldarchen/ClickHouse that referenced this pull request Nov 13, 2026
Since ClickHouse#126191, `wide_integer_from_builtin(self, float)` falls back to the
`double` overload for |x| >= 2^63. That overload passes `self` by reference
to `set_multiplier`, which is recursive and never inlined, so wherever it is
inlined into a batch loop (`convertToDecimalBatch`, `ConvertImpl`) the result
of every row goes through a stack temporary: zeroed, written with two 8-byte
stores and read back with a 16-byte load. On arm that made `decimal_casts`
query ClickHouse#7 (Float32 -> Decimal128) about 8% slower on master, and 13-20% slower
in builds where that temporary lands at 24 mod 64 (16 of 16 such CI builds).

The `double` overload now checks the int64 range in `double` and converts the
in-range value directly; the rest goes to a `NO_INLINE` helper that returns
the integer by value, so the caller's result stays in registers. The range
check accepts exactly the same set of `double` values as the old
`long double` one (no `double` lies in [2^63 - 1, 2^63)), and on aarch64 it
no longer calls `__extenddftf2` + `__lttf2` per row. `float` and `BFloat16`
now go through `double`, which converts them like the same value as
`Float64` by construction.

Results are unchanged: all 2^32 Float32 patterns, all BFloat16 patterns and
~4.7e9 Float64 inputs (6.5e8 on aarch64) convert to the same
Int128/UInt128/Int256/UInt256 bytes as before, on x86-64 and aarch64.

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 comp-data-types Type system & core datatypes used across query planning/execution. pr-bugfix Pull request with bugfix, not backported by default 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.

4 participants