Repository navigation
Conversation
Per IEEE 754 / SQL JOIN ON semantics, NaN never compares equal to NaN, but ClickHouse's hash table compared float keys bitwise via bitEquals (memcmp). Two NaN values with matching bit patterns therefore wrongly joined - INNER JOIN ON NaN = NaN returned rows instead of zero, and ANTI JOIN dropped the NaN-keyed left row instead of keeping it. Fold NaN rows into the JOIN-key null map so they are skipped on both build and probe sides, mirroring how NULL keys behave. Done at three layers: * HashJoin / ConcurrentHashJoin: extend the build- and probe-side null_map after extractNestedColumnsAndNullMap via a new helper JoinCommon::extendJoinKeyNullMapWithFloatNaNs. * FullSortingMergeJoin: in FullMergeJoinCursor::setChunk, OR NaN positions into the per-key null_map so nullableCompareAt short-circuits. * BuildRuntimeFilterTransform: drop NaN rows before they enter the bloom/exact runtime filter, so the runtime filter never carries a NaN entry that would mis-prune a probe-side NaN. GROUP BY / DISTINCT / uniq / IN keep their existing NaN-coalescing behaviour - this changes only the JOIN ON path. Closes: ClickHouse#106531
Pre-PR validation gate
Session id: cron:clickhouse-ci-task-worker:20260605-091500 |
|
cc @KochetovNicolai @vdimir — could you review this? It fixes wrong results for INNER/LEFT/RIGHT/FULL/SEMI/ANTI JOIN ON with float keys: the hash table compared NaN keys bitwise via |
| DROP TABLE IF EXISTS l; | ||
| DROP TABLE IF EXISTS r; | ||
|
|
||
| CREATE TABLE l (k Float64, v String) ENGINE = Memory(); |
There was a problem hiding this comment.
@groeneai can you add test examples with BFloat16 as well?
There was a problem hiding this comment.
Added in d51a467.
The fix already dispatched on BFloat16 in all three NaN-detection paths (extendJoinKeyNullMapWithFloatNaNs in JoinUtils.cpp, foldFloatNaNsIntoNullMap in MergeJoinTransform.cpp, filterOutNaNs in BuildRuntimeFilterTransform.cpp); the new test block exercises that dispatch end-to-end. New cases mirror the Float32 grid: hash INNER/LEFT/ANTI and full_sorting_merge INNER over BFloat16 keys with nan / -nan mixed with a finite value.
Local verification (build-asan, --no-random-settings --test-runs 30): 30/30 pass.
Session: cron:clickhouse-ci-task-worker:20260605-144800
Per @PedroTadim review on PR ClickHouse#106540: cover BFloat16 in addition to Float32 / Float64 / Nullable(Float64). The fix already dispatches on BFloat16 in all three NaN-detection paths (extendJoinKeyNullMapWithFloatNaNs, foldFloatNaNsIntoNullMap, filterOutNaNs); this commit just exercises that dispatch end-to-end. The new block covers BFloat16 keys for hash INNER / LEFT / ANTI and full_sorting_merge INNER, mirroring the Float32 grid.
Pre-PR validation gate
Session id: cron:clickhouse-ci-task-worker:20260605-144800 |
|
Workflow [PR], commit [deba70c] Summary: ✅
AI ReviewSummaryThis PR changes float-key PR Metadata
Findings💡 Nits
Final VerdictStatus: Minimum required action: update the PR description and changelog entry to match the current |
CI Ledger — covered HEAD: `d51a4676af70`Pulled the failure set after CI fully completed (last check 20:44:02Z, >20min CIDB ingestion buffer met).
`Mergeable Check` reports failed because of the perf job. `Finish Workflow` SUCCESS. All 100+ stateless / integration / stress / fuzzer / unit-test jobs pass on this HEAD. Separately, the AI Review on this run flagged a Major in `BuildRuntimeFilterTransform.cpp:157` — `filterOutNaNs` only handles top-level `ColumnVector(Float)` and would miss `Nullable(Float)` / `LowCardinality(Nullable(Float))` / `Tuple` runtime-filter keys, leaving an `ANTI JOIN` mis-prune window. This is review-feedback rather than a CI test failure; it will be addressed in a fix-up commit. Session: cron:our-pr-ci-monitor:20260605-210000 |
The previous helper only recognised a top-level `ColumnFloat32`/`ColumnFloat64`/ `ColumnVector<BFloat16>`. Runtime filters can be built over `Nullable(Float*)`, `LowCardinality(Nullable(Float*))`, or - for multi-key `LEFT ANTI` - a temporary `Tuple` of common types, so a probe-side `NaN` was still pre-pruned by `ExactNotContainsRuntimeFilter` before the join saw the row. Recursively traverse those wrappers and OR-mark every row whose float payload is `NaN`, then filter the original (still-wrapped) column once. Already-NULL rows do not need to be dropped: the runtime filter stores `NULL` natively (`argument_can_have_nulls`), so there is no bitwise match for them on the probe side. `isNaN` is templated and works on `Float32`, `Float64` and `BFloat16`, so the fix covers all three element types under any of the three wrappers. Test additions in `04318_106531_join_on_nan_keys.sql` cover, with `enable_join_runtime_filters = 1` and `join_algorithm = 'hash'`: * `Nullable(Float64)` `ANTI`/`INNER` * `LowCardinality(Nullable(Float64))` `ANTI` * `Tuple(Float64, Float64)` `LEFT ANTI` (multi-key path)
Pre-PR validation gate (commit 1b3d5dc)
Session id: cron:clickhouse-ci-task-worker:20260605-235700 |
CI Ledger — covered HEAD:
|
| job | classification | disposition |
|---|---|---|
Build (arm_tidy) — cppcoreguidelines-init-variables on src/Storages/ObjectStorage/DataLakes/Iceberg/Mutations.cpp:731,733 (last_version, compression_method) |
trunk regression, NOT caused by this PR | Introduced by master commit 9c9b2b9a0da7 (merge of #106102, "catalogs with schema evolutions + concurrent checks", merged 2026-06-05T17:43:31Z). Hit on master and 21+ unrelated concurrent PRs in the 18:04Z–21:25Z window. Trivial 2-line init fix already filed by us as #106615 (APPROVED by @ alexey-milovidov 23:35Z, awaiting CI). 155 downstream jobs are SKIPPED because they depend on arm_tidy. Not actionable on this PR's branch. |
posted-comment:
All other checks for HEAD 1b3d5dc0bf15 passed or skipped-due-to-arm_tidy. The ledger covers the full set; nothing on this PR's diff is failing.
`extendJoinKeyNullMapWithFloatNaNs` (HashJoin / ConcurrentHashJoin path) and `foldFloatNaNsIntoNullMap` (full_sorting_merge path) only dispatched on top-level `ColumnFloat32` / `ColumnFloat64` / `ColumnVector<BFloat16>`. A `ColumnTuple` key fell through, so `tuple(NaN) = tuple(NaN)` (whether planner-generated or written explicitly as `ON tuple(l.k) = tuple(r.k)`) still produced a wrong match because the hash table or merge cursor compared the tuple payload bitwise. Mirror the recursion landed at 1b3d5dc in `BuildRuntimeFilterTransform::filterOutNaNs`: unwrap `Nullable` (respect existing null map for the element-Nullable case), unwrap `LowCardinality` via `convertToFullColumnIfLowCardinality`, and recurse into `ColumnTuple` (a row is dropped if ANY float element is `NaN`, matching scalar tuple equality semantics: `(a, b) = (c, d)` iff `a = c AND b = d`, with `NaN != NaN`). `extendJoinKeyNullMapWithFloatNaNs` first runs a type-only walk (`containsFloatPayload`) so a fresh null map is still allocated lazily; purely integer/string/date keys keep the previous fast path. Tuple-keyed `JOIN ON` test cases added to `04318_106531_join_on_nan_keys.sql` for `hash` and `full_sorting_merge`, covering plain `tuple(Float64)`, multi-element `tuple(Float64, Float64)` where only one element is `NaN`, `tuple(Nullable(Float64))` (preserves NULL-safe tuple equality), and `tuple(LowCardinality(Nullable(Float64)))`. Demonstrated both directions on a debug build: pre-fix (HEAD~) the tuple-keyed `INNER JOIN` returns the matched row plus the wrongly-joined NaN rows; post-fix it returns only the matched row. ANTI returns the NaN-keyed rows after the fix. Closes: ClickHouse#106531
Pre-PR validation gateFollowing commit a08706c (
Session id: cron:clickhouse-ci-task-worker:20260606-043300 |
The HashJoin / FullSortingMergeJoin / BuildRuntimeFilter NaN-as-null treatment did not extend to `SET join_algorithm = 'direct'`. The MergeTree direct path builds the right-side lookup with `IN` (which intentionally keeps coalescing NaN per this PR's design) and then maps found rows back to probe keys via `ColumnsHashing::HashMethodHashed`, which compares the key payload bitwise. Two `NaN` keys with identical bit patterns therefore matched for `INNER` / `LEFT SEMI` and were suppressed for `LEFT ANTI`. Force every probe row whose key holds a `NaN` to the not-found path (sentinel selector + `null_map = false`) inside `getByKeys`, mirroring `JoinCommon::extendJoinKeyNullMapWithFloatNaNs`. The recursion walks `Nullable` / `LowCardinality` / `Tuple` so the same shapes covered on the hash path work here too. `joinKeyContainsFloatPayload` and `markFloatNaNRowsAsNull` are exposed in `JoinCommon` so the helper is shared with the hash and merge paths. New tests in `04318_106531_join_on_nan_keys.sql` cover `SET join_algorithm = 'direct'` over MergeTree-keyed `Float64` and `Nullable(Float64)` for `INNER` / `LEFT` / `LEFT SEMI` / `LEFT ANTI`. Address-requested in clickhouse-gh[bot] inline review on commit a08706c (PR ClickHouse#106540) at 2026-06-06T05:03:46Z. Closes: ClickHouse#106531
Pre-PR validation gate
Session id: cron:clickhouse-ci-task-worker:20260606-065700 |
…umnConst Addresses 5 follow-up review items on PR ClickHouse#106540 (issue ClickHouse#106531): 1. arm_tidy parameter-name mismatch: align JoinUtils.h declaration with .cpp definition (mutable_null_map). Fixes the readability-inconsistent-declaration-parameter-name warning that broke the arm_tidy build on commit c183aff. 2. ColumnNullable branch must respect the outer null map. A ColumnNullable may carry arbitrary trash bytes in its nested column for rows where the null map says NULL. If those bytes happen to be a NaN bit pattern, the previous markFloatNaNRowsAsNull marked the whole row in the join null map and broke null-safe tuple equality (tuple(NULL) = tuple(NULL) wrongly became a non-match). The recursion now threads is_null down so an already-NULL row is left alone. 3. MergeJoinTransform foldFloatNaNsIntoNullMap and BuildRuntimeFilterTransform filterOutNaNs gain a type-only joinKeyContainsFloatPayload guard. Most full-sorting-merge and runtime-filter keys are integer/string/date and never carry a NaN, so we now skip the per-chunk ColumnUInt8/Filter allocation in those cases. 4. Defence-in-depth ColumnConst handling in joinKeyContainsFloatPayload and markFloatNaNRowsAsNull (and the parallel helpers in MergeJoinTransform and BuildRuntimeFilterTransform). Direct joins pass the original probe key column without convertToFullColumnIfConst, so a constant NaN can reach this helper as ColumnConst(ColumnFloat*(NaN), N). Marking all rows when the underlying scalar is NaN keeps the constant-probe semantics aligned with the materialised path. Test: 04318_106531_join_on_nan_keys gains a Tuple(Nullable(Float64)) null-safe-match case where NULL slots carry a NaN trash payload. Pre-fix this returned 0 (BUG); post-fix it returns 1.
Pre-PR validation gate (commit 25b677f)
Session id: cron:clickhouse-ci-task-worker:20260606-084500 |
Address three follow-up CRs from clickhouse-gh[bot] on commit 25b677f (PR ClickHouse#106540, NaN-as-null treatment for JOIN ON): CR 1 — `ColumnSparse` was not unwrapped in `joinKeyContainsFloatPayload` / `markFloatNaNRowsAsNullImpl` (`JoinUtils.cpp`), `markNaNRows` (`MergeJoinTransform.cpp`), and `markNaNRowsImpl` (`BuildRuntimeFilterTransform.cpp`). HashJoin and full_sorting_merge materialise sparse columns upstream, but direct joins and runtime-filter builds can see them raw. Added a `column.isSparse()` branch in each helper that calls `convertToFullColumnIfSparse` and recurses on the dense form. CR 2 — The `ColumnConst` branch in `markFloatNaNRowsAsNullImpl` recursed into the one-row data column while keeping the full-size `mutable_null_map`, so the leaf branch's `chassert(data.size() == mutable_null_map.size())` would trip in debug/ASan builds. Rewrote the branch to evaluate the scalar into a one-row `scalar_mask`, then spread the mark across all rows not excluded by `is_null`. Mirrors the pattern already used in `BuildRuntimeFilterTransform.cpp::markNaNRowsImpl`. Same fix applied to `MergeJoinTransform.cpp::markNaNRows`. CR 3 — Re-confirms CR 2 on the `HashJoin.cpp:792` thread; addressed by the same JoinUtils.cpp rewrite. Test additions to `tests/queries/0_stateless/04318_106531_join_on_nan_keys`: - Constant `NaN` probe key (hash) covering the rewritten ColumnConst branch via the helper's contract. - Build-side sparse `Float64` key with runtime filter enabled, exercising the new `ColumnSparse` unwrap in `markNaNRowsImpl`. Local verification (debug build, x86-64-v2): 30/30 passes via `clickhouse local --queries-file` on the test file, sibling `03214_join_on_tuple_comparison_elimination_bug` continues to pass.
Pre-PR validation gate
Session id: cron:clickhouse-ci-task-worker:20260606-102600 |
|
@vdimir re your question "can we check how nan handling is implemented in other places (aggregation or wherever we do comparisons)?" - I audited the other equality/comparison contexts. Short answer: every other place uses bitwise (
The bitwise behavior in the hash table is load-bearing, not accidental: the comment at Why leaving the others unchanged is correct:
The existing test already pins this ( On your other comments: I will address the |
Address @vdimir review feedback on PR ClickHouse#106540 (the JOIN ON NaN-keys fix for issue ClickHouse#106531). The previous version carried three near-identical ~80-line recursive NaN-detection cascades (in JoinUtils.cpp, BuildRuntimeFilterTransform.cpp and MergeJoinTransform.cpp), each re-implementing the same Nullable/LowCardinality/Tuple/ColumnConst/ ColumnSparse unwrap plus a per-float-type leaf loop. Replace them with a single per-column primitive: ColumnVector<T>::getNanMask, which OR-marks NaN rows for floating-point T (no-op otherwise). The shared JoinCommon recursion (markFloatNaNRowsAsNull / joinKeyContainsFloatPayload) keeps the wrapper unwrap in one place and calls getNanMask at the leaf; the two transforms now reuse that shared recursion instead of private copies. Behaviour is unchanged: NaN keys are still treated as never-matching for JOIN ON, while null-safe tuple equality (tuple(NULL) = tuple(NULL)) is preserved because the Nullable branch skips already-NULL rows. Net -250 lines across the four join code paths. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gateThis push (
Session id: cron:clickhouse-worker-slot-8:20260610-230810 |
…erMap) The generic direct (key-value) JOIN path did not honour IEEE 754 / SQL JOIN ON NaN != NaN for IKeyValueEntity backends. DirectKeyValueJoin::joinBlock forwarded the probe key to storage->getByKeys; StorageEmbeddedRocksDB (and Redis / KeeperMap) serialize the key Field bitwise, so a probe NaN matched a build-side NaN with the same bit pattern. Only DirectJoinMergeTreeEntity masked NaN internally, so the direct algorithm overlisted NaN-safety in the join_algorithm docs for the generic backends. Fix: fold NaN probe rows to the not-found path inside DirectKeyValueJoin::joinBlock, gated on offsets.empty() so only the generic backends (which return a 1:1 result with empty offsets) are touched; DirectJoinMergeTreeEntity already masks NaN and returns non-empty offsets, so it is left unchanged. Reuses the shared JoinCommon::markFloatNaNRowsAsNull recursion (Nullable / LowCardinality / Tuple), so the masking matches the hash / full_sorting_merge paths exactly. NaN rows are remapped to a default sentinel and null_map=false, mirroring how the MergeTree entity handles its own NaN rows, which yields the correct shape for INNER (drop), LEFT (default / NULL), LEFT SEMI (drop), and LEFT ANTI (keep). Adds 04318_106531_join_on_nan_keys_rocksdb_direct (tagged no-fasttest, use-rocksdb) covering all four join kinds plus join_use_nulls, Float32 keys, non-NaN regression, and a String key literally equal to 'nan' (must still match). Split from the parent 04318 test because EmbeddedRocksDB is not in the fast-test build. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (commit
|
| # | Question | Answer |
|---|---|---|
| a | Deterministic repro? | Yes. CREATE TABLE rdb (k Float64, v String) ENGINE = EmbeddedRocksDB PRIMARY KEY k; INSERT VALUES (1.0,'one'),(nan,'rocks_nan'),(2.0,'two'); then SELECT l.x, r.v FROM (SELECT arrayJoin([1.0, nan, 2.0]) AS x) l INNER JOIN rdb r ON l.x = r.k SETTINGS join_algorithm='direct' returns nan -> rocks_nan every time on 6243982. EXPLAIN confirms FilledJoin (the direct path), not a fallback. |
| b | Root cause explained? | DirectKeyValueJoin::joinBlock (DirectJoin.cpp:159) forwards the raw probe key to storage->getByKeys. For generic IKeyValueEntity backends, StorageEmbeddedRocksDB::getByKeys serializes the probe Field bitwise (StorageEmbeddedRocksDB.cpp:940-947), so a probe NaN matches a build-side NaN with the same bit pattern. Only DirectJoinMergeTreeEntity::getByKeys masked NaN internally, so the generic path stayed unmasked. |
| c | Fix matches root cause? | Yes. Masks NaN probe rows at the consumer (DirectKeyValueJoin::joinBlock), gated on offsets.empty() so only the generic backends (which return a 1:1 result with empty offsets) are touched; DirectJoinMergeTreeEntity (non-empty offsets) is left unchanged. Reuses the shared JoinCommon::markFloatNaNRowsAsNull recursion introduced in 6243982, so masking matches the hash / full_sorting_merge paths. |
| d | Test intent preserved / new tests added? | New test 04318_106531_join_on_nan_keys_rocksdb_direct (no-fasttest, use-rocksdb): all four direct join kinds (INNER drop, LEFT default, LEFT SEMI drop, LEFT ANTI keep) + join_use_nulls (NaN -> NULL) + Float32 keys + non-NaN regression + a String key literally 'nan' that must still match. Split from the parent 04318 because RocksDB is not in the fast-test build; parent 04318 stays dependency-free and still passes. |
| e | Both directions demonstrated? | Yes. Without the fix (6243982): INNER and LEFT both return nan -> rocks_nan. With the fix (deba70cd): INNER drops NaN, LEFT yields nan -> '' (or NULL with join_use_nulls), SEMI drops, ANTI keeps. Matches the already-fixed hash reference exactly. New test 30/30 deterministic passes; parent 04318 still passes. |
| f | Fix is general, not a narrow patch? | Yes. The fix lives in DirectKeyValueJoin::joinBlock, the single consumer of getByKeys, so it covers ALL generic IKeyValueEntity backends (EmbeddedRocksDB, Redis, KeeperMap), not just RocksDB. The offsets.empty() gate is the structural discriminator between self-masking (MergeTree) and non-masking backends, not a RocksDB-specific check. Not a defensive symptom guard: the masking is the same canonicalization the other algorithms apply, applied at the point the unmasked key enters the lookup. |
Session id: cron:clickhouse-worker-slot-15:20260611-004100
| When using the `partial_merge` algorithm, ClickHouse sorts the data and dumps it to the disk. The `partial_merge` algorithm in ClickHouse differs slightly from the classic realization. First, ClickHouse sorts the right table by joining keys in blocks and creates a min-max index for sorted blocks. Then it sorts parts of the left table by the `join key` and joins them over the right table. The min-max index is also used to skip unneeded right table blocks. | ||
|
|
||
| :::note Float keys | ||
| Float `JOIN ON` keys are compared bitwise by `partial_merge`, so two `NaN` rows with identical bit patterns spuriously match. The other algorithms (`hash`, `parallel_hash`, `grace_hash`, `full_sorting_merge`, `direct`) treat `NaN` as never equal, matching IEEE 754 semantics. Use one of those algorithms when `NaN`-safety matters. |
There was a problem hiding this comment.
The code now documents and tests partial_merge as the legacy exception that still bitwise-matches same-pattern NaN keys, but the PR description and changelog entry still say partial_merge now rejects float JOIN ON keys with NOT_IMPLEMENTED and that users must migrate. That release note is now wrong for the current code: users will expect an exception/migration, while partial_merge still returns same-bit NaN matches.
Please update the PR description and changelog entry to say that partial_merge keeps its legacy bitwise behavior and is the documented exception; only hash, parallel_hash, grace_hash, full_sorting_merge, and direct treat NaN as never equal.
There was a problem hiding this comment.
Fixed the PR description and changelog entry to match the code.
After the 4cb2d05 revert (per the backward-compat request on MergeJoin.cpp), partial_merge no longer rejects float keys with NOT_IMPLEMENTED. It keeps its legacy behavior: float JOIN ON keys are compared bitwise, so two NaN rows with identical bit patterns still match. The description and changelog now state exactly that and point users at the NaN-safe algorithms (hash, parallel_hash, grace_hash, full_sorting_merge, direct). This matches the :::note Float keys block already in this join_algorithm doc.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered by tests: 167/190 (87.89%) | Lost baseline coverage: none · Uncovered code |
| auto & selector_data = selector->getData(); | ||
| selector_data.resize(num_rows); | ||
| for (size_t i = 0; i < num_rows; ++i) | ||
| { | ||
| if (nan_mask[i]) | ||
| { | ||
| selector_data[i] = num_rows; | ||
| null_map[i] = 0; | ||
| } | ||
| else | ||
| selector_data[i] = i; | ||
| } | ||
| MutableColumns chunk_columns = joined_chunk.mutateColumns(); | ||
| for (auto & col : chunk_columns) | ||
| { | ||
| col->insertDefault(); | ||
| col = IColumn::mutate(col->index(*selector, 0)); |
There was a problem hiding this comment.
Why to use selector rather then just IColumn::filter ?
There was a problem hiding this comment.
IColumn::filter can only delete rows, but a NaN probe key must not be deleted for every kind: regular LEFT keeps the left row with a default/NULL right side, and LEFT ANTI keeps the row entirely. The generic backend returns a 1:1 result (one right row per probe row) plus a null_map; setting null_map[i]=0 alone handles INNER/SEMI/ANTI (they filter on null_map at the end), but for regular LEFT the row is kept and would still show the stale bitwise-matched right value. So I remap NaN rows to an appended default sentinel via index() and set null_map[i]=0, which routes them through the exact same not-found path the code already produces for a genuinely missing key.
This mirrors DirectJoinMergeTreeEntity::getByKeys, which uses the same selector-to-sentinel pattern for its own not-found rows. Verified against EmbeddedRocksDB (Float64 PK with NaN): all four kinds match the hash reference (INNER -> drop, LEFT -> default right, SEMI -> drop, ANTI -> keep). A plain filter would give the wrong shape for LEFT and ANTI.
That said, I agree the block is a bit heavy. If you prefer, I can drop the index() selector and instead blank only the right columns for NaN rows in place (the chunk is already 1:1 here, so no reindex is needed), keeping null_map[i]=0 to drive the filtering. Happy to switch to whichever you find cleaner.
| /// `Tuple` like `JoinCommon::extendJoinKeyNullMapWithFloatNaNs` does on the hash path. | ||
| PaddedPODArray<UInt8> nan_mask; | ||
| bool any_nan = false; | ||
| if (JoinCommon::joinKeyContainsFloatPayload(*keys[0].column)) |
There was a problem hiding this comment.
Won't it work automatically with direct join with MT, since we build plan with IN which should handle nans proerly?
There was a problem hiding this comment.
I checked this empirically and the IN plan does not make the masking redundant, because IN coalesces NaN (the opposite of JOIN ON):
nan IN (nan) -> 1 (true)
So buildFilterStepWithIn keeps the right-side NaN row rather than excluding it. The IN step is only a coarse candidate pre-filter to fetch matching right rows; the actual key matching happens afterwards in the ColumnsHashing findKey loop, which compares the key payload bitwise, so a probe NaN then matches the retained right NaN.
Confirmed by disabling just the mask and rebuilding: MT direct INNER JOIN ON l.k = r.k with NaN on both sides returns the NaN row (wrong) without the mask, and drops it (correct, matching hash) with it. So the DirectJoinMergeTreeEntity mask is load-bearing, not redundant.
There was a problem hiding this comment.
If IN works that way, maybe we can keep the whole thing as is? It seems like a major change that addresses the issue only partly without a systematic fix, so different parts of clickhouse would behave inconsistently. Maybe we should just keep it as unexpected but well-known behavior?
There was a problem hiding this comment.
Agree that a systematic fix is out of reach here: IN, GROUP BY, DISTINCT and partial_merge match NaN bitwise and would stay that way. The counterweight is that JOIN currently disagrees with the = operator itself: FROM t1, t2 WHERE t1.k = t2.k is rewritten to INNER JOIN and returns rows where the predicate evaluates to 0. That predicate-vs-result mismatch is what fuzzers keep hitting (#106531 is its De Morgan variant). Postgres and Spark resolved it the other way (NaN equals NaN everywhere, scalar comparison included); changing scalar = is beyond this PR.
Merging current master into the branch (done locally, not pushed) surfaced three facts that rule out the current shape regardless of the semantics call:
- The null-map fold now breaks on tuple keys. The run detection from Speed up
DISTINCTin order, sort-merge joins,LIMIT BYand negativeLIMIT BY#106502 assumes rows that compare equal are contiguous in the sorted range; the fold marks NaN tuple rows NULL while they keep their raw sort positions. Debug and sanitizer builds abort with LOGICAL_ERROR "Equal values are not contiguous within the range assumed to be sorted"; release builds skip the check and can compute wrong runs:
CREATE TABLE lt (k1 Float64, k2 Float64, v String) ENGINE = Memory;
CREATE TABLE rt (k1 Float64, k2 Float64) ENGINE = Memory;
INSERT INTO lt VALUES (1.5, 2.5, 'm'), (nan, 2.5, 'a'), (3.5, nan, 'b'), (4.5, 5.5, 'c');
INSERT INTO rt VALUES (1.5, 2.5), (nan, 2.5), (3.5, nan);
SET join_algorithm = 'full_sorting_merge';
SELECT v FROM lt INNER JOIN rt ON tuple(lt.k1, lt.k2) = tuple(rt.k1, rt.k2);Top-level float keys are unaffected: the sort routes NaN and NULL to the same end, so the folded null block stays contiguous. Only the tuple recursion breaks the invariant.
-
joinGetagainstENGINE = Joinshares the masked build and probe paths, so a stored NaN key becomes unreachable. A dictionary-style lookup should not get JOIN ON semantics. -
VariantandDynamicfloat alternatives are not covered by the type walk, so they keep bitwise matching anyway.
Options:
a. Scope the fold to top-level float keys (Nullable and LowCardinality wrappers included). Plain ON l.k = r.k and multi-key AND clauses arrive as separate top-level columns, which is exactly the reported class. Explicit tuple(...) keys and the null-safe <=> wrap keep bitwise behavior, so tuple NaN stays consistent with tuple(NULL) = tuple(NULL) as you suggested on the JoinUtils thread. No interaction with the run-detection invariant, joinGet untouched, Variant/Dynamic documented as bitwise together with partial_merge and tuples. Noticeably smaller diff than the current branch.
b. Keep full wrapper coverage and rework full_sorting_merge so the physical order matches the effective null map. Consistent for tuples, but invasive into the sort layer and works against #106502.
c. Keep current behavior: close this PR and document bitwise NaN matching as known behavior (I would post the analysis on #106531 and send the join_algorithm docs note as a small separate PR).
I prefer (a). If you prefer (c) I will close this PR. WDYT?
| return markFloatNaNRowsAsNullImpl(*full, mutable_null_map, is_null); | ||
| } | ||
|
|
||
| if (const auto * tuple = typeid_cast<const ColumnTuple *>(&column)) |
There was a problem hiding this comment.
For NULL we treat tuple(NULL) == tuple(NULL), for backward compatibility perhaps for nans it could be consistent with nulls
There was a problem hiding this comment.
Good question, and it is worth settling explicitly. The reason I treat tuple-nested NaN differently from tuple-nested NULL is that the two are not actually consistent in ClickHouse's own comparison semantics:
nan = nan -> 0 (false)
nan IS NOT DISTINCT FROM nan -> 0 (false) <-- NaN is distinct from itself
NULL IS NOT DISTINCT FROM NULL -> 1 (true)
tuple(nan) = tuple(nan) -> 0 (false)
tuple(NULL) = tuple(NULL) -> NULL (not true)
The null-safe tuple wrap in PlannerJoins.cpp exists specifically so tuple(NULL) matches tuple(NULL), i.e. it implements a IS NOT DISTINCT FROM b. But that very operator says nan IS NOT DISTINCT FROM nan is false, so making tuple-nested NaN match would make the JOIN disagree with the scalar <=> it is supposed to implement. Concretely, on Nullable(Float64):
SELECT v FROM la INNER JOIN ra ON la.k <=> ra.k -- la=(1.5,'m'),(nan,'nan-l'),(NULL,'null-l')
master: m, nan-l, null-l (nan-l wrongly matches)
this PR: m, null-l (NULL still matches null-safe; NaN dropped, matching nan<=>nan=false)
So the current behavior keeps NULL matching (compat preserved) while making NaN consistent with both scalar = and <=>. If you would still prefer tuple-nested NaN to match for strict backward compatibility with pre-PR partial_merge-style bitwise behavior, I can scope the fold to top-level float keys only (plain ON a = b and multi-key AND, which arrive as separate top-level columns, not as a ColumnTuple), leaving explicit/<=>-wrapped tuple keys untouched. That is a smaller change and also drops the tuple recursion. Let me know which semantics you want and I will adjust.
|
@vdimir can you give a final look? |
|
Dear @vdimir, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself. |
…rge NaN semantics Make the NaN case composite (NaN first key on both sides, mismatching second key) so compareTrackAt actually compares NaN vs NaN, while the join still yields no NaN match. Correct the comment: partial_merge compares float keys bitwise, and PR ClickHouse#106540 leaves that unchanged, so the test is independent of the hash / full_sorting_merge NaN!=NaN equi-join fix. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
@groeneai fix the merge conflict |
vdimir
left a comment
There was a problem hiding this comment.
Actually I'm not sure we need to merge this PR. This behavior has existed for quite a while, so it might be considered unexpected behavior or a known pitfall. Given that and the size of the patch, maybe we should just document it and keep it unchanged for now.
Also, as mentioned in comment, we have the same behavior in other parts (IN/GROUP BY), so it won't be a systematic fix.
|
I agree @groeneai can you create a PR adding this behavior to the docs? I can review it |
|
Agreed, I will not pursue the behaviour change. I re-measured your IN/GROUP BY point on master (26.8.1.1) before agreeing, and it holds
So one query shape yields 1 for the predicate and 2 rows for the join. That is a Two measurements that keep the docs change small and precise:
On the merge conflict: the textual conflict was trivial and I had it resolved locally, @PedroTadim yes, I will open the docs-only PR and request your review. It extends |
|
@PedroTadim the docs PR is open: #112409 Two deviations from what I described above, both because measuring the claims while writing the text
Also: The |
@ PedroTadim asked to remove the changes to src/DataTypes/DataTypesNumber.cpp and to tests/queries/0_stateless/04546_partial_merge_join_float_nan.sql, so the PR requested on ClickHouse#106540 stays docs-only. Both files are reverted to their master content; the join.mdx paragraph is unchanged. The Float page therefore keeps stating the byte-wise key-identity rule as a blanket fact and naming equi-JOIN among the operations it covers, which is true of the hash joins only. That is left as it is on master pending his answer on how he wants that page handled.
The NULL section of the JOIN docs does not cover NaN. A scalar NaN = NaN is 0, but an equality JOIN key is compared by key identity, so NaN keys can match each other depending on their bit patterns and on the join implementation, and isNotDistinctFrom does not reliably separate them. Document the two workarounds and scope each one. On a key that is not Nullable, if(isNaN(A.id), NULL, A.id) = B.id excludes NaN. On a Nullable(Float) key that form also stops NULL keys from matching each other, because isNaN(NULL) is NULL, so a reader arriving from the isNotDistinctFrom section would silently lose those matches; the null-preserving form is documented alongside it, together with the join algorithm restriction its extra condition carries. Related: ClickHouse#106540 Related: ClickHouse#106531
…rge NaN semantics Make the NaN case composite (NaN first key on both sides, mismatching second key) so compareTrackAt actually compares NaN vs NaN, while the join still yields no NaN match. Correct the comment: partial_merge compares float keys bitwise, and PR ClickHouse#106540 leaves that unchanged, so the test is independent of the hash / full_sorting_merge NaN!=NaN equi-join fix. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed
INNER JOIN ON(andLEFT/RIGHT/FULL/SEMI/ANTIvariants) on float keys returning wrong results when both sides evaluated toNaN. Per IEEE 754 / SQLJOIN ONsemanticsNaN != NaN, but the hash table compared float keys bitwise so matching bit patterns wrongly joined. The fix applies to thehash,parallel_hash,grace_hash,full_sorting_merge, anddirectalgorithms and the runtime filter path. The legacypartial_mergealgorithm still compares float keys bitwise (so twoNaNrows with identical bit patterns match); use one of the other algorithms whenNaN-safety matters.GROUP BY/DISTINCT/uniq/INsemantics onNaNare unchanged.Description
Per IEEE 754 (and SQL
JOIN ONsemantics)NaNnever compares equal toNaN, but ClickHouse's hash table compared float keys bitwise viabitEquals(memcmp). TwoNaNvalues with matching bit patterns therefore wrongly joined:INNER JOIN ON NaN = NaNreturned rows instead of zero, andANTI JOINdropped theNaN-keyed left row instead of keeping it. Reproducer from the issue:Both sides of the
ONclause evaluate toNaN; two of the three build-sideNaNs have bit pattern0xFFF8000000000000matching the probe-sideNaNfromfmod, sobitEqualsreported equality.The fix folds
NaNrows into the JOIN-key null map so they are skipped on both build and probe sides, mirroring howNULLkeys behave. This is applied at every algorithm so they all see the same semantics:HashJoin/ConcurrentHashJoin- extend the build- and probe-sidenull_mapafterextractNestedColumnsAndNullMapviaJoinCommon::extendJoinKeyNullMapWithFloatNaNs(built on the newColumnVector::getNanMaskprimitive).FullSortingMergeJoin- inFullMergeJoinCursor::setChunk, ORNaNpositions into the per-keynull_mapsonullableCompareAtshort-circuits.BuildRuntimeFilterTransform- dropNaNrows before they enter the bloom / exact runtime filter, so the runtime filter never carries aNaNentry that would mis-prune a probe-sideNaN.direct-DirectJoinMergeTreeEntity::getByKeys(MergeTree-keyed) andDirectKeyValueJoin::joinBlock(genericIKeyValueEntitybackends such asEmbeddedRocksDB) routeNaNprobe rows to the not-found path so they honourNaN != NaN.The legacy
MergeJoin(partial_mergealgorithm) keeps its existing behavior: it sorts both sides and merges vianullableCompareAt, which compares float keys bitwise, so twoNaNrows with identical bit patterns still match. Changing it to foldNaNinto the null map is not feasible without rewriting the surrounding output path (copyLeftRange,addRightColumns, fixedright_table_keysschema), and doing so would be a backward-incompatible change for existingpartial_mergequeries on float keys. Thejoin_algorithmsetting documentation gains a:::note Float keysblock describing this, and points users at theNaN-safe algorithms.GROUP BY/DISTINCT/uniq/INkeep their existingNaN-coalescing behaviour. This change only touches the JOIN ON equality path.The new test
04318_106531_join_on_nan_keyscoversINNER/LEFT/RIGHT/FULL/SEMI/ANTIjoins onFloat32/Float64/Nullable(Float64)keys for bothhashandfull_sorting_mergealgorithms, tuple-keyed and runtime-filter variants, and confirmsGROUP BY/DISTINCTsemantics onNaNare unchanged.04318_106531_join_on_nan_keys_rocksdb_directcovers the genericdirectpath overEmbeddedRocksDB.Closes #106531