Skip to content

Fix round, floor, ceil and trunc of floats returning inf on overflow or a wrong value for |N| >= 20 - #128321

Merged
PedroTadim merged 6 commits into
ClickHouse:masterfrom
groeneai:fix-float-rounding-large-scale
Nov 18, 2026
Merged

PedroTadim merged 6 commits into
ClickHouse:masterfrom
groeneai:fix-float-rounding-large-scale

Conversation

@groeneai

@groeneai groeneai commented Oct 30, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #132573
Closes: #132575
Related: #128283

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

Fixes round, roundBankers, floor, ceil and trunc of Float32, Float64 and BFloat16 values returning inf when the scaled value overflows (round(1e300, 10), floor(toFloat32(3.4028235e38), -2)) and a wrong value for |N| >= 20 (round(1.5e-20, 20) returned 0). inf is still returned when the exact result is beyond the range of the type (ceil(1., -400), round(1.7e308, -308)). Closes #132573. Closes #132575.

Description

On 26.3 and 26.8, round(1e300, 10) returns inf, floor(toFloat32(3.4028235e38), -2) returns inf and round(1.5e-20, 20) returns 0 (also roundBankers, ceil, trunc, Float32, BFloat16, column N).

Two defects in the float path of FunctionsRound.h:

  • round(x * 10^N) / 10^N overflows to inf when x * 10^N exceeds the type, and so does round(x / 10^N) * 10^N for x at the type max, although such an x has no digits at that precision;
  • the scale came from intExp10, which saturates to 2^64 - 1 for |N| > 19.

For floats (Dispatcher passes the exponent since #128283):

  • |N| <= 19: the existing vectorized loop, plus a select that returns x when the result overflows. Every other result is unchanged.
  • |N| > 19: computed in Float64 with the correctly rounded 10^N (preciseExp10). x is returned once the scaled value reaches 2^52; N > 308 scales in two steps, N < -308 is answered directly; ceil and floor of an x whose quotient underflows give 10^N and -10^N; directed results are clamped to the valid side of x, which an inexact 10^N can otherwise cross.

Not changed, as on master, for |N| <= 19: the computation stays in the argument type and can be an ulp off, and ceil(5e-324, -1) is still 0 because x / 10^N underflows (handling it costs 4% on the ceil and floor loops).

Validation: the new test fails on master and passes 50/50 randomized runs. 46k random and adversarial cases match, bit for bit on the constant and column N paths, a model checked against exact rationals; for |N| <= 19 results equal master's except where master returned inf. Release build, one thread: constant-N rounding within 3% of master, loops still vectorized.


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

Version info

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

groeneai and others added 3 commits October 30, 2026 20:41
`round`, `roundBankers`, `floor`, `ceil` and `trunc` of `Float64`, `Float32`
and `BFloat16` computed `round(x * 10^N) / 10^N` (or the negative-`N` mirror)
with a scale from `intExp10`, which saturates to 2^64 - 1 for `|N| > 19`:

- For a positive `N`, `x * 10^N` overflows to `inf` when `x` is large
  (`round(1e300, 10) = inf`). Such an `x` has no digits after the N-th
  decimal place, so the result is now `x`.
- For `|N| > 19`, the scale was 2^64 instead of 10^N
  (`round(1.5e-20, 20) = 0`, `floor(1.23456789e25, -20)` wrong).

The rounding functions now receive the exponent (as in the integer rounding
fix). `|N| <= 19` keeps the vectorized computation in the argument type and
only adds the overflow select for a positive `N`; every finite result there
is unchanged. `|N| > 19` is computed in `Float64` for every float type, with
the correctly rounded 10^N from `preciseExp10`:
- results from 2^52 on are integers, so `x` is returned instead of a round
  trip through an inexact scale;
- a scale above 10^308 is applied in two steps (positive `N`), or answered
  directly (negative `N`: every finite `x` is below 10^N in magnitude);
- `ceil` of a tiny positive `x` and `floor` of a tiny negative `x`, whose
  quotient underflows to 0, give 10^N and -10^N;
- a directed result is clamped to the valid side of `x`, which an inexact
  10^N (`N > 22`) can otherwise cross (`ceil(6.385506180058851e-264, 278)`).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… underflow

For a negative `N` with `|N| <= 19`, `round(x / 10^N) * 10^N` overflowed to
`inf` for `x` at the type max (`floor(toFloat32(3.4028235e38), -2)`,
`round(1.7976931348623157e308, -6)`), although such an `x` has no digits
below `10^N`, and `x / 10^N` underflowed to zero for a tiny `x`, so `ceil`
and `floor` returned `0`/`-0` instead of `10^N`/`-10^N`
(`ceil(5e-324, -1)`, `ceil(toFloat32(1e-30), -19)`).

The negative branch now returns `x` when the result is not finite, and
`ceil`/`floor` use `1`/`-1` when the quotient underflows, as the `|N| > 19`
path already does. Also use `if constexpr` for the template-parameter
branches of `FloatRoundingLargeScale::compute`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…rop the |N| <= 19 underflow handling

For |N| <= 19 with a negative N, `x / 10^N` underflows to zero for a tiny
nonzero x, so `ceil(5e-324, -1)` is 0 instead of 10. Handling it inside the
vectorized loop costs ~4% on the negative-N ceil/floor loops (release,
one thread, numbers(1e9), three runs of 11 reps), even in the cheapest
bit-identical form (substituting `val` for an underflowed quotient: one
compare and one blend). That is above the 3% budget for this hot loop, and
the case only concerns values below the type's normal range divided by up
to 10^19, so it stays as on master.

What remains for |N| <= 19 is the overflow select at the type max
(`floor(toFloat32(3.4028235e38), -2)` returned inf), which costs at most
~2% on the same benchmark. The |N| > 19 path keeps its underflow handling
(`ceil(1e-300, -30)` = 1e30).

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; rounds 1-3: 0, 1 and 1 findings) and my own review (3 rounds).

# Sev Finding Verdict Evidence / action
1 ⚠️ Negative N with |N| <= 19: x / 10^N * 10^N overflows at the type max, so floor(toFloat32(3.4028235e38), -2) and round(1.7976931348623157e308, -6) returned inf AGREE, fixed @ 5a2749e returns x when the result is not finite; test rows added
2 ⚠️ Negative N with |N| <= 19: x / 10^N underflows for a tiny x, so ceil(toFloat32(1e-30), -19) and ceil(5e-324, -1) return 0 AGREE, not changed for |N| <= 19 the cheapest form (substituting x for an underflowed quotient) costs +3.7..+4.1% on the ceil/floor loops (release, one thread), over the 3% bar; disclosed in the description. |N| > 19 is handled (ceil(1e-300, -30) = 1e30)
3 💡 Runtime if on the rounding-mode template parameter AGREE, fixed @ 5a2749e if constexpr
4 ❌ |N| > 19: a near-tie input whose scaled value rounds onto an exact .5 lands in the other bucket (round(5.0000000000000005e-21, 20) = 0) DISAGREE the unchanged |N| <= 19 path makes the same rounded-product decision for every N (round(6485.765, 2) = 6485.76, round(0.05, 1) = 0), and round(5.0000000000000005e-21, 20) is 0 on master too; exact decimal ties would need an extended-precision 10^N
5 ❌ |N| > 19: the 2^52 identity shortcut returns x where the correctly rounded result is 1 ulp away (round(4.5035996273704964e-05, 20)) DISAGREE same precision as the unchanged |N| <= 19 path, which master shows for the same shape (floor(6.807983358952, 15) returns x, exact is 1 ulp below; round(50.1400032712205, 15) = 50.14000327122051); keeping the round trip up to 2^53 is not closer (more round mismatches for N >= 23, up to 2 ulp); master returns 0.00004503599627370494 for this input

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

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes: SELECT round(1e300, 10), floor(toFloat32(3.4028235e38), -2), round(1.5e-20, 20) gives inf, inf, 0 on master, 26.3.42.3 and 26.8.18.2, every run.
b Root cause explained? x * 10^N (and x / 10^N * 10^N at the type max) overflows to inf; for |N| > 19 the scale came from intExp10, which saturates to 2^64 - 1.
c Fix matches root cause? Yes: the exponent reaches the float code, the scale is the correctly rounded 10^N, an overflowing result returns x (no digits left at that precision); for |N| > 19 an underflowed ceil/floor quotient becomes 1/-1.
d Test intent preserved / new tests added? New test 05477_round_float_large_scale (five functions, three float types, constant and column N, constant and column x). No existing test changed.
e Both directions demonstrated? Master FAIL, fix OK (local and clickhouse-test, debug and release); 50/50 randomized runs OK; 9 mutation arms each turn the test red.
f Fix is general across code paths? Both float entry points (vectorized constant N, per-row column N), positive and negative N, all modes; integers keep their values; decimals were already digit-based.
g Fix generalizes across inputs (params/datatypes/wrappers)? Float64, Float32, BFloat16, Nullable, LowCardinality, NULL; N = 0, 19/20, 308/309, +-400; 0, -0, subnormal, type max, inf, nan. 46k cases match a model of the algorithm bit for bit.
h Backward compatible? (maintainer-approved exception only) No setting or format change. For |N| <= 19 the only changed results are master's inf; |N| > 19 used a 2^64 scale.
i Invariants and contracts preserved? floor <= x <= ceil and |trunc(x)| <= |x| hold (clamp for |N| > 19); monotonicity: 0 violations in 713k sorted pairs; the vectorized loops stay vectorized.

Session id: cron:clickhouse-impl-self-slot-57:20261030-222201

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @Algunenano @rschu1ze, could you review this and add the can be tested label so CI runs? Float rounding computed x * 10^N in the argument type (overflowing to inf, round(1e300, 10)) and took the scale from intExp10, which saturates for |N| > 19: the vectorized |N| <= 19 loop now returns x on overflow, |N| > 19 is computed in Float64 with preciseExp10, and the Dispatcher hunk is the same as in #128283.

@clickhouse-gh

clickhouse-gh Bot commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [29454f5]

Summary: ❌

job_name test_name status info comment
Performance Comparison (arm_release, master_head, 6/6) FAIL Performance dashboard
codecs_float_insert #15 unstable query history IGNORED

AI Review

Summary

The PR fixes spurious floating-point overflow in round, roundBankers, floor, ceil, and trunc, and uses the intended decimal scale for |N| > 19. Reviewed the current implementation and prior discussion at 29454f535b12b3dcdd5a6e72cfbc9dc206ee47ac; no actionable findings remain. The focused regression test passed in CI on this commit. An independent arithmetic model checked 114,048 adjacent input pairs around the new 2^52 shortcut without finding a monotonicity violation.

Final Verdict

✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... labels Oct 30, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 31, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 29454f535 with master f63ca4f78 (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.

Object file sizes

3 object files changed (+116.40 KiB total), 0 added.

Object file Master PR Δ
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/FunctionsRound.cpp.o 8.69 MiB 8.80 MiB +116.40 KiB (+1.31%)

711 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

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

Median compile-time ratio to the baselines is ×1.12 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +8.0 s (+11%) in total before that adjustment.

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 8b8fe4a

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
Performance Comparison (arm_release, master_head, 4/6) / prewhere_subcolumns #1 not from this PR: select * from test where n.null reads a Nullable subcolumn of a MergeTree table and never calls the rounding functions this PR changes. Confirmed +30.1% (+29.1% after the server restart). The same query has been reported slower on arm on 11 unrelated PRs since 2026-10-30 23:19Z, after at most one such run per day before a fix task is created (investigating at full effort, fixing-PR link to follow here)
Mergeable Check, PR praktika rollups of the row above a fix task is created (the same task as the row above)

The first runs of this head stopped at Config Workflow / Pre Hooks because the can be tested label was not set yet; the run after the label was added is the one above. CIDB has no other FAIL or ERROR row in that run.

Session id: cron:our-pr-ci-monitor:20261031-140009

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the prewhere_subcolumns #1 row of Performance Comparison (arm_release, master_head, 4/6): #128387. The two servers ended with different part layouts (a background merge sometimes finished before merges were stopped), so the query read 784908 rows on one and 130818 on the other; the change is test-only.

…large-scale

Resolve the conflict in src/Functions/FunctionsRound.h with ClickHouse#128283: keep
master's IntegerRoundingImpl, keep this branch's FloatRoundingImpl, whose
FloatRoundingComputation::prepare takes the exponent itself.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 99ac658

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
Performance Comparison (arm_release, master_head, 4/6) / codecs_float_insert infra, not from this PR: the runner disk was full, so query 20 failed with Code: 243 ... Cannot reserve 8.48 MiB, not enough space (the shard's own report has 0 slower queries; its 3 too long entries do not fail a shard). The disk is filled by the outdated hits_100m_single parts that the dataset rebuild leaves behind while the first tests run #131429 (mine, open)
Mergeable Check, PR praktika rollups of the row above #131429 (mine, open)

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261115-190012

@PedroTadim

Copy link
Copy Markdown
Member

🕵️ @groeneai looks good to me. I checked the new path independently:

  • preciseExp10 is correctly rounded for every integer exponent from -340 to 340: I compiled it on its own and compared with float("1e<n>").
  • A step-by-step model of FloatRoundingLargeScale in Python doubles (the same IEEE operations), compared with exact rational arithmetic for |N| from 20 to 700: 0 direction violations in about 100,000 directed results (floor <= x, ceil >= x, |trunc| <= |x|), also for Float32 computed in Float64 and then cast. On random inputs, 1,082 of 64,000 results are 1 ulp off and 12 more than that; in all 12 the exact scaled value is closer to a rounding boundary than a double resolves at that magnitude, which is the same limitation the |N| <= 19 path has. For |N| > 308 the Negative path matches exactly and the Positive path is within 1 ulp.
  • On the |N| <= 19 path, the new code differs from master only where master returned inf (0 other differences in 320,000 results).

One non-blocking note: some results are still inf, on purpose. The test pins ceil(1., -400) = inf, floor(-1., -400) = -inf, ceil(toFloat32(1), -39) = inf and round(1.7e308, -308) = inf. That is consistent, since the exact answer (10^400, 2·10^308) is beyond the range of the type, while a representable exact answer near the type max returns x. But the changelog entry reads as if inf no longer comes out, so a sentence saying it remains when the exact result overflows would set expectations.

The failed Performance Comparison (arm_release, master_head, 4/6) is unrelated: codecs_float_insert failed with Cannot reserve 8.48 MiB, not enough space on the runner, and the three "too long" tests do not involve rounding. The comparison shows no faster, slower or unstable queries in any of the 6 arm shards. I re-ran that job.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Thanks for the independent check. I added a sentence to the changelog entry: inf is still returned when the exact result is beyond the range of the type (ceil(1., -400), round(1.7e308, -308)).

clickhouse-gh[bot]
clickhouse-gh Bot previously approved these changes Nov 18, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 3393765

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
Upgrade check (amd_release) / Logical error: Context has expired (STID: 1805-3f9b) crash, not from this PR: kqlMultiply aborted in the previous release's server (26.10.5.57, git hash 25ea79f784e1) during the stress phase, before the upgrade. The fix is on master and in this tree; its 26.10 backport #132081 merged after that release was built #131363 (external, merged)
Upgrade check (amd_release) / the five Cannot ... rows (mutations and row policies left by the stress phase) consequence of the abort above: the server was down (Connection refused) #131363 (the owner above)
Performance Comparison (arm_release, master_head, 5/6) infra: the runner ran out of disk, codecs_float_insert got Code: 243 ... Cannot reserve 8.48 MiB, not enough space; 0 of 247 queries changed or were unstable #131429 (mine, open)
Mergeable Check, PR praktika rollups of the rows above #131363 and #131429 (the owners above)

Session id: cron:our-pr-ci-monitor:20261118-133026

@clickhouse-gh
clickhouse-gh Bot dismissed their stale review November 18, 2026 16:12

AI review of a later commit does not approve the PR, see the AI Review comment.

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai, please investigate the CI failures in this PR (commit 29454f5) and fix them, or link existing fixes.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=128321&sha=29454f535b12b3dcdd5a6e72cfbc9dc206ee47ac&name_0=PR

Failures without a known issue:

  • codecs_float_insert #15 in Performance Comparison (arm_release, master_head, 6/6)

@PedroTadim
PedroTadim added this pull request to the merge queue Nov 18, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 29454f5

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
Performance Comparison (arm_release, master_head, 6/6) / codecs_float_insert infra, not from this PR: the runner disk was full (job label disk-almost-full, peak 100% of 193.63 GB). The tests started with 27.4 GiB free, codecs_float_insert used it up, query 18 failed with Code: 243 ... Cannot reserve 8.37 MiB, not enough space, and 15 s later the two servers removed 163 and 180 outdated hits_100m_single parts left by the dataset rebuild #131429 (mine, open)
Performance Comparison (arm_release, master_head, 6/6) / codecs_float_insert #15 (unstable) same cause: the query is INSERT INTO codec_rnd_Float64_LZ4 ... SELECT (intHash64(number) - 4294967295)/pi(), which calls no rounding function. It ran with under 7 GiB free, and the reference and the patched server slowed down together (runs 0-1 about 0.21 s, runs 2-6 about 0.42 s on both); median difference +1.2% #131429 (mine, open)
PR praktika rollup of the rows above #131429 (mine, open)

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:clickhouse-premium-slot-24:20261118-203901

Merged via the queue into ClickHouse:master with commit f98d6d5 Nov 18, 2026
191 of 193 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 18, 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-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.

Float round/floor/ceil with |N| >= 20 give silently wrong results round/floor/ceil/trunc on large Float* returns inf instead of the value

4 participants