Skip to content

Document that a float NaN JOIN key can match NaN - #112409

Merged
PedroTadim merged 7 commits into
ClickHouse:masterfrom
groeneai:document-float-nan-in-join-keys
Aug 3, 2026
Merged

PedroTadim merged 7 commits into
ClickHouse:masterfrom
groeneai:document-float-nan-in-join-keys

Conversation

@groeneai

@groeneai groeneai commented Jul 29, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Documentation (changelog entry is not required)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

...

Description

Related: #106540
Closes: #106531

@ PedroTadim asked for a docs PR after #106540 was closed. This adds one paragraph to the
NULL values in JOIN keys section of join.mdx, which a reader would read as covering NaN.

An equality JOIN key is not compared with the scalar = semantics, so NaN = NaN is 0 while a
Float JOIN key holding NaN can still match on the other side. The paragraph states that the
outcome is unspecified and varies with the join implementation, the key type and the settings, and
gives the two comparators as illustrations: the merge algorithms use FloatCompareHelper::compare,
which reports any two NaN values equal, while the hash algorithms compare key bytes via bitEquals.
It promises no per-algorithm outcome, because further layers change it: a LowCardinality(Float) key
can arrive with its NaN payloads already collapsed to one dictionary entry, and the default-enabled
join runtime filter drops matching NaN probe rows when the build side has one distinct key (a
separate defect). isNotDistinctFrom does not separate NaN either; the
paragraph gives a form that does, and scopes itself away from ASOF.

Per review this is docs-only: the Float-page correction and a stale test comment were removed at
@ PedroTadim's request. The paragraph no longer points at the Float page, because that page states
the byte-wise rule as a blanket fact. Measured on master with runtime filters off:

right-side NaN hash / parallel_hash / grace_hash / direct full_sorting_merge / partial_merge
same bit pattern (7FF8000000000000 both sides) matches matches
different bit pattern (nan vs 0./0.) no match matches

I have asked in the review thread how you would like that page handled rather than opening a follow-up
you did not ask for. The docs/en copies are untouched.

Version info

  • Merged into: 26.8.1.676 (included in 26.8 and later)

@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal review: 7 rounds, 32 findings adjudicated, 25 agreed and fixed before publication

Before opening this PR I ran, for each of seven rounds, an independent cold review of the diff plus a
second-model review gate, and adjudicated every finding. That is 32 findings across the seven rounds
(8, 7, 6, 4, 2, 3, 2): 25 agreed and fixed, 7 rejected with evidence.

The mechanism the PR documents held up in every round, verified independently each time: bitEquals
memcmps floats (src/Common/HashTable/HashTable.h:68-82, whose own comment gives the reason) while
FloatCompareHelper::compare inspects only isNaN and never the bits
(src/Core/CompareHelper.h:67-81). What kept failing was the WIDTH of individual sentences: nearly
every blocking finding was a claim true of a bare Float under one implementation, written as if
general.

Round 1 (4 gate + 4 own):

# Finding Verdict Resolution
1 ❌ The direct storage list read as exhaustive. Direct join accepts any IKeyValueEntity, and StorageKeeperMap and StorageRedis implement it too; byte-wise behaviour was measured for only three backends. AGREE Presented as examples, matching how the join_algorithm setting page words it. I did not measure Redis or KeeperMap to widen the claim.
2 ❌ JOIN ... ON isNotDistinctFrom(...) was said to match NaN "under the rules above", i.e. including direct, which cannot run a null-safe predicate. AGREE Scoped, then re-scoped twice more in rounds 5 and 6 (below) before the wording held.
3 ❌ Two runs disagreed on whether an in-order fully-covered GROUP BY folds two NaN payloads (1 vs 2). Correcting exactly this prose is the point of the PR, so an unresolved contradiction could not ship. AGREE Re-measured under a stated protocol; both runs turned out correct on different cells, and the sentence now names the real conditions.
4 ⚠️ The corrected 04546 comment asserted payload independence while the test uses the same nan literal on both sides. AGREE, narrower remedy Comment now says so. I rejected adding differing-payload rows: adding behavioural coverage to a documentation correction is scope creep.
5 ❌ A sentence about not filtering NaN rows in a subquery had no main clause. AGREE Rewritten, same claim.
6 💡 The page names the internal method compareAt to readers. DISAGREE Not introduced here: the sentence this PR replaces already exposed the mechanism ("Hash tables in ClickHouse compare keys byte-wise"), so this is the page's existing register.

Round 2 (5 gate + 4 own):

# Finding Verdict Resolution
7 ❌ Round 1's hedge introduced "key-value" into a list containing MergeTree, which is a category error: no MergeTree storage implements IKeyValueEntity (it reaches direct join through a planner-built adapter instead). AGREE Two-word fix; the in-tree wording deliberately avoids the term.
8 ❌ "A JOIN key is compared by key identity" over-claimed: an ASOF JOIN closest-match key is not compared by identity at all. AGREE Measured 7 ASOF cells plus an equality-key control. The result was not what I expected, and it changed the text: a NaN closest-match key DOES match a finite row under both implementations even though every comparison between them is false. Both pages are now scoped to equality keys, with the measured ASOF behaviour stated separately.
9 ❌ The PR shipped "Both approaches work for DISTINCT and GROUP BY", endorsing a NULL-mapping workaround whose 0 result is a countDistinct artefact: aggregates skip NULL, but DISTINCT/GROUP BY treat NULL as a value, so the rows fold rather than disappear. AGREE Corrected with the mechanism named.
10 ⚠️ prefer_partial_merge was described as runtime-driven; it is a static kind/strictness choice, unlike auto. Also the deprecated default value was unexplained. AGREE Both corrected.
11 💡 The direct bullet's "looks the key up" phrasing fits the key-value mechanism better than the MergeTree one. DISAGREE Both mechanisms are byte-wise, so the sentence misleads no one about the rule being documented, and the phrasing matches the setting page.

Round 3 (3 gate + 3 own):

# Finding Verdict Resolution
12 ❌ The split was presented as decided by the query plan, but a LowCardinality(Float*) column can remove the payload difference before either mechanism runs, which also reaches the hash-join bullet since a single LowCardinality key selects a dictionary-aware hash map. AGREE Addressed, then re-opened twice: the exact scope of this claim took three further rounds to get right (findings 18 and 22).
13 ❌ The prescribed WHERE NOT isNaN(x) also drops pre-existing NULL rows on a Nullable(Float*) column: isNaN inherits default null propagation (src/Functions/FunctionNumericPredicate.h:22 does not override it, default true at src/Functions/IFunction.h:81), so the predicate is NULL for a NULL input and the row fails WHERE. AGREE Measured and addressed; the page now gives WHERE isNull(x) OR NOT isNaN(x) for that case.
14 💡 Literal method and SQL names in the rewritten 04546 comment were not in inline code. AGREE Backticked in the lines this change authored.
15 💡 A Join-engine right side is a third way join_algorithm does not pick the implementation. DISAGREE (own finding, withdrawn) The bullets are keyed on the implementation, not the setting value, so no shipped sentence is false, and the paragraph already tells the reader a value need not select one implementation.
16 💡 "varies between runs" for the ASOF case states an observation where the code proves "unspecified". DISAGREE (own finding, withdrawn) It was measured 12 times, with a NaN-free control stable across 10 runs; a user-facing page should state the observable.

Round 4 (4 findings): the LowCardinality claim from round 3 turned out to be two separate
over-claims.

# Finding Verdict Resolution
17 ❌ The paragraph claimed a -0.0 fold alongside the NaN one. There is no signed-zero canonicalization anywhere in src/Columns/: NaN has four explicit sites, -0.0 has none, and the fold I had observed came from one incidental default-entry comparison on the bulk path only. AGREE The -0.0 clause was dropped rather than re-scoped. Measuring a fold is not evidence that a canonicalization exists.
18 ❌ The paragraph's first sentence was a blanket type-level claim that a LowCardinality Float is not subject to the split at all. The read path adopts a deserialized dictionary verbatim, so it can hold distinct payloads. AGREE Narrowed to canonicalizing insertion, which was still too strong; see finding 22.
19 💡 "unwrapped Float" was introduced undefined, and could be misread as excluding Nullable(Float64), which IS subject to the split. AGREE Names the LowCardinality qualification explicitly instead.
20 💡 The ### Description section should be moved before the changelog headers. DISAGREE Refuted against the live upstream template, re-fetched: it has no ### Description header at all, so there is no template position to move it before, and free-form context belongs at the end.

Round 5 (2 findings) and round 6 (3 findings): the null-safe-predicate restriction, twice raised.

# Finding Verdict Resolution
21 ❌ Round 1's fix for finding 2 stated the restriction by enumerating one storage plus one setting, so any new IKeyValueEntity storage or analyzer change falsifies it. Raised twice, so it could not be closed as presentation-only. AGREE The finding's own suggested remedy and my first prescription were both refuted on reading (the old analyzer installs a StorageJoin right side unconditionally, and the shipped join_algorithm default already contains direct, so no pinning is needed). Replaced with a behavioural statement: the predicate is not accepted in every join, so use a plain equality where it must work everywhere.
22 💡 The 04546 comment attributed the test's first-key NaN == NaN to nullableCompareAt, but the first key goes through nullableCompareTrackAt -> compareTrackAt -> compareAt (src/Interpreters/MergeJoin.cpp:379-387, src/Columns/ColumnVector.h:160-165). AGREE Comment names compareAt without the wrong wrapper.

Round 7 (2 findings): both on sentences this PR authored, both fixed.

# Finding Verdict Resolution
23 ❌ The page asserted one unconditional value, "isNotDistinctFrom returns 0 for two NaN arguments". That is only the non-nullable branch. src/Functions/FunctionsNullSafeCmp.h:168-171 casts both operands to their common supertype and only then, at :175, tests nullability, so ONE Nullable operand is enough to reach the compareAt branch, which returns 1. The nullable case is the one a reader matching NULL keys is actually in. AGREE Measured across all four nullability cells (0, 1, 1, 1) and stated with its condition instead of as a constant.
24 ❌ Third raise on the LowCardinality paragraph. Canonicalization is a property of which insertion API is called, not of insertion: ColumnUnique::uniqueInsert and tryUniqueInsert substitute a canonical NaN, uniqueInsertData does not, and ColumnLowCardinality::insertData calls the latter directly. AGREE Stopped enumerating exceptions. The paragraph now asserts only a disjunction (a dictionary either folds NaN payloads or keeps them as given, depending on how the value reaches the column), with both behaviours given as examples that are explicitly not exhaustive. A further producing path can add detail to that but cannot make any sentence false, which is what the previous form could not survive.

Three findings not listed above were on my own .scratch drafts rather than on the diff (a
pr-body.md over-claim, a stale gate scope, and a stale claim in this comment); I fixed those
directly, since no source file is involved.

The ASOF instability in finding 8 is a genuine engine issue. It is not addressed here: this is a
documentation change, so the docs tell readers to exclude NaN from that key and I filed the engine
behaviour separately.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, in the sense this change admits. The defect is wrong documentation, i.e. a fixed string, and every behavioural claim in the new text is a deterministic one-command measurement against a binary built from this branch (matrices below). Nothing probabilistic.
b Root cause explained? Yes. The Float page stated the byte-wise key-identity rule as a blanket fact, naming equi-JOIN among the affected operations, and ignored the second implementation: compareAt via FloatCompareHelper (src/Core/CompareHelper.h:33), whose less and greater both return false when both sides are NaN, so any two NaN values are one key there. It then said "the same approach works for DISTINCT, GROUP BY, and JOIN keys" about two workarounds, one of which (canonicalize to a single nan) makes NaN rows match.
c Fix matches root cause? Yes. The section is restructured around the actual mechanism split, with JOIN presented as an instance of it. No sentence was merely deleted to make the remainder technically true, and no wording hides the inconsistency.
d Test intent preserved / new tests added? Yes. 04546_partial_merge_join_float_nan.sql is comment-only: non-comment diff lines = 0, the .reference file is untouched, and the test's output still matches it byte-for-byte (plus 50/50 randomized runs green, with the server build id verified against the ELF before and after the run). Its comment now also records that the test uses one nan literal on both sides, so it exercises the NaN branch without claiming payload independence. No new test is owed: no runtime behaviour changes and no harness asserts prose.
e Both directions demonstrated? Yes, by mutation, re-run after each review round. Reading the generated text with the generator's own query (SELECT description FROM system.data_type_families WHERE name = 'Float64'): with the fix every new sentence is present and the wrong ones are gone; with DataTypesNumber.cpp reverted to the base the new sentences are absent and the wrong ones return; restoring rebuilds bit-identically (same Build ID, source md5 restored, readback identical), so no instrumentation remains. Every shipped example was extracted from the generated text and run verbatim, and all annotated outputs are byte-exact.
f Fix is general across code paths? Yes. Swept the tree for contradicting prose: git grep "106540" over src/ tests/ docs/ is now 0 hits (was 1), and bitwise in 04546 is 0 (was 2). The embedded block was grepped for JOIN: only the two sentences named above, both corrected. ## NaN values in set semantics occurs exactly once in the .cpp, so the Float32/BFloat16 entries do not repeat it. The review rounds then swept the new text itself for claims wider than their evidence and narrowed five: the direct-join storage list, its "key-value" characterization (no MergeTree storage implements IKeyValueEntity), the availability rule for the in-order form, the null-safe-predicate restriction, and the merge-vs-hash cause for prefer_partial_merge (static) versus auto (runtime). The join-implementation matrix is now complete over the accepted join_algorithm values, including the deprecated default. A later round narrowed two more: the split's opening sentence now names the LowCardinality qualification explicitly instead of using the undefined term "unwrapped", which could be misread as excluding Nullable(Float64) (that type is subject to the split), and the row-filtering recommendation is now nullable-aware. The LowCardinality paragraph itself was then rewritten twice. Narrowing it to "canonicalizing insertion" was still too strong, because canonicalization is a property of which insertion API is called and not of insertion: ColumnUnique::uniqueInsert and tryUniqueInsert substitute a canonical NaN, while uniqueInsertData does not, and ColumnLowCardinality::insertData calls the latter directly. The final round therefore inverted the paragraph instead of adding a further exception: it states that the dictionary may or may not fold NaN bit patterns, gives the two behaviours as examples that are explicitly not exhaustive, and tells the reader not to rely on either outcome. That phrasing stays true if a further producing path exists, which the previous enumerate-the-exceptions form did not.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes, and the wording reflects it. It says "a Float JOIN key", not Float64, because Float32 (7FC00000 vs FFC00000), BFloat16 and Nullable(Float64) show the same payload split; it covers ON and USING (measured identical: 2 same-payload / 1 different-payload); all six join algorithms were measured individually, and direct on Dictionary, EmbeddedRocksDB and MergeTree with the plan confirmed as DirectKeyValueJoin in each. Direct join accepts any IKeyValueEntity storage, so the text gives those three as examples rather than as the complete set. The null-safe predicate was measured per backend and its acceptance is irregular rather than uniform per storage class (accepted on EmbeddedRocksDB in every nullability cell and on a FLAT Dictionary; rejected on MergeTree only when direct is pinned, and on ENGINE = Join only when both keys are Nullable), so the text claims only that the predicate is not accepted in every join and that a plain equality is the portable form, attributing the variation to no single cause. Its own scalar value was measured across all four nullability cells this round and is nullability-dependent, not a constant: 0 for two non-Nullable Float arguments, 1 as soon as either argument is Nullable (both-nullable, left-only and right-only all return 1, including for two distinct NaN bit patterns), because FunctionsNullSafeCmp casts both operands to their common supertype before testing nullability, so one Nullable operand makes both converted columns nullable and the compareAt branch is taken. The text states both values with that condition rather than a single unconditional one. The ASOF JOIN closest-match key was measured separately under hash and full_sorting_merge (implementation confirmed by EXPLAIN in each) and is excluded from the split, since a NaN there matches even a finite row and the chosen row is not stable once the right-hand side of that key holds a NaN; that exclusion was re-measured for Float32 and BFloat16. The LowCardinality wrapper is covered as its own case, and is deliberately stated as a two-outcome qualification rather than a guarantee: a dictionary may fold NaN payloads together or keep them as given, depending on how the value reaches the column. The folding outcome was measured across four entry routes (and again this round for toLowCardinality and a RowBinary read, both folding to the single canonical 7FF8000000000000); LowCardinality(Nullable(Float64)) was measured too, and a plain-Float64 control on the same payloads still shows the split. Two claims were withdrawn in the final round because they were wider than the evidence: the -0.0 fold (no signed-zero canonicalization exists in src/Columns/; the observed fold comes from an incidental default-entry comparison on the bulk path only), and any type-level claim of immunity, since a dictionary read back from storage is not re-canonicalized. That non-folding behaviour is documented from the in-tree contract (ColumnLowCardinality.cpp:393-401, plus the adopting ColumnUnique constructor at ColumnUnique.h:279-292, which performs no NaN scan, and the read path that reaches it at SerializationLowCardinality.cpp:681) and is explicitly not claimed as measured, since the fixture cannot be built from SQL in a session; the text presents it as one of two example behaviours rather than as a closed exception. The nullable filter recommendation was measured on a column holding NaN, NULL and a finite value, since isNaN returns NULL for a NULL argument and the naive filter silently drops those rows. inf is deliberately excluded (inf = inf is 1), and no claim is made about sign-bit-only distinctness since -nan normalizes to nan.
h Backward compatible? Yes, vacuously. No setting, no default, no format, no serialization, so no SettingsChangesHistory.cpp entry. Zero runtime behaviour change: the only src/ edit is inside a raw string literal.
i Invariants and contracts preserved? Yes. No signature, logic or control flow is touched. The invariant this change asserts is that the documented statements are true of master, and each one is backed by a measurement on a binary built from this branch.

Session id: cron:clickhouse-impl-slot-40:20260729-034400

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @PedroTadim @nickitat — could you review this? It is the docs PR requested on #106540: the Float page stated the byte-wise key-identity rule as a blanket fact (naming equi-JOIN), which is false for the merge joins and for the in-order forms of DISTINCT/GROUP BY, and it offered two JOIN-key workarounds when canonicalizing to a single nan actually makes NaN rows match. The section now describes the byte-wise vs compareAt split with JOIN as one instance of it, plus one cross-referencing paragraph in join.mdx.

@PedroTadim PedroTadim self-assigned this Jul 29, 2026
@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jul 29, 2026
@PedroTadim
PedroTadim enabled auto-merge July 29, 2026 08:07
@PedroTadim
PedroTadim disabled auto-merge July 29, 2026 08:07
@clickhouse-gh

clickhouse-gh Bot commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [70defdf]

Summary: ✅


AI Review

Summary

This PR adds a short NaN caveat to the JOIN documentation, but two issues still block it for me. The new text is being added to the generated docs/reference copy instead of the hand-edited docs/en source, so the canonical docs remain unchanged and the edit can be overwritten by the next sync. The paragraph also still documents ON if(isNaN(A.id), NULL, A.id) = B.id as a general workaround even though that rewrite breaks the NULL = NULL behavior the section just taught for Nullable(Float) keys.

Findings
  • ⚠️ Majors
    • [docs/reference/statements/select/join.mdx:278] This PR edits docs/reference/statements/select/join.mdx, but the repo documentation contract says docs/reference/ is generated and only docs/en/ is hand-edited source. The corresponding source page, docs/en/sql-reference/statements/select/join.md, still has the old NULL values in JOIN keys section with no NaN paragraph, so merging this as-is leaves the canonical docs unchanged and the next sync can overwrite the new text. Suggested fix: move the change to docs/en/sql-reference/statements/select/join.md and let the generation/sync step update the derived copy.
    • [docs/reference/statements/select/join.mdx:282] [dismissed by author -- https://github.com/Document that a float NaN JOIN key can match NaN #112409#discussion_r3673242099] ON if(isNaN(A.id), NULL, A.id) = B.id is still presented as the workaround for keeping NaN rows from matching, immediately after the section teaches isNotDistinctFrom for preserving NULL = NULL matches. On a Nullable(Float) key, isNaN(NULL) yields NULL, so this rewrite also drops those NULL = NULL matches. Suggested fix: either scope this sentence to non-Nullable keys, or document the null-preserving predicate instead.
Final Verdict

Status: ⚠️ Request changes

Minimum required actions:

  • Move the documentation change from docs/reference/statements/select/join.mdx to docs/en/sql-reference/statements/select/join.md.
  • Fix or explicitly scope the if(isNaN(...), NULL, ...) workaround so it does not misdocument Nullable(Float) JOIN keys.

Comment thread src/DataTypes/DataTypesNumber.cpp Outdated
Hash tables in ClickHouse compare keys byte-wise, so different `NaN` bit patterns hash to
different buckets and are treated as distinct values by set-semantics operations including
`DISTINCT`, `GROUP BY`, `uniqExact`, `countDistinct`, and equi-`JOIN` on a `Float` key:
ClickHouse decides whether two `Float` values are the same key in one of two ways, and the two

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@groeneai remove the changes on this file

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Removed in 0e84018 (via f6001d4); the file is back to its master content, and the PR is now join.mdx only.

One consequence I want to flag rather than leave silent. That embedded documentation is what generates the Float page, and on master it states the byte-wise key-identity rule as a blanket fact, naming equi-JOIN among the operations that treat different NaN bit patterns as distinct. That holds for the hash joins only. Measured on this branch's merge base with l = {nan, 1.0} joined on equality:

right-side NaN hash / parallel_hash / grace_hash full_sorting_merge / partial_merge
same bit pattern (7FF8000000000000 both sides) matches matches
different bit pattern (nan vs 0./0.) no match matches

The paragraph in join.mdx linked to that page "for the details", which would have sent readers to text that contradicts it for the merge joins, so I dropped the pointer and the paragraph now stands on its own.

Which would you prefer: I open a separate PR correcting the Float page, I leave it as it is, or you would rather it said something different from what I had written? I did not want to open a follow-up you had not asked for.

@clickhouse-gh clickhouse-gh Bot added the pr-documentation Documentation PRs for the specific code PR label Jul 29, 2026
-- which explicitly leaves partial_merge's bitwise behavior unchanged.
-- with `compareAt`, under which any two NaNs are equal regardless of their bit
-- patterns, so NaN==NaN on the first key; the second key is what excludes the
-- pair. Note this test uses the same `nan` literal on both sides, so it

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@groeneai remove the changes at this file as well

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Removed in the same commit; the file is back to its master content and no longer part of this PR.

Just so it is on the record: those changes were comment-only, so nothing about the test's coverage changed either way. The comment on master says partial_merge compares float keys bitwise via nullableCompareAt, and that helper delegates to compareAt, under which any two NaN values are equal regardless of bit pattern. I will leave that as it is unless you want it corrected separately.

Comment thread src/DataTypes/DataTypesNumber.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Jul 29, 2026
@groeneai groeneai changed the title Document that a float NaN JOIN key can match NaN, and correct the Float page Document that a float NaN JOIN key can match NaN Jul 29, 2026
@PedroTadim
PedroTadim enabled auto-merge July 29, 2026 10:15
@PedroTadim
PedroTadim disabled auto-merge July 29, 2026 10:23
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 0e84018

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
(none) — 174 checks completed, 0 failures

CI is fully finished on this head with no failing checks.

Session id: cron:our-pr-ci-monitor:20260729-103000

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
@groeneai
groeneai force-pushed the document-float-nan-in-join-keys branch from 0e84018 to b39a22a Compare July 29, 2026 12:47
The Float page's embedded documentation states the byte-wise key-identity
rule as a blanket fact and names equi-JOIN among the operations that treat
different NaN bit patterns as distinct. That holds for the hash joins only:
full_sorting_merge and partial_merge match NaN keys across differing bit
patterns. It also presents if(isNaN(x), NULL, x) as working for JOIN keys
in general, which breaks on a Nullable(Float) key.

The correction to that page was removed from this PR on review, so the
link sent readers from this paragraph to text contradicting it. The
paragraph is self-contained, and Nullable(Float) two sentences below was
already an unlinked type name, so drop the link rather than send readers
to the contradiction.
…ntity

The paragraph claimed an equality JOIN key is "compared by key identity". That
describes only the byte-comparing algorithms: hash and direct compare the key
bytes (bitEquals in HashTable.h), while full_sorting_merge and partial_merge go
through the column comparator (MergeJoinTransform.cpp compareCursors and
MergeJoin.cpp nullableCompareAt, both reaching ColumnVector::compareAt and
FloatCompareHelper::compare), which returns 0 for any two NaN values regardless
of payload. Calling both key identity contradicted this PR's own measured matrix.

Naming the algorithm as the thing that decides it is not right either, because
other layers decide it too. A LowCardinality(Float) key can arrive with its NaN
payloads already collapsed into one dictionary entry, so two originally distinct
payloads join as one key (measured: plain Float64 tables give 0 matches, the same
two values in LowCardinality(Float64) tables give 1). And with the default
enable_join_runtime_filters, a build side holding a single distinct key makes the
runtime filter fall back to scalar equality, which rejects every NaN and drops
the probe row before the join runs; that one is a separate defect and is not
documented here as intended behaviour.

So state what actually holds: whether two NaN keys match is unspecified and
varies with the join implementation, the key type and the settings. The two
comparators remain as illustrations, and the practical advice is unchanged, since
it is what a reader should follow either way. Also drop "rather than by key
identity" from the ASOF sentence, since ordering is the point there.
@rschu1ze
rschu1ze requested a review from a team as a code owner August 3, 2026 09:01
@PedroTadim
PedroTadim enabled auto-merge August 3, 2026 09:01
Proofreading only, no change to the described behavior or to the
recommended predicate:

- "in a float JOIN keys" -> "in float JOIN keys" (number agreement)
- "If they actually do is" -> "Whether they actually do is"
- "Do do not rely" -> "Do not rely"
.claude/CLAUDE.md requires literal names from the ClickHouse SQL
language to be wrapped in inline code. The rest of this file already
follows that (21 backticked occurrences of JOIN, none bare), so these
two were inconsistent. No wording change.
auto-merge was automatically disabled August 3, 2026 10:24

Head branch was pushed to by a user without write access

└─────────┴───────┘
```

`NaN` values in float `JOIN` keys do not follow the `NULL` rule above.

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.

docs/reference/ is the generated docs tree, not the hand-edited source. The repo instructions explicitly say to make documentation changes in docs/en/ and let the sync/generation pipeline update docs/reference/ afterwards.

Right now the corresponding source page, docs/en/sql-reference/statements/select/join.md, still has the old NULL values in JOIN keys section with no NaN paragraph at all. So this PR changes only the derived copy: the canonical docs stay unchanged, and the next sync can overwrite this edit.

Please move the heading/paragraph update to docs/en/sql-reference/statements/select/join.md instead of editing docs/reference/statements/select/join.mdx directly.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

I checked the premise before acting. On current master (07e66b53312d) the direction is the other way round.

  • No tooling generates docs/reference/ from docs/en/. docs/_migration/ is one-shot tooling that migrated pages in from the separate clickhouse-docs Docusaurus repo, is referenced by no CI job, and its own README says the folder can be deleted once the migration completes. autogenerate_docs.py generates from a binary's introspection tables into AUTOGENERATED regions, and this page has none.
  • The check that rule names, "No direct edits to generated or read-only docs", takes its protected list from ci/jobs/scripts/docs/readonly_copies.json, which holds only the two clickhouse-connect paths. docs/reference/ is not in it, and Docs check (Mintlify) is green on 70defdfd.
  • docs/README.md describes en/ as legacy content from the previous Docusaurus site with "do not add new content here", docs/.mintignore excludes /en/ from the published build, and this page is listed in docs/reference/navigation.json. There is no navigation.json under docs/en/.
  • 118 of the 134 non-merge commits touching docs/reference/ in the last 90 days do not touch docs/en/, so the trees are not kept in step.

.claude/CLAUDE.md:13 does say what you quote, but its two factual claims do not hold for this path: there is no sync to overwrite the edit, and the check it names does not cover docs/reference/. It reads stale against the 2026-07-14 Mintlify cutover recorded in docs/README.md.

Moving the paragraph to docs/en/ would place it on a page excluded from the published site, so I am leaving the change where it is.

@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 70defdf

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Build (arm_release) / Post Hooks CI telemetry infra: build_profile_hook.py INSERT into build_time_trace rejected with LogCluster query failed with code 500; the enclosing Build (arm_release) job itself is success, so nothing in this PR's diff is implicated a fix task is created (investigating at full effort — fixing-PR link to follow here)

All 174 other checks completed without failure (Finish Workflow and Config Workflow both green).
This PR changes one docs file (docs/reference/statements/select/join.mdx) and touches no src/ or
tests/ path, so no test surface is exercised by it.

Session id: cron:our-pr-ci-monitor:20260803-123000

@PedroTadim
PedroTadim added this pull request to the merge queue Aug 3, 2026
Merged via the queue into ClickHouse:master with commit 7dce428 Aug 3, 2026
180 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 3, 2026
pull Bot pushed a commit to Mu-L/ClickHouse that referenced this pull request Aug 6, 2026
Issue ClickHouse#113169 reports that indexOf matches NULL and inf but not nan, while
Postgres array_position matches NaN.

Both behaviours already exist in the tree and which one you get depends only on
the column layout. Float32 and Float64 are in INTEGRAL_PACK
(src/Functions/array/arrayIndex.h:703), which routes them to the typed compare
overloads at :92-138 - raw left[i] == right[j], so IEEE-754 semantics and NaN
never matches. Every other layout falls through to compareAt at :148, which for
floats reaches FloatCompareHelper::compare (src/Core/CompareHelper.h:67-76);
that returns 0 for two NaN values, so a LowCardinality, Tuple or nested array
element does match. That is the same comparator ORDER BY uses, which is why the
paragraph describes those layouts as compared by ordering.

The behaviour is not changed here. The decision owner put NaN, -0.0, +0.0, -Inf
and +Inf in the expected-behavior bucket on ClickHouse#112514 and ClickHouse#112502 and again on
this issue, pointing at the docs pattern from ClickHouse#112409, so this documents the
outcome as unspecified rather than promising either result.

Scoped to indexOf. has, countEqual and indexOfAssumeSorted share the same
FunctionArrayIndex implementation and mapContainsKey/mapContainsValue reuse it,
and all measure 0; hasAll and hasAny are a separate implementation
(FunctionArrayHasAllAny via sliceEqualElements) with the same observable result,
so text under indexOf would not speak for them.

Every sentence was measured against the built binary with negative controls:
plain Array(Float32)/Array(Float64) return 0 while an ordinary needle returns 1;
LowCardinality, Tuple and nested-array elements return 2 while the same layouts
without a NaN element return 0; indexOf([1.1, NULL], NULL) returns 2, which is
why the paragraph says NaN does not follow the NULL rule stated one line above;
arrayFirstIndex(x -> isNaN(x), arr) returns 2 on the reported example, 1 with
the NaN first, and 0 for a NaN-free and for an empty array.

No tests: nothing observable changed, so a test could only restate
system.functions. 02415_all_new_functions_must_be_documented still passes. The
rendered pages under docs/reference/ come from the nightly regeneration, so only
the C++ documentation string changes here.

Closes: ClickHouse#113169
pull Bot pushed a commit to Mu-L/ClickHouse that referenced this pull request Aug 6, 2026
The paragraph said that "other layouts, such as a LowCardinality, Tuple or
nested array element, are compared by ordering, in which NaN ties with
itself". That is right for Tuple and nested-array elements, which reach
compareAt and therefore FloatCompareHelper::compare, but wrong for
LowCardinality: executeArrayLowCardinality runs first and matches by
dictionary index (ColumnUnique::getOrFindValueIndex, then a bytewise
getDataAt comparison), so it is not an ordering comparison at all, and the
result flips on whether the needle is constant - measured 2 for a constant
NaN needle and 0 for a non-constant one, in both the expression form and on
a real Array(LowCardinality(Float64)) column, each with a non-NaN control.

The surrounding sentences already say the outcome is an implementation
detail not to be relied on, so a corrected LowCardinality rule would just
hand the reader a second thing to rely on. Drop the mechanism clause
instead of refining it, matching ClickHouse#112409, which states no mechanism either.
The remaining Tuple and nested-array claim was re-measured in both needle
constness shapes and on real columns, with non-NaN controls: 2 for the NaN
row, 0 for the control, in all eight arms.

Also split the 193-character sentence above it in two.

Co-Authored-By: Claude Fable 5 <[email protected]>
huldarchen pushed a commit to huldarchen/ClickHouse that referenced this pull request Nov 5, 2026
Add a "Comparison of JOIN keys" section to the JOIN algorithms page and
point the `ie_join` and block nested loop sections at it.

A JOIN key is compared by the algorithm, not by `equals`. The hash
family compares `Float` keys by their bits, so a `NaN` matches only a
`NaN` with the same bit pattern; the sort-merge family compares with
`IColumn::compareAt`, where any two `NaN` are equal; both match a
`Tuple` with a `NULL` element and a `NULL` `Variant`, for which
`equals` returns `NULL`. `ie_join` evaluates a remaining equality as a
residual filter or post-join filter with `equals`, and the block nested
loop fallback evaluates the whole `ON` condition, so neither matches
those pairs.

Measured per algorithm on master (26.11.1.1) with one row on each side.
`-0.0` vs `0.0` and a `String` with trailing zero bytes vs `FixedString`
are left out on purpose: ClickHouse#115970 and ClickHouse#118561 remove those differences.
The JOIN statement page is not edited because ClickHouse#129276 rewrites it.

Related: ClickHouse#129219
Related: ClickHouse#112409

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors manual approve Manual approve required to run CI pr-documentation Documentation PRs for the specific code PR pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

INNER JOIN on NaN condition returns incorrect rows with HAVING + UNION DISTINCT when enable_optimize_predicate_expression=0

4 participants