Skip to content

Replace negative zeros in hash keys only when they are present - #130054

Open
alexey-milovidov wants to merge 28 commits into
masterfrom
negative-zero-keys-scan
Open

alexey-milovidov wants to merge 28 commits into
masterfrom
negative-zero-keys-scan

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Nov 8, 2026 •

Copy link
Copy Markdown
Member

Related: #115970
Related: #126433

A less intrusive alternative to #115970, for comparison.

-0. is equal to 0., but hash tables compare floating point keys bitwise, so IN, GROUP BY, DISTINCT, LIMIT BY and hash JOIN treated them as different keys and disagreed with equals and with the comparison-based operators. SQLancer++ found it as a NoREC mismatch: WHERE (atan(false) / c2) NOT IN (log10(1)) returned 8 rows, while the same expression as a projection counted 11, because atan(false) / c2 is -0. for a negative c2.

Instead of changing the hash tables, the hash methods and the column hashing, a key column is quickly scanned for negative zeros right before it is hashed, and only if there are any, a copy is made with them replaced by positive zeros (replaceNegativeZeros, for Float32, Float64, BFloat16, also inside Nullable, Array, Tuple, Map, LowCardinality, Sparse, Const, Replicated). The scan is branchless in blocks of 256 values, so the common case costs one pass over the key column and no copy. It is applied in:

  • Set: building and lookup;
  • Aggregator::executeOnBlock;
  • DistinctSetFilter, DistinctSortedStreamTransform;
  • LimitByTransform, NegativeLimitByTransform;
  • hash JOIN: build and probe; the bucket scatter of grace hash join; ScatterByPartitionTransform;
  • the aggregation in order of a prefix of the keys (AggregatingInOrderTransform);
  • the fingerprints of spilled DISTINCT runs;
  • the Bloom runtime filter of a join (insertion and probing).

Several places relied on the keys being compared bitwise, and are adjusted to stay consistent:

  • KeyCondition does not use a set pushed through a key transform that tells the zeros apart (e.g. ORDER BY toString(a) with a IN ([0.0])), as it already does for =; otherwise the index prunes rows that the predicate matches.
  • optimize_inverse_dictionary_lookup is not applied to floating point keys: a dictionary lookup still tells the zeros apart.
  • the bloom_filter skip index is not used for an IN set that contains a floating point zero, because the index stores the hashes of the original representation.
  • optimize_injective_functions_in_group_by / ..._in_limit_by do not unwrap an injective function of a floating point argument with a non-floating point result (e.g. hex(f)), and optimize_group_by_function_keys / optimize_limit_by_function_keys do not drop expressions of a floating point key (e.g. toString(f) in GROUP BY f, toString(f)), because such expressions tell the zeros apart.

Not covered: uniqExact and other aggregate functions with their own hash sets, dictionaries, the hashes inside Dynamic/JSON values, the merging of partially aggregated blocks from another server. NaN is unchanged.

Found by SQLancer++: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=master&sha=233269369bec82828592b4429bf10e80690a41f2&name_0=NightlySQLancer&name_1=SQLancerPP%20%28arm_release%29

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

-0. and 0. are now the same key in IN, GROUP BY, DISTINCT, LIMIT BY and hash JOIN, in agreement with equals. Previously, e.g. materialize(-0.) IN (0.) returned 0.

🤖 Generated with Claude Code


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

alexey-milovidov and others added 3 commits November 7, 2026 17:49
`-0.` is equal to `0.`, but hash tables compare floating point keys bitwise, so `IN`,
`GROUP BY`, `DISTINCT`, `LIMIT BY`, hash `JOIN` and hash sharding treated them as different keys.

The key columns are quickly scanned for negative zeros right before they are hashed, and only if
there are any, a copy is made with them replaced by positive zeros. This is a less intrusive
alternative to #115970: the hash tables and the hash
methods are not changed. `uniqExact` and other aggregate functions are not covered.

Found by SQLancer++: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=master&sha=233269369bec82828592b4429bf10e80690a41f2&name_0=NightlySQLancer&name_1=SQLancerPP%20%28arm_release%29

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

Now that `IN` matches `-0.` with `0.`:
- `KeyCondition` does not use a set pushed through a key transform that tells the two zeros
  apart (e.g. `ORDER BY toString(a)` with `a IN ([0.0])`), as it already does for `=`.
  Otherwise the index pruned the rows holding the other zero.
- `optimize_inverse_dictionary_lookup` is not applied to floating point keys: a dictionary
  lookup still tells the zeros apart, so the rewrite to `IN` changed the result.
- Negative `LIMIT BY` replaces negative zeros in its keys as well.

Update the tests that pinned the old behaviour, and render zeros without the sign where the
surviving zero of a group depends on the order of rows.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3e899a3]

Summary: ✅


AI Review

Summary

The PR makes signed zeros equal in hash keys for IN, GROUP BY, DISTINCT, LIMIT BY, and hash JOIN, and adjusts related filtering and partition optimizations. Three previously reported correctness concerns remain in the current code. The author dismissed them; they are retained below without new inline comments or reopened threads. No additional inline findings were confirmed.

Findings

❌ Blockers

  • Key-removal optimizations do not preserve the new equality. src/Analyzer/Passes/OptimizeKeyExpressionsUtils.cpp:162 still unwraps injective functions without checking whether their outputs distinguish the zero signs. For input 0., -0., GROUP BY hex(f) can become grouping by f, collapsing two different strings into one group. Line 70 similarly allows dropping toString(f) from GROUP BY f, toString(f). The corresponding LIMIT BY optimizations have the same issue; these settings default to enabled. Preserve keys unless the rewrite preserves signed-zero equivalence, and compare results with the optimizations enabled and disabled. [dismissed by author -- https://github.com/Replace negative zeros in hash keys only when they are present #130054#discussion_r4522524739] The accepted tradeoff still changes group cardinality for distinct string keys; the earlier guards have been removed from the current code.

  • Matching join keys can overwrite the original right-side value. src/Interpreters/HashJoin/HashJoinResult.cpp:179 reconstructs requested right keys with copyLeftKeyColumnToRight. Joining a left 0. to a right -0. therefore exposes the right key as 0., observable through hex or toString. Join table reads also reconstruct keys from the normalized map key (src/Interpreters/HashJoin/HashJoinTable.h:1152), so their reads and mutations lose the original sign. Retain original keys as row payload and normalize only the lookup representation. [dismissed by author -- https://github.com/Replace negative zeros in hash keys only when they are present #130054#discussion_r4539755616] Accepting normalization of lookup keys does not preserve the values projected from matched rows or read for mutations.

  • Existing aggregate projections retain the old grouping semantics. src/Processors/QueryPlan/AggregatingStep.cpp:1148 selects only_merge for an aggregate projection, while src/Interpreters/Aggregator.cpp:6298 obtains merge keys through makeRawKeyColumnsForMerging, which does not normalize signed zeros. A projection written before this change can contain separate 0. and -0. groups: a hash merge still returns two groups, while reading and aggregating the base rows returns one. Normalize at the hash-merge boundary with consistent bucket routing, and add an upgrade regression against a projection containing both signs. [dismissed by author -- https://github.com/Replace negative zeros in hash keys only when they are present #130054#discussion_r4539755628] This remains a local persisted-data inconsistency, independent of the explicitly excluded merging of partial results from another server.

Final Verdict

Status: ❌ Block

Preserve equality through key-removal rewrites, preserve original join-key payloads, and make existing aggregate projections agree with base-table aggregation. Add focused regressions for these cases before approval.

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. labels Nov 8, 2026
@alexey-milovidov
alexey-milovidov marked this pull request as ready for review November 8, 2026 16:23

@alexey-milovidov alexey-milovidov left a comment

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.

The implementation looks good.

@alexey-milovidov alexey-milovidov self-assigned this Nov 8, 2026
Comment thread src/Interpreters/HashJoin/HashJoin.cpp Resolved
Comment thread src/Interpreters/Set.cpp Resolved
Comment thread src/Interpreters/Aggregator.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 3e899a319 with master cb694c085 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

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

25 object files changed (+56.22 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Columns/replaceNegativeZeros.cpp.o new 44.19 KiB +44.19 KiB

716 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

34 translation units recompiled, 252 s compile time in total, 33 of them have a recent master baseline.

Job report

alexey-milovidov and others added 7 commits November 11, 2026 13:35
… replicated columns

`ApproximateSetRuntimeFilter` hashed the raw bytes of the keys, so after the transition
from the exact set (whose elements are normalized) a probe-side `-0.` could be rejected
before the join, which matches it with `0.`. This is what made
`05245_spilling_join_float_keys_no_order_fallback` fail in CI. Hash both inserted and
probed values with negative zeros replaced.

`replaceNegativeZeros` now descends into `ColumnReplicated`, which `ARRAY JOIN` produces
for array-valued passenger columns and which is hashed in `ScatterByPartitionTransform`.

Also add `containsFloatingPointZero`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…loating point zero

The index stores the hashes of the original representation of the values, while `IN`
now matches `-0.` and `0.` as equal, so a granule with only `-0.` would be skipped for
`f IN (0., 1.)`. The index is still used when the set has no zero, and old parts stay correct.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…a prefix of the keys

`AggregatingInOrderTransform` passes its key columns to `Aggregator::executeOnBlockSmall`,
which bypassed the normalization in `Aggregator::executeOnBlock`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…rom normalized keys

The in-memory set hashes the keys with negative zeros replaced, so the `Hash128`
fingerprints of ordinary spill runs have to be computed the same way.

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

`hex(f)` is injective, but now that `-0.` and `0.` are the same key, replacing
`GROUP BY hex(f)` with `GROUP BY f` merges two groups. Likewise `toString(f)` is not
determined by the key `f`. Do not unwrap an injective function with floating point arguments
unless its result is floating point too, and do not treat expressions of floating point keys
as functions of the keys.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
….` as a separate key

`DistinctSetFilterExtraction.FloatBitPatternsSurviveExtraction` and
`ExternalDistinctTransformTest.SuppressionSortingKeepsSortEquivalentKeys` failed in CI:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=130054&sha=dd7448ce6cd78781c603f2e366ecdedf5e4ba343&name_0=PR&name_1=Unit%20tests%20%28amd_debug%29
They now check NaN payloads, which are still distinct keys.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Interpreters/HashJoin/HashJoin.cpp Resolved
Comment thread src/Interpreters/Aggregator.cpp Resolved
alexey-milovidov and others added 2 commits November 11, 2026 23:00
Treating `-0.` and `0.` as one key means that a value can come out as the
other zero (accepted for `JOIN` keys as well). With that, unwrapping
`GROUP BY hex(f)` to `GROUP BY f`, or dropping `toString(f)` next to `f`,
just merges the two zeros into one group, so the guards in
`OptimizeKeyExpressionsUtils` are not needed and are reverted to master.

The `bloom_filter` skip index guard now uses the existing `anyFieldSatisfies`
with `isFloatZeroField` over the set elements instead of a separate
column-walking `containsFloatingPointZero` helper.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Columns/replaceNegativeZeros.cpp Resolved
…ceNegativeZeros`

Instead of a branch per column type (`Nullable`, `Array`, `Map`, `Tuple`,
`Sparse`, `Const`, `Replicated`), the check recurses with `forEachSubcolumn`
and the replacement copies the column with `IColumn::mutate` and swaps the
affected subcolumns with `forEachMutableSubcolumn`. Only the float vectors
and `LowCardinality` stay special: `forEachSubcolumn` skips a shared
dictionary, and the dictionary cannot be modified in place (both zeros
would become duplicate values), so it is rebuilt as before.

This also covers `Variant`, and the typed and dynamic paths of `Dynamic`
and `JSON` (not the values serialized in their shared storage). So a `JSON`
key now matches `-0.` with `0.` like any other key, and the anti join in
`05210_join_runtime_filter_float_nan` no longer keeps that row; both runtime
filter arms still agree.

#130054 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Columns/replaceNegativeZeros.cpp Resolved
`Dynamic` keeps a value either in a typed variant or serialized in the shared variant, depending on
the order of inserts, and both layouts give the value the same key. Only the typed one could be
modified, so the same `-0.` got two keys, e.g. an extra group in `GROUP BY` over
`Dynamic(max_types = 1)`. `Dynamic`, also as a path of `JSON`, is left as before; typed paths of
`JSON` are still normalized.

#130054 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Interpreters/Set.cpp Resolved
Comment thread src/Interpreters/Set.cpp Resolved
alexey-milovidov and others added 2 commits November 13, 2026 02:09
… them

A `Set` matches a floating-point zero with the zero of the other sign, and with
values of other types that convert to it (the `String` `'-0'` against a `Float64`
set). Three optimizations converted or evaluated the set elements and lost that:

- the `bloom_filter` skip index checked for a zero only after converting the set to
  the index type, where a `Float64` zero is the `String` `'0'`;
- the key lookup of `EmbeddedRocksDB` / `KeeperMap` / `Redis` (`getFilterKeys`)
  looked up only the converted key `'0'`;
- `optimize_skip_unused_shards` (`analyzeSet`) evaluated a sign-sensitive sharding
  key on the normalized elements only.

Decline these optimizations when a set element holds a floating-point zero, checked
in the type of the set.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Interpreters/Aggregator.cpp Resolved
alexey-milovidov and others added 2 commits November 14, 2026 13:26
…ith signed zeros

- The tuple `IN` branch of the key extraction in `KVStorageUtils.cpp` (shared by
  `EmbeddedRocksDB`, `KeeperMap`, `Redis`) now declines the key lookup when an
  element of the set is a floating-point zero, checked before the conversion to
  the key type, as the single-column branch already does: a `String` key `'-0'`
  matches the zero, but the conversion yields only `'0'`.
- `StorageDistributed::isShardingKeySuitsQueryTreeNodeExpression` no longer
  elides the final `GROUP BY`, `DISTINCT` or `LIMIT BY` when the sharding key
  depends on a floating-point column: `-0.` and `0.` are now the same key, but
  a sharding key such as `cityHash64(f)` can send them to different shards.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/StorageDistributed.cpp Resolved
alexey-milovidov and others added 2 commits November 18, 2026 11:27
… partition key depends on a float

`-0.` and `0.` are the same key of `GROUP BY`, `DISTINCT` and `LIMIT BY`, but a partition expression such as
`bitShiftRight(reinterpretAsUInt64(f), 63)` puts them into different partitions. `isPartitionKeyFunctionOfKeys`
and `applyStreamDisjointness` now reject a table partition key that reads a column that can contain a float,
the same as the sharding-key check in `StorageDistributed`. Hash partitioning is unaffected, because
`ScatterByPartitionTransform` replaces negative zeros before hashing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 2 commits November 21, 2026 09:55
# Conflicts:
#	src/Interpreters/Set.cpp
…ing point zeros in `IN`

The test pinned that `[-0.] IN (SELECT [0.])` returns 0, because the set compared
floating point keys by their bits. This PR intentionally makes `-0.` and `0.` the same
key in `IN`, in agreement with `equals`, so the expected result is now 1, both with
`rewrite_in_to_join` disabled and enabled. NaN still matches itself.

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

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

stresshouse Bot commented Nov 21, 2026

Copy link
Copy Markdown

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 29 queries analysed

I found no performance change in this PR's benchmarks: the three slower ClickBench queries are not caused by its code. Q10 (+20.7%), Q30 (+25.5%) and Q31 (+17.7%) all run the aggregator path the PR changes, but their GROUP BY keys are String and integer columns, so the new negative-zero check finds no float data and returns after a few type checks per block without copying anything. All three PR medians fall inside master's current range, the baseline medians sit near the bottom of it, and these queries are noisy on master, so the deterministic decision to treat them as within normal variation is consistent with the diff. No tpch_adapted_1_official query was flagged, and none of the flagged queries has a float key, so this run does not measure the hash join, IN or DISTINCT changes.

clickbench

⚠️ 3 inconclusive

Flagged queries (3 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 10 not_sure 92 111 +20.7% <0.0001 aggregation: The GROUP BY key MobilePhoneModel is a String, so the new negative-zero check in the aggregator finds no float data and stops after a few type checks per block. That cost cannot explain +20.7%, and 111 ms is inside master's current range of 83-115 ms.
⚠️ 30 not_sure 157 197 +25.5% <0.0001 aggregation: The GROUP BY keys SearchEngineID and ClientIP are integers, so the new negative-zero check finds no float data and is close to free. 197 ms is inside master's current range of 154-199.5 ms, so the +25.5% looks like a baseline from a faster point in master's history.
⚠️ 31 not_sure 215 253 +17.7% <0.0001 aggregation: The GROUP BY keys WatchID and ClientIP are integers, so the new negative-zero check in the aggregator does no per-row work. 253 ms is inside master's current range of 202-258 ms, and this query's history on master is noisy.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 26263335-a1e6-4258-a0df-fd90178506f7
  • MIRAI run: dcfa1db5-a31c-425c-b9f1-23ef6e376439
  • PR check IDs:
    • clickbench_643635_1795260650
    • clickbench_643641_1795260650
    • tpch_adapted_1_official_643648_1795260650
    • tpch_adapted_1_official_643663_1795260650

alexey-milovidov and others added 2 commits November 24, 2026 09:07
# Conflicts:
#	src/Processors/QueryPlan/RuntimeFilterLookup.cpp
… zeros in `GROUP BY`

The query `SELECT n, ... FROM remote(...) GROUP BY n WITH ROLLUP ORDER BY n, 2` over the
values `0.0` and `-0.0` returned three rows: two groups and the rollup total. With this
change `-0.` and `0.` are the same `GROUP BY` key, so there is one group and the total.
The test checks that the query works on a remote server, not the number of groups.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=130054&sha=897427970ef026ecf1debf7cd3c1737dec222c7c&name_0=PR&name_1=Fast%20test
PR: #130054

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

This branch has not been deployed

No deployments
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

Development

Successfully merging this pull request may close these issues.

1 participant