Skip to content

Make hash tables agree with equals on negative zero - #115970

Open
alexey-milovidov wants to merge 134 commits into
masterfrom
fix-negative-zero-hash-keys
Open

alexey-milovidov wants to merge 134 commits into
masterfrom
fix-negative-zero-hash-keys

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 23, 2026 •

Copy link
Copy Markdown
Member

Closes: #117334
Closes: #65316
Closes: #68928
Closes: #116358

Hash tables in ClickHouse compare floating point keys bitwise, so that NaN is equal to itself and GROUP BY and DISTINCT work on NaN values. Negative zero has a different binary representation than positive zero, but is equal to it by the rules of comparison, so everything based on hashing disagreed with the equals function:

SELECT materialize(-0.) = materialize(0.);                                    -- 1
SELECT count() FROM (SELECT 0. AS x) a JOIN (SELECT -0. AS x) b USING (x);    -- 0, expected 1
SELECT materialize(-0.) IN (0.);                                              -- 0, expected 1
SELECT count() FROM (SELECT arrayJoin([0., -0.]) AS x GROUP BY x);            -- 2, expected 1
SELECT uniqExact(x) FROM (SELECT arrayJoin([0., -0.]) AS x);                  -- 2, expected 1

Comparison-based operations, including the sorting merge join, did not have this problem, so the result of a query depended on the join algorithm. In the reported query, cross_to_inner_join_rewrite turns the WHERE predicate into a hash join key, 0 / -1 is -0., and the row that WHERE accepts is dropped by the join.

Negative zero is replaced with positive zero before a floating point value is hashed or used as a hash table key. This is possible because, unlike NaN, negative zero has exactly one binary representation. NaN is unchanged: it is not equal to itself, so hash tables cannot agree with equals on it, and grouping equal binary representations together remains the most useful behaviour.

The check is written on the binary representation on purpose - a floating point comparison with zero costs about 44% in the hashing loops, while the bit comparison is free.

Hash methods reinterpret a floating point column as an integer column of the same width (a Float64 key is looked up in a UInt64 hash table), and pack or serialize composite keys as raw bytes, so by the time a key is hashed the information that it is a floating point value is already lost. That is why the key columns are canonicalized as well, recursively for Nullable, Array, Tuple and Map. No copy is made when a column contains no negative zeros, which is the common case.

Two consequences worth calling out:

  • A GROUP BY key is reconstructed from the hash table, so a group that contains a negative zero is now reported as a positive zero. The values selected from a JOIN mostly come from the source blocks, so negative zero is preserved there, with one exception: with a single ON disjunct, a hash join restores the right key column from the left key column (required_right_keys in HashJoinResult), so when -0. matches 0. the right key is returned with the sign of the left key (full_sorting_merge keeps the right value). Before this change such rows were not matched at all.
  • bloom_filter indexes hash floating point values the same way, which fixes a related discrepancy: a granule containing -0. was skipped for WHERE x = 0.. For index data written by older versions, which stores the raw-bit hash of -0., a probe for a floating point zero also tries the legacy hash, so old parts keep returning correct results for both WHERE x = 0. and WHERE x = -0. (extra probes only make the filter more permissive, so this is always safe). In the other direction, a granule that contains a floating point zero also gets the legacy raw-bit hash of -0. written into it, so that a server of an older version, which probes -0. with that hash, finds the parts written by this version as well.

Per review, the same canonicalization is applied in the places that hash values by their raw bytes outside of hash table keys: the variadic and tuple forms of uniq* (uniqExact(-0., 1), uniq(tuple(-0.))), and the generic deduplication path of arrayDistinct for composite elements such as [(0., 1), (-0., 1)].

Per further review, the canonicalization is applied everywhere a floating point value takes part in set semantics by its binary representation, not only in the hash table keys:

  • The key columns of a hash method are canonicalized recursively for Variant, Dynamic and JSON as well. The values that a Dynamic column keeps in its shared variant, and a JSON column in its shared data, are stored as a binary encoded type followed by the value, so they are decoded, canonicalized and encoded back - only for the types that can contain a floating point value, which is checked on the decoded type without reading the value.
  • The functions that deduplicate values by their serialized representation see one row at a time, so canonicalizing the argument column - as the hash methods do - would need a copy of the column per row. The canonicalization is done in the serialization instead: IColumn::SerializationSettings has a new canonicalize_negative_zero flag, honoured by ColumnVector::serializeValueIntoMemory - the single method through which the value of a fixed size column is written into a serialized representation - and it applies recursively, because the composite columns pass the settings to their nested columns. The flag is set exactly where a serialized value is used as a set key: getKeyHolder (groupUniqArray and the -Distinct combinator - groupArrayDistinct, minDistinct, ...), AggregateFunctionDistinctMultipleGenericData, topK, topKWeighted, groupArrayIntersect, arrayIntersect, and the complex keys of dictionaries, so that dictGet(dict, attr, (-0.)) finds the value stored for 0.. It is not set where a serialized value is a value and not a key, e.g. groupArray, which keeps negative zero as it is.
  • A value of a type that is unambiguously represented in a contiguous memory region does not go through the serialization at all: it is used as a key by the raw bytes that IColumn::getDataAt returns, which is the path an Array(Float64) argument of the functions above takes, and the path of the non-exact UniqVariadicHash for a composite argument (uniq, uniqCombined, uniqHLL12 and uniqUpTo). Such bytes are a flat sequence of floating point values of the same width, so rawFloatValueWidth recognizes them and the callers hash a canonicalized copy - made in the arena and rolled back when the key was not inserted, so a lookup leaves nothing behind.
  • ColumnVector::updateHashWithValue normalizes negative zero. This is the generic way to hash a single value of a column, so arrayUniq, arrayEnumerateUniq, arrayEnumerateDense and the single argument composite forms of uniq* (uniqExact([-0.])) now agree with equals as well - the last one is the finding that was previously left as a known limitation. The hash functions available in SQL (sipHash64 and the others) do not use this method, so their results are unchanged, and neither is the hash that identifies a block for insert deduplication, which hashes whole ranges of values (updateHashWithValueRange).
  • transform looks its first argument up in a hash table of the elements of the second one, keyed on the binary representation of a value (a floating point value is reinterpreted as a UInt64 on purpose, so that NaN is found), which made transform(-0., [0.], ...) not find the zero. Both sides of the lookup are canonicalized now.

Because row evaluation now matches a stored -0. against a set that contains 0., primary key analysis of IN had to follow: with a sorting key that is a deterministic transform separating the two spellings, such as ORDER BY reinterpretAsUInt64(f), the set index pushed only the spelling that is in the set into key space and could prune away the granule holding the other one. The set index is declined for such a transform now, and pruning is kept when the set holds no zero, or when the key type is only known at runtime and the elements are not zeros. The same composition on the equals / notEquals / isNotDistinctFrom atoms is a pre-existing bug, independent of this change, and is fixed in #117611.

Not covered, on purpose: the hash functions available in SQL and the hash that identifies a block for insert deduplication - the results of these have to stay stable, and they are documented as being computed on the binary representation of a value.

The Hash output format is a fingerprint of the result as it is, so it has to keep telling -0. and 0. apart even though updateHashWithValue no longer does: a value that contains a negative zero (also inside LowCardinality, Nullable, Array, Tuple, ...) additionally contributes its serialized representation to the hash. Every fingerprint of a result without a negative zero is byte-identical to the one of the previous version (checked against a master binary).

Aggregate function states written by an older version are read without any change (the state format is the same), but they keep the content they were written with: an old uniq*, topK, groupUniqArray, -Distinct or groupArrayIntersect state that has seen both zeros keeps them as two entries after -Merge. For the hashed sketches (uniq, uniqCombined, uniqTheta) the original value is not recoverable from the state at all. States built by this version, and old states re-aggregated from the source data, treat the two zeros as one value.

Existing tests that changed meaning:

  • 03254_uniq_exact_two_level_negative_zero - the state is 8 bytes smaller, because the two zeros are now one key, and the size no longer depends on rand().
  • 04312_in_order_aggregation_inconsistency - this test documents the disagreement between hash grouping and in-order grouping. The negative zero half of it is now consistent; NaN-payload cases were added so the test still covers the part that cannot be fixed.
  • 04649_distinct_in_order_final_float_equality, 05082_distinct_in_order_signed_zero and the gtest DistinctSetFilterExtraction.FloatBitPatternsSurviveExtraction pinned -0. and 0. as two groups of the hash DISTINCT / LIMIT BY / GROUP BY; they are one group now, while NaN payloads stay apart.

Where updateHashWithValue identifies a constant rather than a set key - the key of the compiled expression cache (CompileDAG::hash), ActionsDAG::updateHash (the query condition cache), the deduplication of constants in ActionsDAG::deduplicateSubtrees (ConstantKeyHash / constColumnsEqual), and candidateFingerprint of TTL - the two zeros are different values (1 / -0. is -inf), so a constant that contains a negative zero additionally contributes its serialized representation, and every other constant hashes exactly as before.

The bucket of a key in the bucketed Map serialization is a part of the format of a data part, so it keeps hashing floating point keys by their raw bits (updateHashWithRawValue), exactly as before, and parts remain compatible with older versions in both directions.

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 operations on Float32 and Float64 values disagreeing about negative zero. -0. and 0. are equal by the rules of comparison, but they used to be treated as two different values by everything based on hashing, so a hash JOIN on a floating point key did not match them, -0. IN (0.) was false, and GROUP BY, DISTINCT and uniqExact counted them twice. Negative zero is now canonicalized to positive zero before it is used as a hash table key. Aggregate function states written by older versions keep the two zeros apart until they are re-aggregated.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

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

alexey-milovidov and others added 2 commits August 23, 2026 01:29
Hash tables in ClickHouse compare floating point keys bitwise, so that `NaN`
is equal to itself and `GROUP BY` and `DISTINCT` work on `NaN` values.
Negative zero has a different binary representation than positive zero, but is
equal to it by the rules of comparison, so operations based on hashing
disagreed with the `equals` function: a hash `JOIN` on a `Float64` key did not
match `0.` with `-0.`, `-0. IN (0.)` was false, and `GROUP BY`, `DISTINCT` and
`uniqExact` counted them as two values, while `=` and the sorting merge join
treated them as one.

Replace negative zero with positive zero before a floating point value is
hashed or used as a hash table key. The check is written on the binary
representation, because a floating point comparison with zero costs about 44%
in the hashing loops, while the bit comparison is free.

Hash methods reinterpret a floating point column as an integer column of the
same width, and pack or serialize composite keys as raw bytes, so by the time
a key is hashed the information that it is a floating point value is already
lost. That is why the key columns are canonicalized as well, recursively for
`Nullable`, `Array`, `Tuple` and `Map`. No copy is made when a column contains
no negative zeros, which is the common case.

Closes: #65316

Co-Authored-By: Claude Fable 5 <[email protected]>
The hash based `DISTINCT` now canonicalizes negative zero, so it agrees with the
sorted `DISTINCT` on `0.` and `-0.`. `NaN` values with different payloads still
survive as separate rows, which is what the test keeps covering.

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4dde534]

Summary: ❌

job_name test_name status info comment
Integration tests (amd_asan_ubsan, db disk, targeted) FAIL
test_ai_functions/test.py::test_filter_where FAIL cidb
test_ai_functions/test.py::test_filter_prewhere_after_cheap_condition FAIL cidb
test_ai_functions/test.py::test_filter_prewhere_behind_condition_left_in_where FAIL cidb
test_ai_functions/test.py::test_filter_truncated_response_throw FAIL cidb
test_ai_functions/test.py::test_filter_truncated_response_graceful FAIL cidb
test_ai_functions/test.py::test_filter_response_format FAIL cidb
test_ai_functions/test.py::test_filter_no_structured_output FAIL cidb
test_ai_functions/test.py::test_filter_null_input FAIL cidb
test_ai_functions/test.py::test_filter_profile_events FAIL cidb
test_ai_functions/test.py::test_filter_prewhere FAIL cidb
290 more test cases not shown
Stateless tests (amd_asan_ubsan, db disk, distributed plan, targeted) FAIL
01409_topK_merge ERROR cidb
Server died FAIL cidb
Logical error: 'this->use_count() == 1' (STID: 2508-3293) FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

The PR makes hashing and set operations treat negative and positive floating-point zero as equal, including composite values, aggregate keys, joins, and Bloom indexes. At head 4dde5341f546131093160b7f1bd1a1e0d26b476c, two correctness blockers remain: mixed-version aggregation can split identical keys, and transported runtime Bloom filters bypass build-side normalization.

Findings

❌ Blockers

  1. Mixed-version aggregation can return duplicate groups. src/Common/ColumnsHashing/HashMethod.h:142 canonicalizes keys, but Aggregator::mergeBlocks still merges into the sender-selected bucket. Old and new shards assign identical negative-zero source keys to different buckets, so the coordinator cannot combine them. The existing reproduction returns two (0, 1) groups instead of one (0, 2) group during a rolling upgrade; an old coordinator also splits the keys with single-level aggregation. The author acknowledges the issue and leaves the rollout policy pending. Coordinate the key/bucket policy across revisions, or obtain an explicit maintainer decision accepting the incompatibility with corresponding changelog and upgrade guidance. Existing thread.

  2. Transported runtime Bloom filters can discard matching join rows. src/Processors/QueryPlan/RuntimeFilterLookup.cpp:1300 canonicalizes probes, but BuildRuntimeFilterPartialTransform::work at src/Processors/QueryPlan/BuildRuntimeFilterStep.cpp:193 inserts directly into AdaptiveSetRuntimeFilter, bypassing RuntimeFilter::insert. After exact-set overflow, the transported Bloom state therefore hashes raw negative-zero bytes. Wrapping that state in RuntimeFilter makes even an identical negative-zero probe use a different hash. Normalize all build paths before populating the Bloom state. This source-traced path remains after the claimed fix; the existing bot thread is reopened with the concrete bypass. Existing thread.

Tests
  • ⚠️ Add mixed-version aggregation coverage with old/new shards, both coordinator versions, and forced two-level aggregation, unless maintainers explicitly accept and document an upgrade restriction.
  • ⚠️ Extend 05768_join_runtime_filter_bloom_signed_zero with transported filters: enable make_distributed_plan and distributed_plan_join_runtime_filters, force exact-set overflow, include negative zero on the build side, and verify that filter transport and Bloom evaluation actually occur. Compare the result with runtime filtering disabled.
  • The fetched CI reports report 15,410 passed, zero failed, and 4,567 skipped tests. No local binary execution was available; these results do not establish the two cases above.
Final Verdict

Status: ❌ Block

Close the transported-filter normalization gap and settle the mixed-version aggregation policy, with the focused regression coverage described above.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 23, 2026
`docs/reference/data-types/float.mdx` is generated from the embedded
documentation of the `Float64` data type, and the whole page body sits inside an
`AUTOGENERATED` region, so the docs check rejects direct edits to it. Put the
new section into `src/DataTypes/DataTypesNumber.cpp` instead and leave the
generated page to the nightly regeneration job.

Co-Authored-By: Claude Fable 5 <[email protected]>
@mintlify

mintlify Bot commented Aug 23, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated
ClickHouse-docs 🟢 Ready View Preview Nov 24, 2026, 8:37 AM

`04234_non_constant_rhs_in` and `04811_constant_lambda_rhs_in` documented
the disagreement between the constant `Set` path, which was keyed on raw
float bits, and the row-wise comparisons a non-constant right-hand side
lowers to: `-0.0 IN (0.0)` was 0 in the first and 1 in the second. The
`Set` now canonicalizes negative zero, so both agree on 1.

Also renumber the new test to `05044_negative_zero_hash_keys`, because
`05037` was taken by `05037_postgresql_startup_message_size` on master.
Comment thread src/Common/HashTable/Hash.h Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 5826a21bf with master 6618395f5 (stripped binary size, per-symbol sizes and ThinLTO time; 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 ⚠️

367 object files changed (+1.56 MiB total), 1 added.

Object file Master PR Δ
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniq.cpp.o 13.67 MiB 13.93 MiB +258.80 KiB (+1.85%)
src/CMakeFiles/dbms.dir/Columns/canonicalizeNegativeZero.cpp.o new 152.24 KiB +152.24 KiB
src/Functions/array/CMakeFiles/clickhouse_functions_array.dir/arrayUniq.cpp.o 574.16 KiB 624.05 KiB +49.89 KiB (+8.69%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/RightHashJoinAsof.cpp.o 1.78 MiB 1.83 MiB +49.64 KiB (+2.72%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/InnerHashJoinAsof.cpp.o 1.78 MiB 1.83 MiB +49.62 KiB (+2.72%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/FullHashJoinAsof.cpp.o 2.03 MiB 2.08 MiB +49.30 KiB (+2.37%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinAsof.cpp.o 2.03 MiB 2.08 MiB +49.30 KiB (+2.37%)
src/CMakeFiles/dbms.dir/Interpreters/Aggregator.cpp.o 28.30 MiB 28.34 MiB +46.45 KiB (+0.16%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/HashJoin.cpp.o 4.21 MiB 4.25 MiB +40.61 KiB (+0.94%)
src/Functions/array/CMakeFiles/clickhouse_functions_array.dir/arrayEnumerateDense.cpp.o 574.62 KiB 614.88 KiB +40.25 KiB (+7.01%)
src/Functions/array/CMakeFiles/clickhouse_functions_array.dir/arrayEnumerateUniq.cpp.o 581.33 KiB 621.48 KiB +40.16 KiB (+6.91%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinAntiMapsAll.cpp.o 2.15 MiB 2.17 MiB +29.02 KiB (+1.32%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/RightHashJoinAnti.cpp.o 2.13 MiB 2.16 MiB +28.98 KiB (+1.33%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/InnerHashJoinAnyMapsAll.cpp.o 2.21 MiB 2.23 MiB +28.98 KiB (+1.28%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/InnerHashJoinRightAnyMapsAll.cpp.o 2.16 MiB 2.19 MiB +28.96 KiB (+1.31%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/RightHashJoinRightAny.cpp.o 2.22 MiB 2.25 MiB +28.95 KiB (+1.27%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinSemiMapsAll.cpp.o 2.17 MiB 2.19 MiB +28.95 KiB (+1.31%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/FullHashJoinAll.cpp.o 2.63 MiB 2.66 MiB +28.91 KiB (+1.07%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/FullHashJoinRightAny.cpp.o 2.44 MiB 2.47 MiB +28.90 KiB (+1.15%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinAll.cpp.o 2.57 MiB 2.60 MiB +28.90 KiB (+1.10%)

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.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.67, programs/clickhouse-keeper ×0.67 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 5.6 s 13.7 s +9.9 s (+263%)
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.3 s 7.6 s +5.4 s (+242%)
Compile time of recompiled translation units

2773 translation units recompiled, 16842 s compile time in total, 2772 of them have a recent master baseline.

Job report

…nonicalized behavior

The test was added on master and pinned the old behavior where `-0.0` and `+0.0`
hash differently. With this PR negative zero is canonicalized before hashing,
so they must hash identically.
The variadic and tuple forms of `uniq*` hash argument values by their raw bytes
via `getDataAt` / `updateHashWithValue`, so `uniqExact(-0., 1)` or `uniq(tuple(-0.))`
still treated signed zeros as different values. Intercept top-level floating point
argument columns (including the elements of a single tuple argument) and normalize
the value before hashing.
The generic path of `arrayDistinct` deduplicates elements by a SipHash of their
raw bytes, so composite elements such as `[(0., 1), (-0., 1)]` or `[[0.], [-0.]]`
(and `BFloat16` elements) kept both zeros. Canonicalize the elements column in
advance, recursively for composite elements, which also makes the result agree
with `GROUP BY` and `DISTINCT`.
…r` index

Canonicalizing negative zero changed the hash the `bloom_filter` index computes for
`-0.`, so a granule of a part written by an older version that contains only `-0.`
could be skipped incorrectly for `WHERE x = 0.` (and for `x = -0.`, which used to work).
On the predicate side, a probe for a floating point zero now also tries the raw-bit
hashes of `-0.` as written by the old code. Extra probes only make the filter more
permissive, so this is always safe; under the all-of semantics of `hasAll`, where
extra probes cannot be added, the zero probes are dropped instead, which is also
only permissive. The hashes written to the filter are not changed.
The `bloom_filter` index hashes `Float32` values after a conversion to `Float64`
(see `getNumberTypeHash`), so the only raw-bit hash of `-0.` ever written by the
old code is the `Float64`-width one.
Comment thread src/Functions/array/arrayDistinct.cpp Resolved
…d `JSON` columns

`canonicalizeNegativeZero` stopped at `Nullable`, `Array`, `Tuple` and `Map`, so a `Variant`,
`Dynamic` or `JSON` key of a hash method kept the raw representation of a negative zero and was
split into two hash table keys, while `compareAt` descends to the typed leaf values and reports the
two zeros as equal.

The values that a `Dynamic` column keeps in its shared variant, and a `JSON` column in its shared
data, are not stored in a typed column: they are stored as the binary encoding of their type
followed by the value, so they are decoded, canonicalized and encoded back. Only the type is
decoded for every such value; the value itself is deserialized only when its type can contain a
floating point value at all.
…uplicated by their serialized representation

`groupUniqArray`, the `-Distinct` combinator, `topK`, `groupArrayIntersect`, `arrayIntersect` and
the complex keys of dictionaries key a hash table on the serialized bytes of a value, one row at a
time, so canonicalizing the whole column - as the hash methods do - would need a copy of the column
per row.

The canonicalization is done in the serialization instead: `IColumn::SerializationSettings` has a
new `canonicalize_negative_zero` flag, honored by `ColumnVector::serializeValueIntoMemory` - the
single method through which the value of a fixed size column is written into a serialized
representation - and it applies recursively, because the composite columns pass the settings to
their nested columns. The flag is set only where a serialized value is used as a key, and not where
it is a value, such as in `groupArray`.
…hValue`

This is the generic way to hash a single value of a column, and it is used to group or deduplicate
equal values: `arrayUniq`, `arrayEnumerateUniq`, `arrayEnumerateDense`, `transform`, and the single
argument composite forms of `uniq*` and `uniqUpTo`, such as `uniqExact([-0.])` - the last one was
the remaining known limitation of the previous commits.

The hash functions available in SQL (`sipHash64` and the others) do not use this method, so their
results are unchanged, and neither is the hash that identifies a block for insert deduplication,
which hashes whole ranges of values (`updateHashWithValueRange`).
Comment thread src/Columns/IColumn.h Resolved
…tes are used as a key

A value of a type that is unambiguously represented in a contiguous memory region is used as a hash
table key by the raw bytes that `IColumn::getDataAt` returns, without going through the
serialization: `groupUniqArray`, the `-Distinct` combinator, `topK`, `topKWeighted` and
`groupArrayIntersect` take that path for an `Array(Float64)` argument, and so does the non-exact
`UniqVariadicHash` for a composite argument, which is what `uniq`, `uniqCombined`, `uniqHLL12` and
`uniqUpTo` of an `Array(Float64)` use.

Such bytes cannot be canonicalized in place, but they are a flat sequence of floating point values
of the same width, so `rawFloatValueWidth` recognizes them and the callers make a canonicalized
copy. In the hash table paths the copy is made in the arena and rolled back if the key was not
inserted, so nothing is left behind for a lookup.

This is the case that the previous commits missed: `groupArrayDistinct(arrayJoin([[0.], [-0.]]))`
and `uniqUpTo(3)(arrayJoin([[0.], [-0.]]))` still returned both zeros.
`transform` looks the value up in a hash table of the elements of its second argument, keyed on the
binary representation of a value - the `Field` of a floating point value is reinterpreted as a
`UInt64` on purpose, so that `NaN` is found - which made `transform` disagree with the `=` operator
on negative zero: `transform(-0., [0.], [...])` did not find the zero.

The `from` column is canonicalized once, when the lookup table is built, and the values that are
looked up in it are canonicalized as well - on the numeric path by normalizing the value before it
is reinterpreted, and on the contiguous path by canonicalizing the input column of the block. The
generic path hashes the values with `IColumn::updateHashWithValue`, which canonicalizes them
already.
…duplicating aggregate functions, and in `transform`

Covers the three places the canonicalization was extended to: the keys of a hash method for the
carrier types (`Variant`, `Dynamic` with a value in the shared variant, `JSON` with a dynamic path,
a typed path and a value in the shared data, and `Map`), the values that are deduplicated by their
serialized or raw representation (`groupUniqArray`, `groupArrayDistinct`, `uniqExactDistinct`,
`topK`, `topKWeighted`, `groupArrayIntersect`, `arrayIntersect`), the values that are hashed by
their generic binary representation (`arrayUniq`, `arrayEnumerateUniq`, `arrayEnumerateDense`,
`uniqExact`, `uniq`, `uniqCombined`, `uniqHLL12`, `uniqUpTo`), `transform`, and the complex key of a
dictionary.

`groupArray` is there to show that a value is not canonicalized when it is not used as a key.
It is called for every row on the paths that key on the raw bytes of a value, including the ones
that never contain a floating point value, such as `groupUniqArray` of a `String`, so it dispatches
on `IColumn::getDataType` instead of a chain of `typeid_cast`.
alexey-milovidov and others added 2 commits November 10, 2026 04:54
Depending on the insert path, the sorting key of the stored `LowCardinality(Float64)` zero row is
computed from either `-0.` or `0.`, so the row sorts either last or first. When it sorts first, the
granule ranges of the three-row part all touch the set `(1., 2.)`, and nothing can be pruned, so the
`max_rows_to_read = 2` check failed in the Fast test. Probe values away from both ends instead.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=115970&sha=29c934c02c6bc87201a041246dc1a4e55137b9d9&name_0=PR&name_1=Fast%20test
#115970

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Common/ColumnsHashing/HashMethod.h Resolved
alexey-milovidov and others added 2 commits November 11, 2026 11:31
…it has no negative zeros

`HashOutputFormat::consume` removed `LowCardinality` from every column to look for
negative zeros, which materializes all dictionary references even for types such as
`LowCardinality(String)` that cannot contain one. Now a column is checked only if its
type may contain a floating point value (`mayContainNegativeZero`), and a top-level
`LowCardinality` column is expanded only if its dictionary has a negative zero.
The fingerprints are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A probe that hits `max_joined_block_rows` is continued by `HashJoin::ContinuationResult`
over the remaining suffix of the same source block, and every dispatch built new key
getters that scanned the whole key columns for negative zeros again, which is quadratic
in the block size. Now `JoinOnKeyColumns` canonicalizes the key columns in the first
dispatch over a block and keeps them in `CanonicalJoinKeys`, owned by the continuation,
and the key getters are told the keys are already canonicalized
(`RowRange::negative_zeros_canonicalized`, now accepted by `HashMethodOneNumberInRange` too).
`hash_join_probe_continuation.xml` is extended with `Float64` keys.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 2 commits November 12, 2026 14:39
…o fix-negative-zero-hash-keys

# Conflicts:
#	src/Processors/Transforms/RadixUniqExactTransform.cpp
`HashMethodHashedJoinKey`, the new key getter of the `hashed` and
`two_level_hashed` join maps that came from master, hashed the key
columns without replacing negative zeros, so composite keys such as
`(Float64, String)` or `Tuple(Nullable(Float64))` built on the right
side did not match a positive zero on the left side. It now canonicalizes
the key columns unless `RowRange::negative_zeros_canonicalized` says the
probe has already done it.

Also declare `ErrorCodes::LOGICAL_ERROR` in `AddedColumns.cpp` (style check).

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=115970&sha=1bf37f461293a029e6679e1f49f738641a67b68e&name_0=PR&name_1=Fast%20test

Co-Authored-By: Claude Opus 5.5 <[email protected]>
canonical_keys.clear();
canonical_keys.reserve(key_columns.size());
for (const auto * key_column : key_columns)
canonical_keys.push_back(canonicalizeNegativeZero(*key_column));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

❌ Blocker: runtime Bloom filters still reject matching signed-zero keys

Canonicalizing the join keys here happens after the probe-side runtime filter. ApproximateSetRuntimeFilter::insertIntoBloomFilter and find still use forEachColumnHashBatch in src/Processors/QueryPlan/RuntimeFilterLookup.cpp:289-325, which hashes getRawData / getDataAt bytes without normalization. Once the adaptive filter exceeds its exact-set limit, it can therefore reject -0. before this lookup matches it to 0..

Reproduced with the exact head binary (5826a21bf1da):

SET max_threads = 1;
SET join_algorithm = 'hash';
SET query_plan_join_swap_table = 'false';
SET query_plan_optimize_join_order_algorithm = 'greedy';
SET query_plan_optimize_join_order_limit = 1;
SET join_runtime_filter_min_probe_rows = 0;
SET join_runtime_filter_exact_values_limit = 1;
CREATE TABLE p (k Float64) ENGINE = Memory;
CREATE TABLE b (k Float64) ENGINE = Memory;
INSERT INTO p VALUES (-0.0);
INSERT INTO b VALUES (0.0), (1.0);

SELECT count() FROM p INNER JOIN b ON p.k = b.k
SETTINGS enable_join_runtime_filters = 0; -- 1
SELECT count() FROM p INNER JOIN b ON p.k = b.k
SETTINGS enable_join_runtime_filters = 1; -- 0

The same comparison fails for Array(Float64) keys. It also reproduces with the default runtime-filter settings using 2,000 probe rows and 10,001 distinct build keys, so this affects ordinary larger joins. EXPLAIN PIPELINE confirms the filter is installed.

Please canonicalize both Bloom insertion and lookup keys centrally, including composite float carriers, and add a regression that forces the Bloom phase. The updated 05210 cases exercise only the exact-set phase.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🕵 Fixed in 4fb4b2e. RuntimeFilter::insert and RuntimeFilter::find now replace negative zeros with positive zeros in the keys, using canonicalizeNegativeZeroThroughLowCardinality, whenever the key type may contain a floating point value (mayContainNegativeZero). This is one central place, so the exact set, the Bloom filter and the adaptive filter all agree with the join, including composite keys (Array, Tuple) and LowCardinality(Float64). Your reproducer now returns 1 with and without runtime filters. The same bug made 05245_spilling_join_float_keys_no_order_fallback fail in CI under query_plan_optimize_join_order_randomize, which swaps the sides so that the -0. row is probed through a Bloom filter. I added 05768_join_runtime_filter_bloom_signed_zero: it forces the Bloom phase with join_runtime_filter_exact_values_limit = 1 and also covers the exact-set phase, an ANTI join, and a negative zero on the build side.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Blocker] The fix still misses transported runtime filters. At src/Processors/QueryPlan/BuildRuntimeFilterStep.cpp:193, BuildRuntimeFilterPartialTransform::work calls AdaptiveSetRuntimeFilter::insert directly, bypassing RuntimeFilter::insert. Once the exact set overflows, that path inserts the original column into the Bloom filter through ApproximateSetRuntimeFilter::insertIntoBloomFilter (src/Processors/QueryPlan/RuntimeFilterLookup.cpp:651), which hashes raw bytes.

registerCompleteRuntimeFilter subsequently wraps this already-built state in RuntimeFilter, whose lookup now canonicalizes the probe at src/Processors/QueryPlan/RuntimeFilterLookup.cpp:1300. A build-side -0. inserted in the Bloom phase is therefore hashed differently from even an identical -0. probe, so matching join rows can still be discarded. This is reachable with make_distributed_plan = 1 and distributed_plan_join_runtime_filters = 1 on a single version.

Please normalize at the shared adaptive insertion boundary, or cover the transported builder explicitly, and add a transported-filter regression that forces the Bloom phase. The existing 05768_join_runtime_filter_bloom_signed_zero covers the local builder. This remaining path is established by source tracing; I could not execute a binary in this CI review job.

alexey-milovidov and others added 4 commits November 14, 2026 06:17
The hash join matches `-0.` with `0.`, but the runtime filter built for it
compared the keys bitwise: the Bloom filter of `ApproximateSetRuntimeFilter`
hashes the raw bytes of the keys. So a probe row with `-0.` could be rejected
before the join matched it, e.g. in `05245_spilling_join_float_keys_no_order_fallback`
with `query_plan_optimize_join_order_randomize`, which swapped the sides.

`RuntimeFilter::insert` and `RuntimeFilter::find` now replace negative zeros with
positive zeros in the keys when the key type may contain a floating point value,
so every kind of filter (exact set, Bloom filter, adaptive) agrees with the join,
including composite keys and `LowCardinality`.

Addresses the review comment about runtime Bloom filters rejecting matching
signed-zero keys.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=115970&sha=5826a21bf1da6fca40ab5f10a97582f758c88fff&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20flaky%20check%29
PR: #115970

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The test came from master, where the `hashed` join maps compared float keys
bitwise. With this PR, `-0.` matches `0.`, so the `f_s` key (`Float64`, `String`)
has more matches. The new count, 7254, was checked against a join on
`reinterpretAsUInt64(f + 0.)`, which compares the canonicalized bits.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=115970&sha=5826a21bf1da6fca40ab5f10a97582f758c88fff&name_0=PR&name_1=Stateless%20tests%20%28arm_asan_ubsan%2C%20targeted%29
PR: #115970

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…` without negative zeros

`HashOutputFormat::consume` removed `LowCardinality` recursively from every column
whose type may contain a floating point value before looking for negative zeros,
so `Tuple(LowCardinality(String), Float64)` expanded the whole string dictionary.

The check now runs `canonicalizeNegativeZeroThroughLowCardinality` on the column
as it is: it looks into the nested dictionaries and expands one only if it has a
negative zero. The serialized value of a `LowCardinality` row is its dictionary
value, so the column no longer needs to be expanded for the comparison either, and
the fingerprints stay the same.

Extended `05617_hash_output_format_wide_low_cardinality_string` with the tuple case.

PR: #115970

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 5 commits November 18, 2026 07:41
# Conflicts:
#	src/Columns/ColumnVector.h
#	src/Common/ColumnsHashing/HashMethod.h
#	src/Processors/Transforms/DistinctSortedStreamTransform.cpp
#	src/Processors/Transforms/DistinctSortedStreamTransform.h
`HashOutputFormat::consume` serialized both the value and its canonical form into
one `Arena` and then rolled back both allocations. When the second allocation
started a new chunk, rolling back the first one from that chunk moved the head
pointer before the start of the chunk, so later values were written over
other memory and the fingerprint depended on how the result was split into
blocks. It made `05617_hash_output_format_wide_low_cardinality_string` fail
in the Fast test. Each value now gets its own arena, which holds one
allocation at a time.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=115970&sha=latest&name_0=PR&name_1=Fast%20test
PR: #115970

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

The test came from `master` and pinned that `uniqExact` counts `0.0` and
`-0.0` as two values. With this change they are one value, both in the
ordinary aggregation and in `UniqExactInOrderTransform`, which passes the run
of zeros to `uniqExact`. Update the reference and the comments.

PR: #115970

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`modernize-use-nodiscard` was enabled on `master`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…hing `0.0` in sets

The test came from `master` and pinned that `[-0.] IN (SELECT [0.])` is false.
With this change, sets canonicalize negative zeros, so it is true.

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

Copy link
Copy Markdown
Member Author

🕵 Merged master and fixed the Fast test failures:

  • 05617_hash_output_format_wide_low_cardinality_string exposed a real bug. HashOutputFormat::consume rolled back two allocations from one Arena. When the second value started a new chunk, the rollback moved the head pointer before that chunk, so the fingerprint of wide values with -0. depended on the block split. Each value now has its own arena (caa5fe2), and the test checks that the hash is the same for two block sizes.
  • 05507_uniq_exact_in_order and 04871_in_tuple_single_key_rewrite_in_to_join came from master and pinned that -0. and 0. are distinct. I updated their references.

The mixed-version aggregation thread is still open. It needs a maintainer to choose between the two options described there.

alexey-milovidov and others added 5 commits November 21, 2026 09:08
…ash-keys

Conflicts are in the hash join, which was reworked on master around `HashJoinTable`
(#120515):

- `createJoinKeyGetter` moved to `HashJoinTable.h`, so its `negative_zeros_canonicalized`
  argument is carried over there. The probe paths (`HashJoinTable::probe` and
  `HashJoinTable::prepareProbeAll`) pass `true`, because the keys of `JoinOnKeyColumns`
  are canonicalized once per source block (`CanonicalJoinKeys`), and the build paths keep
  the default, so the key getter canonicalizes the keys itself.
- `JoinOnKeyColumns` no longer has `key_sizes` (they live in `HashJoinTable`), and
  `joinBlockImpl` no longer takes the maps; the `CanonicalJoinKeys` arguments are kept.
- `Aggregator::mergeStreamsImpl` takes the state cache as an argument on master; the
  `negative_zeros_canonicalized` flag of the row range is kept.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Master added a hashing method for `GROUP BY` over fixed-width keys and one `String` key,
`HashMethodKeysAndPackedString`. It packs the fixed-width values into the hash table key as raw
bytes, so `GROUP BY x, s` with a floating point `x` put `-0.` and `0.` into different groups
again. The fixed-width key columns are now canonicalized as in the other hashing methods, unless
the caller has already done it (`RowRange::negative_zeros_canonicalized`), including the copy
of a sub-range with a `LowCardinality` fixed-width key.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
The test failed in the Fast test:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=115970&sha=2712e96360d21687cd78e57aa870479897a7b813&name_0=PR&name_1=Fast%20test
#115970

The fingerprints of the two `Dynamic` values changed on master, where the type name is now
delimited in the row hash of `Dynamic` ("Delimit paths and type names in the row hash of JSON
and Dynamic"). Besides, `-0.::Dynamic` is a cast of the string literal `'-0.'`, so the value
was a `String` and the queries did not check a floating point value inside `Dynamic` at all.
They are now written as `CAST(-0. AS Dynamic)`, which holds a `Float64`, and the two
fingerprints are pinned again.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
# Conflicts:
#	src/AggregateFunctions/AggregateFunctionQuantileExactWeighted.cpp
…act_tuples` for equal signed zeros

Both tests were added on `master` and pin the behaviour that this change
fixes: `-0.` and `0.` were different keys of hash tables.

- `05836_radix_uniq_exact_tuples`: `uniqExact` now counts `-0.` and `0.`
  as one value, with and without `optimize_uniq_exact_radix_partitioning`,
  so the counts for the `Float64` tuples are lower. The two paths still agree.
- `05829_order_by_float_redundant_keys`: `GROUP BY n WITH ROLLUP` over `0.`
  and `-0.` now produces one group and the total instead of two groups.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=115970&sha=b378557049532bf28c7985c99aa1d16bb39671a0&name_0=PR&name_1=Fast%20test
#115970

Co-Authored-By: Claude Fable 5.2 <[email protected]>

This branch was successfully deployed

1 active deployment
staging - docs — 4dde5341 Deployed Nov 24, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

4 participants