Repository navigation
Conversation
…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]>
|
Pre-PR validation gate (per TASK.md Phase 4 Step 9):
Session id: cron:clickhouse-ci-task-worker:20260524-224500. |
|
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. |
|
Workflow [PR], commit [9f5558c] Summary: ❌
AI ReviewSummaryThis PR canonicalizes floating-point NaN bit patterns at hash/equality boundaries used by Missing context / blind spots
Final Verdict
|
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
`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
LLVM Coverage Report
Changed lines: 99.03% (102/103) · Uncovered code |
Algunenano
left a comment
There was a problem hiding this comment.
@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)
|
@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. Perf: the 25% comes from the per-row Standard: you are right that the IEEE / SQL standard does not mandate NaN-equal set semantics, only the scalar My recommendation is your option 2: close this PR and open a docs PR explaining the bit-pattern split (glibc scalar OK to proceed with close + docs PR, or do you prefer the complete-fix + branchless route pursued instead? |
|
@groeneai I agree, let's improve the docs and close this |
|
Closing per @Algunenano's review. The complete-fix-with-no-perf-cost route (extending canonicalization to 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. |
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.
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.
Closes #105748.
bitEqualsinHashTable.hcompares hash keys byte-wise, so two NaN values that differ only in sign bit or mantissa payload are treated as distinct. This breaksDISTINCT,GROUP BY,uniqExact, andcountDistinct:0./0.is0xFFF8000000000000on x86, the literalnanis0x7FF8000000000000.log(-1.)returns a NaN whose sign bit differs from glibc's scalarlog(-1.).The fix folds every NaN bit pattern onto the canonical positive quiet NaN at three call sites:
ColumnVector<Float>::updateHashWithValue/updateHashWithValueRange/updateHashFast/getWeakHash32(used byhashed/serializedset methods and multi-key SipHash paths).ColumnsHashing::HashMethodOneNumber::getKeyHolderfor single-column numeric keys (thekey32/key64andnullable_key32/nullable_key64variants).AggregateFunctionUniq::AdderforuniqExact/countDistinct(which inserts the value directly intoHashSet<Float>rather than going throughHashMethodOneNumber), plus theinsertManyfast path used by theuniqHLL family.For non-floating-point types every change is a compile-time no-op:
canonicalizeNaN<T>reduces to identity and themay_canonicalize_nanflag onHashMethodOneNumberisfalseso the branch is pruned. For floating-point columns the cost is oneisNaNcheck per key access, on the predicted-not-taken path for non-NaN data.JOIN with NaN keys: the
HashJoin::KeyGetterpath usesHashMethodOneNumber, so after this change two NaN-valued rows compare equal underON l.x = r.x(consistent withuniqExact/DISTINCT). The scalar=operator continues to follow IEEE 754 (nan = nanis0). 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 throughSetVariants::nullable_keys128(HashMethodKeysFixed multi-key packing) rather thanHashMethodOneNumber.DISTINCT/GROUP BYof(Float, ...),Tuple(Float, ...),Array(Float)likewise use raw bytes when packing the fixed-size hash key.Regression test:
04275_105748_distinct_nan_canonicalizationcovers the reproducer from #105748 plusFloat32/Float64/Nullable(Float64)variants and a materialized table with four NaN producers. The pre-existing test01428_hash_set_nan_keyhad a final assertion that constructs ten distinct NaN bit patterns and expected ten distinct values; that expectation is updated to1with an inline comment.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed
DISTINCT,GROUP BY,uniqExact, andcountDistinctto treat NaN values consistently regardless of bit pattern. Previously, NaN values produced by different operations (e.g.0./0.versus the literalnan, or ARM NEONlog(-1.)versus glibclog(-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 fornan = nanper IEEE 754.Documentation entry for user-facing changes