Skip to content

Fix UBSan in FieldVisitorConvertToNumber for wide-integer Float64 boundary - #104154

Merged
alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-103817-fieldvisitor-convert-to-number-ubsan
May 9, 2026
Merged

alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-103817-fieldvisitor-convert-to-number-ubsan

Conversation

@groeneai

@groeneai groeneai commented May 5, 2026 •

Copy link
Copy Markdown
Collaborator

Fix undefined behavior in FieldVisitorConvertToNumber<T>::operator()(Float64) when T is a wide integer type (UInt64, Int64, Int128, UInt128, Int256, UInt256).

Bug

For these wide integer types numeric_limits<T>::max() has more than 53 significant bits, so converting it to Float64 rounds up. Example for UInt64:

numeric_limits<UInt64>::max() = 18446744073709551615 = 2^64 - 1
Float64(numeric_limits<UInt64>::max()) = 18446744073709551616 = 2^64  (rounded up)

The existing boundary check x > Float64(numeric_limits<T>::max()) therefore fails to reject Float64 values equal to the rounded-up boundary. The subsequent static_cast<T>(x) is undefined behavior.

UBSan output from issue #103817 (CI: Unit tests (asan_ubsan, function_prop_fuzzer) on PR #103580):

src/Common/FieldVisitorConvertToNumber.h:85:22: runtime error: 1.84467e+19 is outside the range of representable values of type 'unsigned long'
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior src/Common/FieldVisitorConvertToNumber.h:85:22

1.84467e+19 is exactly 2^64. On a release build the same code silently truncates the value (typically to 0), which is also wrong — topK(1.8446744073709552e19)(...) would proceed with threshold = 0 instead of rejecting the input.

Fix

Replace the buggy boundary check with accurate::greaterOp / accurate::lessOp (from Core/AccurateComparison.h), which uses DecomposedFloat::compare to perform precision-correct float-vs-integer comparison. This is the existing canonical helper for this kind of comparison and is already used elsewhere in convertNumeric, FieldVisitorAccurateLess, etc.

The same buggy pattern existed in two other places — fixed all three:

  1. src/Common/FieldVisitorConvertToNumber.h — the reported site (used in aggregate function parameter parsing: topK, histogram, uniqUpTo, groupArrayInsertAt, etc.)
  2. src/Core/SettingsFields.cpp::fieldToNumber<T> — used by SET <integer_setting> = <Float64>
  3. src/Common/NaNUtils.h::canConvertTo<T> — used by callers in InterpreterSelectQuery.cpp, UnionStep.cpp, PlannerJoinTree.cpp

bool is special-cased — numeric_limits<bool> is exactly representable in Float64, so the simple comparison is correct, and accurate::lessOp would fail to instantiate for bool (make_unsigned_t<bool> is ill-formed since C++17).

Test

tests/queries/0_stateless/04205_field_visitor_convert_to_number_ubsan_103817.sql exercises both call paths (aggregate function parameters and integer settings) at the boundary value 1.8446744073709552e19 (= 2^64). The test fails on master without this fix (queries return wrong results in release builds, abort under UBSan) and passes with this fix (queries throw CANNOT_CONVERT_TYPE).

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

Fix undefined behavior when an out-of-range Float64 value is converted to a wide integer type (UInt64, Int64, Int128, UInt128, Int256, UInt256). Previously, values equal to Float64(numeric_limits<T>::max()) (which rounds up to a value above the actual maximum) bypassed the bounds check and produced UB in the subsequent cast. This affected aggregate-function parameter parsing (topK, histogram, uniqUpTo, groupArrayInsertAt, etc.) and integer-typed settings via SET <setting> = <Float64>. Closes #103817.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.5.1.476

…ndary

For wide integer types (`UInt64`, `Int64`, `Int128`, `UInt128`, `Int256`,
`UInt256`), `numeric_limits<T>::max()` has more than 53 significant bits, so
converting it to `Float64` rounds UP. Example for `UInt64`:

  numeric_limits<UInt64>::max() = 2^64 - 1 = 18446744073709551615
  Float64(numeric_limits<UInt64>::max()) = 2^64 = 18446744073709551616

The boundary check `x > Float64(numeric_limits<T>::max())` therefore failed
to reject `Float64` values equal to that rounded-up boundary, leading to
undefined behavior in the subsequent `static_cast<T>(x)`:

  src/Common/FieldVisitorConvertToNumber.h:85:22: runtime error:
    1.84467e+19 is outside the range of representable values of type 'unsigned long'

Replace the buggy boundary check with `accurate::greaterOp` /
`accurate::lessOp` (in `Common/NaNUtils.h::canConvertTo`, with `DecomposedFloat`
directly to avoid a circular include), which use precision-correct
float-vs-integer comparison via `DecomposedFloat::compare`. This is the
canonical helper already used by `convertNumeric` and `FieldVisitorAccurateLess`.

The same pattern existed in three places, all fixed:
* `src/Common/FieldVisitorConvertToNumber.h` — aggregate-function parameter
  parsing (`topK`, `uniqUpTo`, `groupArrayInsertAt`, etc.)
* `src/Core/SettingsFields.cpp::fieldToNumber` — `SET <integer-setting> = <Float64>`
* `src/Common/NaNUtils.h::canConvertTo` — used in `InterpreterSelectQuery`,
  `UnionStep`, `PlannerJoinTree`

`bool` is special-cased: `numeric_limits<bool>` is exactly representable in
`Float64`, and `accurate::lessOp` would fail to instantiate for `bool` because
`make_unsigned_t<bool>` is ill-formed since C++17.

Closes ClickHouse#103817.

CI report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=103580&sha=baca42bf3124df58c66bec7dba0089cd200c24c1&name_0=PR&name_1=Unit%20tests%20%28asan_ubsan%2C%20function_prop_fuzzer%29
@groeneai

groeneai commented May 5, 2026

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (per TASK.md Phase 4 / fix-ci-failure skill):

a) Deterministic repro? ✅ SELECT topK(1.8446744073709552e19)(number) FROM numbers(0) and SET max_threads = 1.8446744073709552e19 deterministically trigger the UB site (FieldVisitorConvertToNumber.h:85 and SettingsFields.cpp:119 respectively). The boundary value 1.8446744073709552e19 = 2^64 is exactly representable in Float64.

b) Root cause explained? ✅ For wide integer types (UInt64, Int64, Int128, UInt128, Int256, UInt256), numeric_limits<T>::max() has more than 53 significant bits, so converting it to Float64 rounds UP. For UInt64: max() = 2^64 - 1, but Float64(max()) rounds to 2^64. The check x > Float64(max()) therefore allows x = 2^64 to slip through, after which static_cast<UInt64>(2^64) is undefined behavior.

c) Fix matches root cause? ✅ Replace the boundary check with accurate::greaterOp / accurate::lessOp (or DecomposedFloat directly in NaNUtils.h to avoid a circular include with Core/AccurateComparison.h). These helpers use DecomposedFloat::compare for precision-correct float-vs-integer comparison without rounding.

d) Test intent preserved? ✅ Existing tests (02992_settings_overflow, 04146_settings_float_overflow, 00919_histogram_merge, 00647_histogram*, 02902_topKGeneric_deserialization_memory, 01519_topK_distributed_parametrized, 01409_topK_merge, 00981_topK_topKWeighted_long) all still pass. No assertions weakened.

e) Both directions demonstrated? ✅

  • With fix: new test 04205_field_visitor_convert_to_number_ubsan_103817.sql passes 30/30 with full randomization.
  • Without fix: the CI UBSan log on PR Fix infinite loop on WITH FILL for data starting with ±inf #103580 proves the bug. A standalone C++ verification (DecomposedFloat<double>(1.8446744073709552e19).greater(numeric_limits<UInt64>::max()) returns true) confirms the new check correctly catches what the old x > Float64(max()) missed.

f) Fix is general? ✅ Three sites with the same buggy pattern, all fixed: FieldVisitorConvertToNumber.h, SettingsFields.cpp::fieldToNumber, NaNUtils.h::canConvertTo. Verified no other instances via grep "Float64(std::numeric_limits" across src/.

Session: cron:clickhouse-ci-task-worker:20260505-214500

@groeneai

groeneai commented May 5, 2026 •

Copy link
Copy Markdown
Collaborator Author

cc @alexey-milovidov @Algunenano — could you review this? Per directive on #103817.

The fix replaces a Float64-vs-integer boundary check that silently overflowed for wide-integer types (UInt64, Int64, Int128, UInt128, Int256, UInt256) at the rounded-up Float64 representation of numeric_limits<T>::max() — e.g. 2^64 for UInt64. The new check uses accurate::greaterOp / DecomposedFloat::compare for precision-correct comparison. Same pattern fixed in three places: FieldVisitorConvertToNumber.h, SettingsFields.cpp::fieldToNumber, and NaNUtils.h::canConvertTo.

@Algunenano — flagging because of overlap with your open PR #102646 (NumberLiteral Field type) which touches the same files. Happy to rebase on top of #102646 if you'd prefer that ordering.

@Algunenano Algunenano added the can be tested Allows running workflows for external contributors label May 6, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [eae0a62]

Summary: ✅


AI Review

Summary

This PR fixes a real UB path when converting Float64 to wide integer types by replacing lossy boundary checks with precision-correct comparisons in three call sites, and adds a regression test that reproduces and validates the behavior on affected user-facing paths. I did not find blockers or major issues in the proposed change.

ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ✅
Compilation time ✅
No large/binary files ✅
Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label May 6, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 6, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 91.10% 91.10% +0.00%
Branches 76.70% 76.60% -0.10%

Changed lines: 73.68% (14/19) · Uncovered code

Full report · Diff 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.

Yes, this is good.

@alexey-milovidov alexey-milovidov self-assigned this May 9, 2026
@alexey-milovidov
alexey-milovidov merged commit c9e37b1 into ClickHouse:master May 9, 2026
164 of 165 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 May 9, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi @groeneai @alexey-milovidov — while reviewing this PR I found the following:

Could you review the test PR and add the can be tested label if it looks good?
Happy to discuss — close anything that's wrong or already addressed.

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 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.

UndefinedBehaviorSanitizer in FieldVisitorConvertToNumber.h:85:22

5 participants