Skip to content

Canonicalize NaN bit patterns at hash boundaries (DISTINCT/GROUP BY/uniqExact) - #105756

Closed
groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-105748-distinct-nan-canonicalize
Closed

groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-105748-distinct-nan-canonicalize

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

Closes #105748.

bitEquals in HashTable.h compares hash keys byte-wise, so two NaN values that differ only in sign bit or mantissa payload are treated as distinct. This breaks DISTINCT, GROUP BY, uniqExact, and countDistinct:

The fix folds every NaN bit pattern onto the canonical positive quiet NaN at three call sites:

  • ColumnVector<Float>::updateHashWithValue / updateHashWithValueRange / updateHashFast / getWeakHash32 (used by hashed / serialized set methods and multi-key SipHash paths).
  • ColumnsHashing::HashMethodOneNumber::getKeyHolder for single-column numeric keys (the key32 / key64 and nullable_key32 / nullable_key64 variants).
  • AggregateFunctionUniq::Adder for uniqExact / countDistinct (which inserts the value directly into HashSet<Float> rather than going through HashMethodOneNumber), plus the insertMany fast path used by the uniq HLL family.

For non-floating-point types every change is a compile-time no-op: canonicalizeNaN<T> reduces to identity and the may_canonicalize_nan flag on HashMethodOneNumber is false so the branch is pruned. For floating-point columns the cost is one isNaN check per key access, on the predicted-not-taken path for non-NaN data.

JOIN with NaN keys: the HashJoin::KeyGetter path uses HashMethodOneNumber, so after this change two NaN-valued rows compare equal under ON l.x = r.x (consistent with uniqExact/DISTINCT). The scalar = operator continues to follow IEEE 754 (nan = nan is 0). This matches the direction PostgreSQL and DuckDB took for cross-platform consistency.

Out of scope (follow-ups, noted in regression-test comments):

  • SELECT DISTINCT Nullable(Float) of a single nullable key routes through SetVariants::nullable_keys128 (HashMethodKeysFixed multi-key packing) rather than HashMethodOneNumber.
  • Multi-key DISTINCT / GROUP BY of (Float, ...), Tuple(Float, ...), Array(Float) likewise use raw bytes when packing the fixed-size hash key.

Regression test: 04275_105748_distinct_nan_canonicalization covers the reproducer from #105748 plus Float32 / Float64 / Nullable(Float64) variants and a materialized table with four NaN producers. The pre-existing test 01428_hash_set_nan_key had a final assertion that constructs ten distinct NaN bit patterns and expected ten distinct values; that expectation is updated to 1 with an inline comment.

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 DISTINCT, GROUP BY, uniqExact, and countDistinct to treat NaN values consistently regardless of bit pattern. Previously, NaN values produced by different operations (e.g. 0./0. versus the literal nan, or ARM NEON log(-1.) versus glibc log(-1.) after #98230) were treated as distinct values because hash tables compare keys byte-wise. Now all NaN bit patterns are canonicalized at the hash boundary, so any NaN compares equal to any other NaN inside set semantics. The scalar = operator still returns false for nan = nan per IEEE 754.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

…niqExact)

Closes ClickHouse#105748.

Hash tables in ClickHouse compare keys byte-wise via `bitEquals` (see
`src/Common/HashTable/HashTable.h`), so two NaN values whose only difference
is the sign bit or mantissa payload are treated as distinct. That breaks
`DISTINCT`, `GROUP BY`, `uniqExact`, and `countDistinct` whenever NaN values
of different bit patterns reach the hash table, for example:

  * `0./0.` (compile-time constant-folded) gives `0xFFF8000000000000` on
    x86 while the literal `nan` gives `0x7FF8000000000000`.
  * After ClickHouse#98230, ARM NEON `log(-1.)` returns a NaN with sign bit flipped
    relative to glibc's scalar `log(-1.)`, so `log(-1.)` and `0./0.` no
    longer compare bit-equal on AArch64.

This fix folds every NaN bit pattern onto the canonical positive quiet NaN
(`std::numeric_limits<T>::quiet_NaN()`) at three hash-boundary call sites:

* `ColumnVector<Float>::updateHashWithValue` / `updateHashWithValueRange`
  / `updateHashFast` / `getWeakHash32` (used by `hashed` / `serialized`
  set methods, scatter-by-partition, multi-key SipHash paths).
* `ColumnsHashing::HashMethodOneNumber::getKeyHolder` for single-column
  numeric keys (the `key32` / `key64` and `nullable_key32` / `nullable_key64`
  variants used by `Aggregator` and PR-`HashJoin`/`SetVariants`).
* `AggregateFunctionUniq::Adder` for `uniqExact` / `countDistinct` (which
  inserts the value directly into `HashSet<Float>` without going through
  `HashMethodOneNumber`), plus the matching `insertMany` fast path used
  by the `uniq` HLL family.

For non-floating-point types every change is a compile-time no-op:
`canonicalizeNaN<T>` reduces to identity, and the `may_canonicalize_nan`
flag on `HashMethodOneNumber` is `false` so the branch is pruned. For
floating-point columns the cost is one `isNaN` check per key access, which
the predicted-not-taken path handles cheaply on normal data.

JOIN semantics with NaN keys are intentionally not touched in this PR: the
`HashJoin::KeyGetter` path that uses `HashMethodOneNumber` does end up
treating all NaNs as the same value after this change, which matches how
`uniqExact` / `DISTINCT` now behave but differs from the scalar `=`
operator that follows IEEE 754. That is the same direction
PostgreSQL / DuckDB took for cross-platform consistency.

Out of scope for this PR (tracked as follow-ups in the regression test
comments):

* `SELECT DISTINCT Nullable(Float)` of a single nullable key currently
  routes through `SetVariants::nullable_keys128` (a multi-key
  `HashMethodKeysFixed` path) rather than `HashMethodOneNumber`, so it
  is not yet canonicalized.
* Multi-key `DISTINCT` / `GROUP BY` of `(Float, ...)` and serialized
  paths (`Tuple(Float, ...)`, `Array(Float)`) likewise still use raw
  bytes when packing into the fixed-size hash key.

Regression test: `04275_105748_distinct_nan_canonicalization` covers the
reproducer from the issue plus Float32 / Float64 / Nullable variants and a
materialized table with four different NaN producers. The pre-existing
test `01428_hash_set_nan_key` had a final assertion that constructs ten
distinct NaN bit patterns and expected ten distinct values; that
expectation has been updated to `1` with an explanatory comment.

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (per TASK.md Phase 4 Step 9):

# Question Answer
a Deterministic repro? Yes. SELECT countDistinct(arrayJoin([0./0., nan])) returns 2 before fix, 1 after fix. The same reproduces on x86 (with literal nan vs 0./0.), no ARM-only setup needed.
b Root cause explained? Yes. The Float NaN payload mantissa / sign bit varies by producer (0./0. vs literal nan vs log(-1.), and additionally fastops NEON log after #98230 on AArch64). HashTable::bitEquals does byte-wise memcmp on the storage type (UInt32/UInt64), so two NaN representations with different bits hash and compare as distinct keys in DISTINCT/GROUP BY/uniqExact/SetVariants.
c Fix matches root cause? Yes. At every byte-equality hash boundary that handles Float32/Float64, the NaN bit pattern is folded to the canonical quiet NaN before the byte comparison happens. No bounds widened, no random-settings disabled, no test data shrunk.
d Test intent preserved? New tests added? The new test 04275_105748_distinct_nan_canonicalization exercises 16 assertions across countDistinct / uniqExact (Float32+Float64) / SELECT DISTINCT / GROUP BY / Nullable / materialized table. The one pre-existing assertion that gets updated (01428_hash_set_nan_key line 7) was a code construction that builds 10 distinct NaN bit patterns and expected 10 distinct values; that expectation IS the bug, so it now expects 1 with an inline explanatory comment pointing at #105748.
e Both directions demonstrated? Yes. With groeneai/fix-105748-distinct-nan-canonicalize checked out and a debug clickhouse-21 build: every assertion in the new test passes. Reverting only src/Common/ColumnsHashing/HashMethod.h / src/Columns/ColumnVector.cpp / src/AggregateFunctions/AggregateFunctionUniq.h (keeping NaNUtils.h and the test) makes the test fail at the first countDistinct assertion.
f Fix is general, not narrow? The fix covers every Float hash boundary I could enumerate without restructuring SetVariants: ColumnVector hash methods (updateHashWithValue / Range / Fast / getWeakHash32) used by hashed/serialized/scatter; HashMethodOneNumber::getKeyHolder for key32/key64 and nullable_key32/nullable_key64; uniqExact adder direct insert; uniq HLL insertMany fast path. Two paths are intentionally out of scope (multi-key HashMethodKeysFixed packing, including nullable_keys128/256 used by SELECT DISTINCT Nullable(Float); and serialized-with-byte-copy paths) and are noted as follow-ups in the PR description and the regression test. They are not covered by the issue's reproducer.

Session id: cron:clickhouse-ci-task-worker:20260524-224500.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @KochetovNicolai @alexey-milovidov @nickitat - could you review this? The PR canonicalizes NaN bit patterns at hash boundaries (HashMethodOneNumber, ColumnVector hash methods, uniqExact adder) so DISTINCT/GROUP BY/uniqExact treat all NaN values as equal regardless of producer bit pattern. Fixes issue #105748 (ARM NEON fastops vs glibc NaN sign-bit mismatch) but the bug also reproduces on x86 between the literal nan and 0./0., which the new regression test covers.

@clickhouse-gh

clickhouse-gh Bot commented May 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9f5558c]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_msan, WasmEdge, parallel, 2/2) FAIL
04043_system_asynchronous_inserts_user_filter FAIL cidb
Unit tests (asan_ubsan, function_prop_fuzzer) FAIL
FunctionsStress.stress FAIL cidb, issue
AllTests FAIL cidb
Performance Comparison (arm_release, master_head, 5/6) FAIL
ColumnMap #0::old FAIL query history
ColumnMap #0::new FAIL query history
array_fill #0::old FAIL query history
array_fill #0::new FAIL query history
array_fill #1::old FAIL query history
array_fill #1::new FAIL query history
array_fill #2::old FAIL query history
array_fill #2::new FAIL query history
grace_hash_join #0::old FAIL query history
grace_hash_join #0::new FAIL query history
28 more test cases not shown

AI Review

Summary

This PR canonicalizes floating-point NaN bit patterns at hash/equality boundaries used by DISTINCT / GROUP BY / uniq* paths (HashMethodOneNumber, ColumnVector hashing, AggregateFunctionUniq, AggregateFunctionUniqCombined) and adds focused regression coverage for Float32, Float64, BFloat16, and nullable variants. I re-checked prior discussion threads against current head, and the previously reported correctness gaps are fixed in the current code.

Missing context / blind spots
  • ⚠️ I could not fetch Praktika CI details in this environment because the GitHub token is rejected by enterprise policy (HTTP 403 from .claude/tools/fetch_ci_report.js), so this review is based on code and test changes rather than CI log inspection.
Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label May 25, 2026
Comment thread src/Common/ColumnsHashing/HashMethod.h Resolved
Addresses clickhouse-gh[bot] review feedback on ClickHouse#105756 / ClickHouse#105748:
`HashMethodOneNumber` only canonicalized 32 and 64-bit float keys.
Single-column `BFloat16` keys go through the `key16` path (FieldType
is `UInt16`), so `SELECT DISTINCT`, `GROUP BY`, and the `nullable_key16`
variant still split NaN values by sign or payload.

Extend `needsFloatNaNCanonicalization`, `canonicalizeFloatBitsAsField`,
and `may_canonicalize_nan` to also recognize the 2-byte width and
`ColumnBFloat16`, folding through `canonicalNaN<BFloat16>()`. For
non-`BFloat16` 2-byte columns (`UInt16`, `Int16`) the runtime check in
`needsFloatNaNCanonicalization` returns false, so there is no overhead.

The `ColumnVector<T>::updateHash*` and `AggregateFunctionUniq::Adder`
paths in the original commit already canonicalize `BFloat16` via the
generic `is_floating_point<T>` predicate, so no further changes are
needed there.

Extends the regression test to cover `BFloat16` and `Nullable(BFloat16)`
across `uniqExact`, `SELECT DISTINCT`, and `GROUP BY`.

Issue: ClickHouse#105748
Comment thread src/Common/NaNUtils.h Resolved
`std::numeric_limits<T>::quiet_NaN` is implementation-defined, so two
libc++/libstdc++ builds are not guaranteed to pick the same bit pattern.
`uniqExact` and similar set aggregates serialize/deserialize keys byte-wise
without re-canonicalizing on read, so distributed merges across mixed
architectures need a stable canonical form.

`canonicalNaN<T>` now returns explicit IEEE 754 positive quiet NaN bit
patterns via `std::bit_cast` (or `BFloat16::fromBits`):

  - `Float32`  -> `0x7FC00000`
  - `Float64`  -> `0x7FF8000000000000`
  - `BFloat16` -> `0x7FC0`

Added `gtest_canonical_nan` that pins these bit patterns explicitly so any
future regression on any platform is caught at unit-test time.

See issue ClickHouse#105748.
Addresses clickhouse-gh[bot] review feedback on ClickHouse#105756 / ClickHouse#105748.

`AggregateFunctionUniqCombined::add` hashes floating values via
`intHash64(bit_cast<UInt64>(value))` directly. Because the existing
canonicalization sits in `ColumnVector::updateHashWithValue`,
`HashMethodOneNumber::getKeyHolder`, and `AggregateFunctionUniq::Adder`,
the `uniqCombined` and `uniqCombined64` paths still split NaN values
with different sign or payload bits. That matters for `countDistinct`
too, since it rewrites to whichever implementation is configured via
`count_distinct_implementation` (`uniqCombined` and `uniqCombined64`
are valid choices).

Fold every NaN bit pattern through `canonicalizeNaN` before the hash,
mirroring the `AggregateFunctionUniq::Adder` fix already in this PR.
The change is contained to the floating-point branch, so non-floating
types and the existing `String`/`IPv6`/`UInt128`/big-integer paths are
untouched.

Extends the regression test (`04275_105748_distinct_nan_canonicalization`)
to cover `uniqCombined` and `uniqCombined64` for `Float64`, `Float32`,
and `BFloat16`, plus the `countDistinct` rewrite chain under both
`count_distinct_implementation` modes.

Issue: ClickHouse#105748
@Algunenano Algunenano self-assigned this May 25, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 25, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 91.40% 91.40% +0.00%
Branches 76.60% 76.60% +0.00%

Changed lines: 99.03% (102/103) · Uncovered code

Full report · Diff report

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

@groeneai I don't like this change for several reasons:

  • It's only a partial fix. You've already mention that there are multiple other places where this should be extended but it's not covered. AKA it's inconsistent.
  • The old behaviour was consistently inconsistent, in the sense that it wasn't done in any path. It was also tested as such.
  • Neither grouping or not grouping all NaNs as equal seem to be much different in practice. I see you mentioned other databases, but not the standard.
  • This has a noticeable performance impact for extremely little benefit. Running SELECT uniq(toFloat64(number)) FROM numbers(10000000000) I measure over 25% performance degradation (9.99 sec vs 12.7 seconds).

All in all, I don't think it's worth it. Either we address it completely and with little performance impact, or we just document it properly and keep living with it (as we've always done)

@groeneai

Copy link
Copy Markdown
Collaborator Author

@Algunenano thanks for the review and the perf measurement. All 4 points are fair.

Partial fix: agreed. The PR only covers single-key Float hash paths. SetVariants::nullable_keys128, HashMethodKeysFixed (packed keys), and tuple/array byte-wise paths still split NaNs, so users can hit the same issue via Nullable(Float) DISTINCT or Tuple(Float, ...) GROUP BY. That is the new inconsistency you describe.

Perf: the 25% comes from the per-row isNaN check in canonicalizeNaN inside the aggregation inner loop. A branchless cmov rewrite would shave some cycles, but recovering the full 25% on a ~1ns/row loop likely needs a batch-level "any-NaN" pre-check, which is a much larger refactor across every call site.

Standard: you are right that the IEEE / SQL standard does not mandate NaN-equal set semantics, only the scalar = returning false. The cross-DB precedent argument alone is not strong enough to justify the perf cost.

My recommendation is your option 2: close this PR and open a docs PR explaining the bit-pattern split (glibc scalar log vs ARM NEON fastops log, 0./0. vs literal nan, etc.) and pointing users at explicit canonicalization (isNaN() / nullIf) in their queries when they need NaN-equal set semantics. The regression test from #105748 becomes the docs example.

OK to proceed with close + docs PR, or do you prefer the complete-fix + branchless route pursued instead?

@Algunenano

Copy link
Copy Markdown
Member

@groeneai I agree, let's improve the docs and close this

@groeneai

Copy link
Copy Markdown
Collaborator Author

Closing per @Algunenano's review. The complete-fix-with-no-perf-cost route (extending canonicalization to SetVariants::nullable_keys128 / HashMethodKeysFixed packed keys / multi-key byte-wise paths plus a branchless or batch-level pre-check to recover the 25% perf regression on uniq HLL) is deferred until there is appetite for the larger refactor.

Replaced by docs-only PR #105787, which adds a section to the Float types reference page explaining the bit-pattern split and shows two canonicalization patterns users can apply when they need NaN-equal set semantics.

Tracking issue #105748 will be closed by #105787.

@groeneai groeneai closed this May 25, 2026
pull Bot pushed a commit to CrazyForks/ClickHouse that referenced this pull request May 25, 2026
Adds a section to the Float types reference page explaining why
different NaN values can be treated as distinct by DISTINCT, GROUP BY,
uniqExact, countDistinct, and equi-JOIN on Float keys, and how to
canonicalize them in user queries.

Follow-up to discussion on ClickHouse#105756 (closed in favor of docs-only path).
Closes ClickHouse#105748.
DavidHe-2008 pushed a commit to DavidHe-2008/ClickHouse that referenced this pull request Jun 1, 2026
Adds a section to the Float types reference page explaining why
different NaN values can be treated as distinct by DISTINCT, GROUP BY,
uniqExact, countDistinct, and equi-JOIN on Float keys, and how to
canonicalize them in user queries.

Follow-up to discussion on ClickHouse#105756 (closed in favor of docs-only path).
Closes ClickHouse#105748.
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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

DISTINCT does not deduplicate NaN on AArch64 (regression from #98230, fastops on ARM)

3 participants