Skip to content

Fix integer rounding functions with |N| >= 20 - #128283

Merged
alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-integer-rounding-large-scale
Nov 2, 2026
Merged

alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-integer-rounding-large-scale

Conversation

@groeneai

@groeneai groeneai commented Oct 30, 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 round, roundBankers, floor, ceil and trunc of integers with |N| >= 20: a constant N threw BAD_ARGUMENTS, and with a negative N 128/256-bit integers were rounded to a multiple of 2^64 - 1 (floor(toInt128('100000000000000000005'), -20) returned 92233720368547758075 instead of 100000000000000000000).

Description

On 26.10 (and 26.3), SELECT round(number, 20) FROM numbers(1) throws BAD_ARGUMENTS, and floor(toInt128('100000000000000000005'), -20) returns 92233720368547758075 instead of 100000000000000000000.

Dispatcher turned N into size_t scale = intExp10(|N|), which saturates to 2^64 - 1 for |N| > 19. With a constant N that value reached the switch in IntegerRoundingImpl::apply, which only has cases up to 10^19 and throws otherwise (also for a positive N, where the result is just x). With a non-constant N or constant arguments, the 128/256-bit compute overload divided by 2^64 - 1.

size_t cannot hold 10^20..10^77, so Dispatcher now passes the exponent, as the decimal path already does, and IntegerRoundingImpl builds the scale:

  • N >= 0: returns x without the switch;
  • 10^|N| does not fit the type: 0, the only multiple of 10^|N| the type can hold;
  • 128/256-bit types, 20 <= |N| <= digits10: the exact scale of the type (up to 10^77 for UInt256);
  • |N| <= 19: the existing compile-time divisor switch, unchanged.

Float results are unchanged (FloatRoundingImpl computes the same intExp10 value itself); large N on floats is a separate problem not changed here.

Validation: the new test fails on master and passes 50/50 with randomized settings. An exact sweep of 396k cases (12 integer types, N in [-80, -18] and large positive N, constant and non-constant N, constant arguments) matches a Python oracle, and master and this PR give byte-identical results for integers with |N| <= 19, decimals with |N| <= 40 and floats.

No related issue found.


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

Version info

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

`Dispatcher` turned the scale argument into `size_t intExp10(|N|)`, which
saturates to 2^64 - 1 for |N| > 19. With a constant N the value reached the
`switch` in `IntegerRoundingImpl::apply`, which has no case for it, so
`round(number, 20)` and `floor(number, -20)` threw BAD_ARGUMENTS for every
integer type (the switch was taken for positive N too, although `compute`
ignores the scale there). With a non-constant N or constant arguments the
value reached the wide-integer `compute` overload, which has no guard, so
`floor(toInt128('100000000000000000005'), -20)` rounded to a multiple of
2^64 - 1 and returned 92233720368547758075.

Pass the exponent instead of the scale, as `DecimalRoundingImpl` already
does. `IntegerRoundingImpl` returns the argument for N >= 0, 0 when 10^|N|
does not fit the type (what the native guard already returned), the exact
`T`-typed scale for 128/256-bit types with 20 <= |N| <= digits10, and keeps
the compile-time divisor switch for |N| <= 19. `FloatRoundingImpl` computes
the same `intExp10` value itself, so float results are unchanged.

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; 0 findings), plus my own cold review of the diff.

# Sev Finding Verdict Evidence / action
1 💡 The default: throw of the switch in IntegerRoundingImpl::apply is unreachable now (every N reaching it has |N| <= 19) AGREE, not changed Kept as is rather than turning it into a new error path without a test.

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

Session id: cron:clickhouse-review-self-slot-58:20261030-194500

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. On master SELECT round(number, 20) FROM numbers(1) throws Code: 36 ... Unexpected 'scale' parameter passed to function (BAD_ARGUMENTS) and floor(toInt128('100000000000000000005'), -20) returns 92233720368547758075, every run (also on 26.10.2.103 and 26.3.60.2).
b Root cause explained? Dispatcher computed size_t scale = intExp10(|N|), which saturates to 2^64 - 1 for |N| > 19. A constant N sent it to the switch in IntegerRoundingImpl::apply (cases up to 10^19, otherwise BAD_ARGUMENTS, also for positive N); a non-constant N or constant arguments sent it to the 128/256-bit compute overload, which divided by 2^64 - 1.
c Fix matches root cause? Yes. The lossy size_t scale is removed where it is produced: the exponent is passed and IntegerRoundingImpl builds an exact scale, as the decimal path does. No guard at the throw site, no kernel change.
d Test intent preserved / new tests added? New test 05476_round_integer_large_scale (constant N on native and Int128 columns, constant arguments, non-constant N, the largest scales 10^38, 10^76, 10^77); its reference equals an independent Python oracle. No existing test changed.
e Both directions demonstrated? Yes. Master: [ FAIL ] with Code: 36. Fix: [ OK ], 50/50 with randomized settings. Five source mutations of the fix (dropped branches, saturated scale, missing 10^77) each make the test fail.
f Fix is general across code paths? All five functions share IntegerRoundingImpl. Constant N, non-constant N, constant arguments and a constant value with a non-constant N are covered. The float path only moves the intExp10 call and is byte-identical; the decimal path computes its own scale and is untouched.
g Fix generalizes across inputs (params/datatypes/wrappers)? 12 integer types incl. 128/256-bit and Bool, N from -32768 to 32767, values 0, +-1, type extremes, ties: an exact sweep of 396,393 cases matches the oracle with 0 mismatches. Nullable, LowCardinality, LowCardinality(Nullable) and NULL rows checked.
h Backward compatible? (maintainer-approved exception only) Only exceptions and wrong values change. Master and the fix are byte-identical for integers with |N| <= 19 (278,070 rows), decimals with |N| <= 40 and floats. No setting involved.
i Invariants and contracts preserved? Result column size and type unchanged; exact results and the constant 0 keep the function monotonic; no new error path. The exact scale is only built for 20 <= |N| <= digits10 of the type, where 10^|N| fits it.

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

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @Ergus @rschu1ze, could you review this and add the can be tested label so CI runs? Dispatcher passed size_t scale = intExp10(|N|), which saturates to 2^64 - 1 for |N| > 19, so a constant N threw BAD_ARGUMENTS and 128/256-bit integers were rounded to multiples of 2^64 - 1; it now passes the exponent and IntegerRoundingImpl builds the exact scale, or returns 0 when 10^|N| does not fit the type.

@clickhouse-gh

clickhouse-gh Bot commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c833f72]

Summary: ✅


AI Review

Summary

The change fixes integer rounding with |N| >= 20 by preserving the exponent, constructing an exact scale for wide integers, and returning integer inputs unchanged for nonnegative precision. No actionable findings at c833f727de3aef64b3fe42439df4b0a4b691498e. The new regression test and existing integer, floating-point, decimal, and column-scale rounding tests passed in Fast test.

Missing context / blind spots
  • ⚠️ The current CI workflow is still running; functional bugfix validation on both architectures is pending. Completed results would close this validation gap.
Final Verdict

✅ Approve. No code changes requested; pending CI results remain to be evaluated.

@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 c833f727d with master a018bd2bb (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of dcccc2b59; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

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

4 object files changed (-1.84 MiB total), 0 added.

Object file Master PR Δ
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/FunctionsRound.cpp.o 10.63 MiB 8.79 MiB -1.84 MiB (-17.30%)

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

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

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

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.

A weird corner case. Thanks for the fix!

@alexey-milovidov alexey-milovidov self-assigned this Nov 1, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 1, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Nov 1, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 2, 2026
Merged via the queue into ClickHouse:master with commit 3fbcffc Nov 2, 2026
527 of 531 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 2, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 15, 2026
…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]>
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.

3 participants