Skip to content

Fix out-of-range Float64 to Int32/UInt32 conversion depending on the row position on aarch64 - #133517

Merged
alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-float-to-int32-aarch64-interleave
Nov 22, 2026
Merged

alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-float-to-int32-aarch64-interleave

Conversation

@groeneai

@groeneai groeneai commented Nov 22, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #133509
Related: #117346
Related: #128538

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

Description

On aarch64 master, the same out-of-range Float64 converted to Int32/UInt32 gives two values in one column: SELECT groupArray(CAST(materialize(-81183017266.28046) AS Int32)) FROM numbers(5) returns [421361358,421361358,421361358,421361358,-2147483648]. Found by SQLancerPP (arm_release) / NoREC (report): WHERE counts 12 rows, the same predicate in the SELECT list 9.

Cause: since #117346 (fa5cc176) the check-free conversion loop in convertNumericGeneral has #pragma clang loop vectorize(disable), which still allows interleaving. On aarch64 clang 23 interleaves it by 4 and the SLP vectorizer packs the copies into fcvtzs v.2d + uzp1 (wraps), while the remainder rows use scalar fcvtzs w (saturates). The first parent of #117346 saturated in every row.

Change: on aarch64, Float64 to Int32/UInt32 gets its own loop that clamps the value to the range of the result type before converting. That gives the saturated value of the scalar instruction in every row, and the loop stays vectorized. Disabling interleaving instead made intDiv #2 (toUInt32 of Float64) 24% slower in this PR's arm performance comparison. The other pairs keep the current code: their vector and scalar instructions saturate alike. Reverting fa5cc176 would also fix it, but brings back the per-row check. The 26.11 branch, not released yet, has the same loop.

Validation:

  • the new test fails on the CI aarch64 binary of 903285ff; on a local aarch64 cross build it passes, fails with the clamp disabled, and passes again. The original NoREC statements give 12/12.
  • toInt32/toUInt32/CAST of 1019 values (out of range both ways, the bounds, fractions) give the same results as the CI binary of the first parent of Use clang-23 #117346.
  • llvm-mca for Neoverse V2 (the arm performance runners): 0.75 cycles per row, as on master.
  • The new code is aarch64-only, so the x86-64 code is that of master.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.12.1.178-master (included in 26.12 and later)

groeneai and others added 2 commits November 22, 2026 09:08
Since ClickHouse#117346 (fa5cc17, "Check for NaN and Inf in a separate pass in the
float to integer conversion") the non-accurate Float -> Int (>= 32 bit)
conversion in convertNumericGeneral runs in a loop marked only
`#pragma clang loop vectorize(disable)`. That pragma sets the vector width to
1 but does not disable interleaving. On aarch64 clang 23 interleaves the loop
by 4 and the SLP vectorizer packs the copies into `fcvtzs v.2d` + `uzp1 v.4s`,
which keeps the low 32 bits of the 64-bit conversion (wraps), while the
n % 4 remainder rows use scalar `fcvtzs w, d`, which saturates. An
out-of-range Float64 -> Int32/UInt32 therefore gave different values for the
same input in one column, depending on block size and row position:

    SELECT groupArray(CAST(materialize(-81183017266.28046) AS Int32)) FROM numbers(5)
    -- [421361358,421361358,421361358,421361358,-2147483648]

SQLancerPP (arm_release) NoREC found it as a WHERE vs SELECT-list count
mismatch (12 vs 9). The first parent of ClickHouse#117346 saturated in every row.

Add interleave(disable), the remedy already used in DataTypesDecimal.cpp, so
the loop is scalar as its comment requires. The comment's old description of
which instruction wraps was the x86 view and the opposite of aarch64.

Validated on a local aarch64 cross build: the new test passes with the fix,
fails with only the token removed, passes again with it restored; it fails on
the CI aarch64 binary of 903285f. x86-64 is not affected: with CI's
AMD_BINARY flags all 34 FunctionsConversion*.cpp.o objects disassemble
identically with and without the change.

Closes ClickHouse#133509

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

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

Pre-publication review by an independent model (engine: codex; 1 finding) plus my own cold review (2 notes). No blocker or major findings.

# Sev Finding Verdict Evidence / action
1 💡 The commit message does not carry the CI report URL (.claude/CLAUDE.md, "include it in the commit message") AGREE, not blocking The rule applies. Amend is not allowed on a branch, so the URL is in the PR body and in #133509 instead.
2 💡 On aarch64 the loop is now scalar for every float to 32/64-bit integer pair, also for pairs whose vector conversion was consistent AGREE, no change It is what the loop's own comment requires, and it was scalar (with a per-row check) before #117346. Stated in the description.
3 💡 The result of an out-of-range conversion still depends on the pragma, not on defined semantics noted Same as before #117346. The new test runs on the aarch64 stateless jobs, and float to integer is not JIT-compiled, so compile_expressions cannot bypass the loop.

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

Session id: cron:clickhouse-review-slot-8:20261122-091000

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The new test on the CI aarch64 binary of 903285ff (qemu) prints 2 2 2 2 / 2 2 / 0 0 every run; the original NoREC statements give WHERE 12 vs projection 9, as in CI.
b Root cause explained? vectorize(disable) leaves interleaving on. On aarch64 clang 23 interleaves the loop by 4 and SLP packs it into fcvtzs v.2d + uzp1 (wraps), the remainder is scalar fcvtzs w (saturates), so the result depends on the row position.
c Fix matches root cause? Yes. interleave(disable) keeps the loop scalar, as its comment requires (same remedy as DataTypesDecimal.cpp). No guard, no bound, no tag.
d Test intent preserved / new tests added? New SQL test with an arch-independent reference; no existing test changed.
e Both directions demonstrated? Yes, on a local aarch64 cross build: fix passes, token-only revert fails, token restored passes. Unfixed CI aarch64 binaries fail.
f Fix is general across code paths? Yes. Int8/Int16 targets, accurateCast*, Int128/Int256, Bool and the JIT use other paths and are consistent (measured); only this loop narrows lane-wise.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Nullable source and target, ::, Array elements: 2 values before, 1 after. Float32, BFloat16, Int64 targets and in-range values unchanged.
h Backward compatible? (maintainer-approved exception only) Yes. aarch64 returns the pre-#117346 saturated values again; x86-64 machine code is identical (34/34 objects).
i Invariants and contracts preserved? Yes. The same float converts to the same integer in every row; the NaN/Inf check and the early return are unchanged.

Session id: cron:clickhouse-impl-slot-4:20261122-080900

@clickhouse-gh

clickhouse-gh Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [75ea87f]

Summary: ✅


AI Review

Summary

The PR makes finite Float64 to Int32/UInt32 conversions consistent across row positions on aarch64 by clamping before conversion. The bounds are exactly representable, and the existing NaN/Inf rejection and accurate-cast paths are preserved. The regression covers mixed vector/scalar block lengths and exact boundary results. No actionable findings at 75ea87fbebc2b58cf6908264e1d48a96232d485b.

Missing context / blind spots
  • ⚠️ Current-head aarch64 build, stateless, and performance jobs were still pending during review. The PR supplies cross-build fail/pass validation and boundary comparisons; completed aarch64 CI would independently confirm those results. The new regression already passes in the current-head Fast test report. No local build or test suite was run.
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-not-for-changelog This PR should not be mentioned in the changelog can be tested Allows running workflows for external contributors comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... labels Nov 22, 2026
groeneai and others added 2 commits November 22, 2026 12:37
`interleave(disable)` made the check-free loop scalar on aarch64 for every
float to integer pair, and `intDiv` ClickHouse#2 (`toUInt32` of `Float64`) became 24%
slower in the arm performance comparison of this PR.

Revert it. Only `Float64` to `Int32`/`UInt32` is inconsistent on aarch64: the
vector conversion goes through 64-bit lanes and keeps the low 32 bits, while
the scalar `fcvtzs w`/`fcvtzu w` saturates. That pair gets its own loop that
clamps the value to the range of the result type before converting, which
gives the scalar result for every finite value and lets the loop vectorizer
use `fmaxnm`/`fminnm` + `fcvtz[su] v.2d` + `xtn`. The same-width pairs keep
the code of master: their vector and scalar instructions saturate alike.

On the aarch64 cross build, toInt32/toUInt32/CAST/Nullable of 1019 values
(out of range both ways, the bounds, fractions, -0.0) give the same results
as the scalar build of the previous commit and as the CI binary of 58726cc,
the first parent of ClickHouse#117346. llvm-mca for neoverse-v2 (the m8g runners of the
arm performance comparison): 0.75 cycles per row, as master; the scalar loop
took 2.0. The x86-64 code is that of master.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=133517&sha=53c88db4bb8b09904e64fcd797dcf581fd9f5706&name_0=PR&name_1=Performance%20Comparison%20%28arm_release%2C%20master_head%2C%203%2F6%29
PR: ClickHouse#133517

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The consistency checks pass for any clamp that returns one value per input,
also a wrong one. A value at a bound that is in range once truncated converts
to the same integer on every platform, so assert those exactly: with the
upper bound of the clamp off by one, the aarch64 build returns 2147483646 and
4294967294 and the test fails.

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

clickhouse-gh Bot commented Nov 22, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 75ea87fbe with master 4c070eb09 (stripped binary size, per-symbol sizes and ThinLTO time; 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.

Compile time of recompiled translation units

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

Job report

@alexey-milovidov alexey-milovidov self-assigned this Nov 22, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 22, 2026
@lmtlssss

Copy link
Copy Markdown

Measured the loop shape on arm64 (Apple clang 21, -O2) with a standalone harness: vector lane = vcvtq_s64_f64 + vuzp1q_s32, tail = scalar fcvtzs w, d / fcvtzu w, d, and the clamp from this PR compiled as a loop (it vectorizes to fmaxnm.2d / fminnm.2d / fcvtzs.2d / xtn.2s with a scalar fcvtzs w remainder). Inputs: every power of two from 2^0 to 2^1023 with both signs and neighbours (±1 ulp, ±0.5, ±1), the bounds of both types, NaN, ±inf, and 10,000,000 random finite doubles (uniform bit patterns, seed 133509). NaN and inf skipped, as the separate pass rejects them.

set target out of range lane != tail (before) clamp != tail clamp loop (vector body + remainder) != tail
boundary (14,354) Int32 13,901 13,901 0 0
boundary UInt32 14,114 487 0 0
random (10M) Int32 4,851,876 4,851,876 0 0
random (10M) UInt32 4,925,008 229,241 0 0

So the clamp gives one value per input in every row, and equals the saturated pre-#117346 aarch64 result. One note: that value is not the x86-64 value. A cvttsd2si model differs from the clamp on 2,425,368 of the random inputs for Int32 (x86-64 returns -2147483648 for every out-of-range input, positive ones included) and on 2,576,526 for UInt32 (x86-64 converts through 64 bits and keeps the low 32 bits). The reference file of the new test asserts uniqueness and in-range bounds only, so it holds on both; cross-architecture agreement for out-of-range values is not given by this change.

Measured with the exact-arithmetic tools at colony.technology (npx speedrunpapi).

Merged via the queue into ClickHouse:master with commit 1623c13 Nov 22, 2026
195 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 22, 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... pr-not-for-changelog This PR should not be mentioned in the changelog 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.

Out-of-range Float64 to Int32/UInt32 conversion returns different values for the same input in one column on aarch64

4 participants