Repository navigation
Replace negative zeros in hash keys only when they are present - #130054
alexey-milovidov wants to merge 28 commits into
Conversation
`-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]>
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]>
|
Workflow [PR], commit [3e899a3] Summary: ✅
AI ReviewSummaryThe PR makes signed zeros equal in hash keys for Findings❌ Blockers
Final VerdictStatus: ❌ 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. |
alexey-milovidov
left a comment
There was a problem hiding this comment.
The implementation looks good.
`04234_non_constant_rhs_in`, `04811_constant_lambda_rhs_in` and `05293_external_set` expected a constant `Set` to distinguish `-0.` from `0.`. This PR intentionally makes them the same key, so the constant and row-wise `IN` paths now agree. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=130054&sha=latest&name_0=PR&name_1=Fast%20test PR: #130054 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes25 object files changed (+56.22 KiB total), 1 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units34 translation units recompiled, 252 s compile time in total, 33 of them have a recent master baseline. |
… 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]>
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]>
The key column holds both zeros, which now match each other in the join, so the `f_s` case returns more rows. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=130054&sha=51869851a459fd4f6604f6dcf634d0fae8408e48&name_0=PR PR: #130054 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…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]>
`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]>
… 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]>
…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]>
… 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]>
# 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]>
|
📊 Cloud Performance Report ✅ AI verdict: 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. clickbenchFlagged queries (3 of 43)
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
|
# 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]>
Related: #115970
Related: #126433
A less intrusive alternative to #115970, for comparison.
-0.is equal to0., but hash tables compare floating point keys bitwise, soIN,GROUP BY,DISTINCT,LIMIT BYand hashJOINtreated them as different keys and disagreed withequalsand 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, becauseatan(false) / c2is-0.for a negativec2.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, forFloat32,Float64,BFloat16, also insideNullable,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;JOIN: build and probe; the bucket scatter of grace hash join;ScatterByPartitionTransform;AggregatingInOrderTransform);DISTINCTruns;Several places relied on the keys being compared bitwise, and are adjusted to stay consistent:
KeyConditiondoes not use a set pushed through a key transform that tells the zeros apart (e.g.ORDER BY toString(a)witha IN ([0.0])), as it already does for=; otherwise the index prunes rows that the predicate matches.optimize_inverse_dictionary_lookupis not applied to floating point keys: a dictionary lookup still tells the zeros apart.bloom_filterskip index is not used for anINset that contains a floating point zero, because the index stores the hashes of the original representation.optimize_injective_functions_in_group_by/..._in_limit_bydo not unwrap an injective function of a floating point argument with a non-floating point result (e.g.hex(f)), andoptimize_group_by_function_keys/optimize_limit_by_function_keysdo not drop expressions of a floating point key (e.g.toString(f)inGROUP BY f, toString(f)), because such expressions tell the zeros apart.Not covered:
uniqExactand other aggregate functions with their own hash sets, dictionaries, the hashes insideDynamic/JSONvalues, the merging of partially aggregated blocks from another server.NaNis 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):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
-0.and0.are now the same key inIN,GROUP BY,DISTINCT,LIMIT BYand hashJOIN, in agreement withequals. Previously, e.g.materialize(-0.) IN (0.)returned 0.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/130054]