Skip to content

Fix wrong results in JOIN on float keys from the join runtime filter - #112502

Closed
groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:fix-join-runtime-filter-float-key-identity
Closed

groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:fix-join-runtime-filter-float-key-identity

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixes wrong results in JOIN on floating-point keys when the join runtime filter's build side has exactly one distinct value. The single-value fast path compared keys with equals/notEquals instead of the bitwise key identity the JOIN itself uses, so rows with NaN keys were dropped from INNER JOIN results and rows with -0.0 keys were dropped from LEFT ANTI JOIN results.

Description

The join runtime filter pre-filters the probe side above the join, so it must never reject a row the join could match. When the build side collects exactly one distinct value, finishInsertImpl takes a fast path evaluating the filter as value == const, or value != const for ANTI, instead of a set lookup. The JOIN compares keys bitwise via bitEquals in HashTable.h, and SQL comparison disagrees with that on floats in both directions:

  • nan = nan is false while the two bit patterns are the same key, so the positive filter drops a row the JOIN would have matched.
  • 0.0 = -0.0 is true while the keys differ, so the negated filter drops a row belonging in the LEFT ANTI JOIN output. No NaN is involved in this one.

Both return silently wrong results on default settings:

CREATE TABLE l (k Float64) ENGINE = Log; INSERT INTO l VALUES (nan);
CREATE TABLE r (k Float64) ENGINE = Log; INSERT INTO r VALUES (nan);
SELECT count() FROM l JOIN r ON l.k = r.k;  -- returns 0, must be 1

The fix skips the fast path when the filter's target type contains a float at any nesting depth, so those filters fall back to the existing Set path, which is byte-wise and already agrees with the JOIN. This mirrors the !argument_can_have_nulls clause on the same line, and keeps the optimization for every type where it is sound. The type test uses isFloat, not isNativeFloat, which would exclude BFloat16, and walks the type tree with IDataType::forEachChild, covering Tuple, Array, Map and Array(Tuple(...)) keys. A JSON key declines outright: its dynamic paths are not in the static type, so a float in one cannot be ruled out. Nullable keys were already excluded by the NULL clause.

Validation and merge-order notes

With this fix the fixture in #106531 returns 2 rather than the 0 seen on 26.x. 2 is the correct key-identity answer, so a reviewer who recalls that report should not expect 0. Documented in #112409.

#96779 carries an equivalent guard inside a much larger change, but it uses isNativeFloat and covers neither signed zero nor JSON.

New test 04653_join_runtime_filter_float_key_identity: 37 rows, of which 18 return 0 before the fix and 1 after; the other 19 are unchanged controls. Carriers: Float64, Float32, BFloat16, LowCardinality(Float64), mixed widths, multi-key INNER and LEFT ANTI over Tuple(Float64, Int64), Array(Float64), Map(String, Float64), Array(Tuple(Float64, Int64)), JSON and Tuple(JSON), and the three hash algorithms. Controls: Nullable(Float64), Decimal64(2) and Int64 keys keep the fast path, and -0.0 INNER JOIN 0.0 and nan LEFT ANTI JOIN nan stay empty, since there the filter was too permissive rather than too strict and the JOIN rejects those rows itself.

Eight mutations confirm every clause of the guard is load-bearing, each reddening only the rows it should. A unit test pins the predicate directly, since a guard answering yes for every type would silently cost the optimization on Int64 and Decimal64 keys while every SQL row still passed.

Liveness: Log tables so the probe-size cutoff cannot suppress the filter even at its default; EXPLAIN PLAN and RuntimeFilterRowsChecked assertions per planner branch that the filter is present and actually ran; and query_plan_join_swap_table pinned, without which a swapped plan builds a positive filter and the signed-zero rows stop reproducing the bug while still passing. 50 of 50 repeated runs pass, 20 of 20 randomized, 20 of 20 at -j 8.

groeneai and others added 4 commits July 29, 2026 20:05
The runtime filter pre-filters the probe side above the join, so it must
never reject a row the join could match. When the build side collects
exactly one distinct value, finishInsertImpl takes a fast path that
findImpl evaluates with the SQL function equals, or notEquals when
negated, instead of a set lookup.

The JOIN compares keys with bitEquals, which is a memcmp for floats
(HashTable.h), and SQL comparison disagrees with that in both
directions. nan = nan is false while the two bit patterns are the same
key, so the positive filter dropped a row the join would have matched
and an INNER JOIN on a NaN key returned nothing. 0.0 = -0.0 is true
while the keys differ, so the negated filter dropped a row that belongs
in the LEFT ANTI JOIN output; that half involves no NaN at all. Both
returned silently wrong results on default settings.

Skip the fast path when the filter's target type contains a float at
any nesting depth, so those filters fall back to the existing Set path,
which is byte-wise and already agrees with the join. This mirrors the
argument_can_have_nulls clause on the same line and keeps the
optimization for every type where it is sound. The predicate is isFloat
rather than isNativeFloat, which would exclude BFloat16, and the walk
uses IDataType::forEachChild, which is transitive, so Tuple, Array, Map
and Array(Tuple(...)) keys are covered too.

Found while building a control fixture for the NaN-in-JOIN-keys
documentation change. The matching behaviour itself is decided: making
float NaN join keys compare unequal was proposed in ClickHouse#106540 and
declined, so the filter is the component that was wrong.

Related: ClickHouse#106531
…elper

Review round 1 on the float-key-identity guard.

A JSON value keeps its numbers in dynamic paths, which are not part of the
static type: DataTypeObject::forEachChild iterates only typed_paths. So the
type-based float test could not see a float in a dynamic path and the
single-distinct-value "== const" fast path was still taken for a JSON key,
where it disagrees with the JOIN's bitwise key identity on signed zero.
Measured: a one-row `-0.0` LEFT ANTI `0.0` on JSON keys returned 0 with the
filter and 1 without it, both before and after the previous commit.
A DECLARED path (JSON(a Float64)) was already covered, since it is part of
the static type.

"Contains a float" is undecidable for a JSON type, so the sound answer is to
decline the fast path for it. The float and the JSON test now share one
predicate applied at both the top-level type and every nested child, so
Tuple(JSON) is covered as well. The NaN direction is unreachable for JSON:
no spelling stores a NaN in a JSON value, it is dropped or read as zero.

A gtest pins both directions of the helper. The FALSE branch is what keeps
the optimization for types where "=" is key identity, and it is not
observable from SQL, because ValuesCount::ONE and MANY return the same rows
for such a type: a helper made unconditionally true reddens none of the 31
SQL assertions while failing all ten float-free gtest cells.

Two tables were renamed to l_lc_f64 / r_lc_f64, since l_lc and r_lc are also
created by 01049_join_low_card_bug_long with an incompatible schema and would
collide in the CI mode where all tests share one database. Five EXPLAIN rows
now assert filter presence per planner branch, so a shape whose filter stops
being installed cannot pass vacuously.
…as one

Review round 2 on the float-key-identity guard.

The six has-filter rows match the substring RuntimeFilter in EXPLAIN PLAN, which
the build-side BuildRuntimeFilter step satisfies on its own. The probe side is a
separate mechanism and it fails open: FunctionApplyFilter returns an all-true
constant when the rendezvous lookup misses. So a broken probe side would leave
every join result correct and all 31 assertions green while the code this test
covers never executed.

RuntimeFilterRowsChecked distinguishes the two. It is incremented only from
IRuntimeFilter::updateStats, which is reached only from the ZERO, ONE and MANY
arms of the filter lookup, so it moves if and only if the probe-side filter ran.
Six new rows read it back from system.query_log, one per planner branch, keyed by
a per-statement log_comment and scoped to currentDatabase() so the rows stay
parallel-safe. The plan rows are kept: they still catch the different failure of
the planner not inserting the pair at all.

Forcing the lookup-miss branch shows the divergence the rows exist for: the six
new rows fail while the six plan rows and all 25 result rows still pass.
LEFT ANTI is a swap-only strictness, so query_plan_join_swap_table=true reverses
it to RIGHT ANTI. The negated filter is built only for LEFT ANTI, so a swapped
plan builds ExactContainsRuntimeFilter instead of ExactNotContainsRuntimeFilter
and the notEquals path this test covers never runs.

Nothing in the test noticed. Under a swapped plan the results stay correct, the
EXPLAIN PLAN rows still find a runtime filter and the RuntimeFilterRowsChecked
rows still move, because a positive filter still runs. Measured on a pristine
master build, all seven signed-zero ANTI rows read 0 with the setting pinned to
0 and 1 without it, so without the pin those seven rows stop reproducing the bug
while every assertion still passes. stress.py randomizes this setting to 'true'
at p=0.2, while clickhouse-test deliberately excludes 'true'.

Also correct the Log-versus-MergeTree rationale comment. It claimed no runtime
filter is installed for a MergeTree source at this size, which is false at the
join_runtime_filter_min_probe_rows=0 pinned just above: the probe-size cutoff is
entirely enclosed in a min_probe_rows > 0 branch, so at 0 either engine keeps
the filter. At the default 1000 a MergeTree source of this size reports an
estimate of 1 row and is suppressed, whereas Log reports no estimate at all, so
Log keeps the test meaningful if that pin is ever dropped.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model, plus my own cold review of the resulting code.
4 review rounds, 19 findings adjudicated (10 AGREE, 5 DISAGREE, 4 dropped). The final round
returned 0 findings. Engine: codex.

# Sev Finding Verdict Evidence / action
1 ⚠️ A JSON key keeps its floats in dynamic paths, which are not part of the static type, so forEachChild cannot see them and a type-based test cannot rule a float out AGREE, fixed The guard now also declines for isObject(). Three SQL rows plus 4 unit cells; a mutation dropping only that clause reddens exactly the two dynamic-path rows and not the declared-path row
2 ⚠️ Test liveness: the assertions could pass with no runtime filter installed at all AGREE, fixed Six EXPLAIN PLAN rows, one per planner branch. The matched string is a plan step name printed unconditionally, so it is robust to plan-format changes
3 ⚠️ Liveness, second layer: FunctionApplyFilter fails open on a lookup miss, so a broken probe side leaves every result correct and every assertion green AGREE, fixed Six RuntimeFilterRowsChecked rows. That counter has exactly one increment in the tree, inside IRuntimeFilter::updateStats, reachable only from probe-side lookup arms
4 ⚠️ Liveness, third layer: LEFT ANTI is a swap-only strictness, so a swapped plan reverses it to RIGHT ANTI, builds a positive filter instead of the negated one, and every assertion still passes AGREE, fixed query_plan_join_swap_table pinned. Measured on unpatched master: the signed-zero row reads 0 with the pin and 1 without it, so without the pin 7 regression rows silently stop reproducing the bug
5 ⚠️ Two tables in the fixture collided by name AGREE, fixed Renamed; assertions unchanged
6 ⚠️ The float guard is over-broad because it declines for composite types whose equals already agrees with the JOIN on NaN DISAGREE Measured: [0.0] = [-0.0] and map('a', 0.0) = map('a', -0.0) are both true while the JOIN treats those keys as distinct, so the ANTI direction is wrong for exactly those types. The guard is needed per type, not per polarity, since one filter serves both
7 💡 The comment claiming no runtime filter is installed for a MergeTree source at this size AGREE, fixed False while join_runtime_filter_min_probe_rows is pinned to 0: the cutoff is entirely inside an if (min_probe_rows > 0) block. Comment and description corrected
8 ⚠️ The test should carry a log-engine tag, since the stress runner rewrites ENGINE = Log to MergeTree Dropped, self-withdrawn The rewrite is real, but the rewritten test still installs the filter and still exercises the fix, so the tag would only skip real coverage
9 💡 QBit declares nested subtypes but has no type-walk override, so a float element is invisible to the guard DISAGREE Reachable as a join key, but equals on QBit is already bitwise and so already agrees with the JOIN: NaN = NaN is true and 0.0 = -0.0 is false for it, the opposite of raw floats. Measured no divergence, so widening the guard would only lose an optimization
10 💡 Dynamic and Variant keys are missing from the carrier list DISAGREE Not carriers: both satisfy canContainNull, so the pre-existing NULL clause already blocks the fast path for them. Measured to agree with the filters-off oracle in both directions

Severity: ❌ blocker, ⚠️ major, 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal
per finding. Two further items I raised against my own artifacts were fixed in this round rather
than bounced: stale assertion and mutation counts in the description, and one acceptance criterion
I had written that contradicted another criterion of the same item.

Session id: cron:clickhouse-review-slot-10:20260730-002100

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. clickhouse local --queries-file 04653_join_runtime_filter_float_key_identity.sql on a pristine-master debug build (Build ID 0e5904a96c36a0cf) returns 0 for 18 rows that must be 1, every run. No server needed, not a low-rate case. Minimal form: Log table holding one nan, joined to a Log table holding one nan, SELECT count() returns 0.
b Root cause explained? Yes. The runtime filter pre-filters the probe side above the join, so it must never reject a row the join could match. RuntimeFilterBase::finishInsertImpl (RuntimeFilterLookup.h:171) takes a fast path when the build side has exactly one distinct value, and findImpl (RuntimeFilterLookup.cpp:471) then evaluates it with SQL equals, or notEquals when negated. The JOIN compares keys with bitEquals, a memcmp for floats (HashTable.h:69-77). The two disagree on floats in both directions: nan = nan is false while memcmp says same key, so the positive filter drops a row the join would match; 0.0 = -0.0 is true while memcmp says different keys, so the negated filter drops a row belonging in the LEFT ANTI output.
c Fix matches root cause? Yes. The defect is the substitution decision itself, so the guard sits on the line that makes it, mirroring the !argument_can_have_nulls clause already there. Not a band-aid: no widened bound, no no-random-* tag, no reduced dataset, and no check bolted onto findImpl, which would have left values_count reporting a path it no longer takes. Correctness of the fallback is measured, not argued: the Set path already returns the right answer for the same data with two or more distinct build values.
d Test intent preserved / new tests added? No existing test was weakened or removed. One new stateless test, 04653_join_runtime_filter_float_key_identity, 37 assertions, every one with runtime filters enabled since a disabled filter makes them vacuous. Each row is proven live: 18 redden on pristine master, and eight mutation tests pin each part of the guard separately. Six assertions read ProfileEvents['RuntimeFilterRowsChecked'] back from system.query_log, one per planner branch, because the EXPLAIN PLAN rows are satisfied by the build-side step alone while the probe side fails open (FunctionApplyFilter.cpp:106-109 passes every row on a lookup miss); mutation 8 forces that miss and reddens exactly those six rows while all six plan rows and all 25 result rows still pass. A gtest, gtest_runtime_filter_contains_float.cpp, additionally pins the helper's FALSE branch, which decides where the optimization is kept and is not observable from SQL. The test also pins query_plan_join_swap_table = 0, because LEFT ANTI is a swap-only strictness (optimizeJoin.cpp:1037-1040) and a swapped plan reverses it to RIGHT ANTI, which builds a positive filter instead of the negated one; measured on pristine master, all seven signed-zero ANTI rows read 0 with the pin and 1 without it, so without the pin those seven rows stop reproducing the bug while every assertion still passes.
e Both directions demonstrated? Yes, using the shipped test file rather than a bespoke probe. Pristine master: 18 rows 0. With the fix (b717ec1b54289761): byte-identical to the .reference. All 19 controls unchanged in both arms, including all six EXPLAIN PLAN anti-vacuity rows and all six RuntimeFilterRowsChecked rows, each of which is itself shown non-vacuous by flipping to 0 when the filter is suppressed. The six execution rows read 1 on pristine as well, which is the point of them: there the filter runs and merely computes the wrong answer, so they pin execution rather than correctness. 50 of 50 repeated runs pass with randomization on, 20 of 20 at -j 8, and 20 of 20 with randomization disabled; the setting pins hold at every client value of query_plan_join_swap_table (0, false, auto, true).
f Fix is general across code paths? Yes, verified by reading rather than assumed. There is exactly one equals/notEquals construction in the whole runtime-filter subsystem (RuntimeFilterLookup.cpp:471). All three filter classes reach the guarded decision: ExactContainsRuntimeFilter::finishInsertImpl and ApproximateRuntimeFilter::finishInsertImpl both call Base::finishInsertImpl (:327, :408), and ExactNotContainsRuntimeFilter declares no override, inheriting it directly. SharedFixedHashTableRuntimeFilter::finishInsertImpl is an empty body (RuntimeFilterLookup.h:351) and its findImpl delegates to a closure over the real join hash table, so it already uses the join's own semantics and is not a carrier. One guard covers the class.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes, and the wrapper matrix is measured and shipped in the test: Float64, Float32, BFloat16, LowCardinality(Float64), mixed Float32/Float64 supertype, Tuple(Float64, Int64), Array(Float64), Map(String, Float64), and Array(Tuple(Float64, Int64)) nested two deep. Both polarities and all three hash algorithms. The type test is isFloat, not isNativeFloat, which excludes BFloat16 (IDataType.h:412 vs :413), and mutation 1 reddens exactly the two BFloat16 rows, so that distinction is load-bearing rather than theoretical. Variant(Float64, String), Tuple containing Nullable(Float64), and LowCardinality(Nullable(Float32)) were each measured on the pristine build and were already correct there via the pre-existing NULL clause, so they are neither regressions nor new coverage and are deliberately not test rows. A JSON key is also a carrier and needed a second clause: its floats live in dynamic paths, which are not part of the static type, so forEachChild cannot see them (DataTypeObject.cpp:273-280 iterates only typed_paths). JSON and Tuple(JSON) reproduce in the signed-zero ANTI direction and are shipped as rows; JSON(a Float64) with the path declared was already covered by the plain walk, which mutation 5 confirms by reddening only the two dynamic-path rows. The NaN direction is unreachable for JSON: five spellings were tried and none stores a NaN in a JSON value.
h Backward compatible? (maintainer-approved exception only) Yes, nothing to migrate. No new setting and no default change, so no SettingsChangesHistory.cpp entry is required or added. No serialization or format change, no new validation over existing data. The only user-visible change is that previously wrong answers become right.
i Invariants and contracts preserved? Yes. The invariant is that the runtime filter must never reject a row the JOIN could match, which the fix restores. The guard can only turn ValuesCount::ONE into ValuesCount::MANY, and only for a float-bearing target type: it cannot reach the ZERO path, which returns earlier at :163-167, cannot change which filter class is constructed, since BuildRuntimeFilterTransform.cpp:48-83 decides that from allow_to_use_not_exact_filter_, and cannot affect a non-float type. MANY is the path every multi-value filter already takes, so no new state becomes reachable. The helper is pure, allocation-free, null-safe, and runs once per filter at build-finish, never on a per-row path. No locks, lifetimes, or error paths change.

Session id: cron:clickhouse-impl-slot-46:20260729-235600

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @antaljanosbenjamin @rschu1ze, could you review this? The join runtime filter's single-distinct-value fast path evaluated the filter as value == const (or != for ANTI), but the JOIN compares keys bitwise, so the filter dropped NaN rows from INNER results and -0.0 rows from LEFT ANTI results; the fix declines that fast path when the filter's target type contains a float at any nesting depth.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jul 30, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [cbd05c5]


AI Review

Summary

This PR fixes the one-distinct-value runtime-filter fast path so it no longer uses SQL equals/notEquals for float-bearing join keys, where that semantics can reject rows the JOIN itself would match under bitwise key identity. The guard is applied in the shared base used by the exact and approximate runtime filters, the helper covers nested float carriers and JSON, the new unit/stateless coverage exercises both the positive and negated paths, and the current Praktika report is all green. I did not find any blocking or major issues in the current diff.

Final Verdict

✅ No new findings.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 30, 2026
@PedroTadim

Copy link
Copy Markdown
Member

@groeneai again for NaN, -0,0, +0.0, -Inf and +Inf we can leave it as expected behavior. Update the docs from #112409

@groeneai

Copy link
Copy Markdown
Collaborator Author

Understood, I will not re-propose the code fix.

You already trimmed that paragraph in 35b643e and asked @ rschu1ze to re-check, so I will not re-expand it. Three measured points instead:

  • -Inf and +Inf need no text. Scalar and JOIN agree for both under all five algorithms, including at 50k probe rows where the runtime filter engages, and ASOF orders them fine.
  • -0.0 vs +0.0 is the only one of the five not covered, and it diverges the opposite way to NaN: the scalar comparison is 1, but hash, parallel_hash and grace_hash return no match while the two merge algorithms return one. Same on Float32 and Nullable(Float64).
  • The condensed text recommends ON if(isNaN(A.id), NULL, A.id) = B.id, which is the form the bot flagged in Document that a float NaN JOIN key can match NaN #112409 (comment). On a Nullable(Float64) key holding 1, NULL and NaN it matches 1 row where isNotDistinctFrom matches 3, so it drops the NULL = NULL match the section above promises. The removed AND NOT ifNull(isNaN(A.id), 0) variant keeps 2.

Happy to push a one-line correction for the last point if you want it.

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

Following up on the ruling above, because I hit the same value class in a different place and I
do not want to re-propose something you have already declined.

MergeTree primary-key index analysis and the runtime IN disagree about float set membership:
the runtime Set matches bitwise, so -0.0 and +0.0 are distinct members and two NaN
payloads are distinct members, while MergeTreeSetIndex orders the same set with
FloatCompareHelper, where -0.0 ties +0.0 and every NaN ties every other. On current
master:

SET optimize_use_implicit_projections = 0;
SET optimize_trivial_count_query = 0;

CREATE TABLE t (k Float64) ENGINE = MergeTree ORDER BY k
SETTINGS index_granularity = 1, add_minmax_index_for_numeric_columns = 0;
INSERT INTO t SELECT arrayJoin([toFloat64(-0.0), toFloat64(0.0), sqrt(-1.0::Float64), nan::Float64]);

SELECT count() FROM t;                       -- 4
SELECT count() FROM t WHERE k IN (0.0);      -- 1
SELECT count() FROM t WHERE k NOT IN (0.0);  -- 2   <-- 1 + 2 = 3, not 4

One row satisfies neither the predicate nor its negation. The same fixture with an ordinary value
adds up: k IN (7.0) is 0 and k NOT IN (7.0) is 4. Putting the same four rows in a table whose
ORDER BY does not include k gives 1 and 3, so it is index analysis, not the semantics of IN.
NOT has([sqrt(-1.0)], k) loses rows the same way.

I want to be clear about what I am not asking. Whether -0.0 IN (0.0) should be true or false
is a semantics choice and yours to make, and I accept the answer you already gave. My question is
narrower: is it acceptable for a row to be absent from both IN and NOT IN on the same table,
or should index analysis decline exactness when a float set holds a zero or a NaN?

If the latter, the mechanism already exists: out.relaxed in tryPrepareSetIndexForIn only
forces can_be_false = true, which is exactly the negated direction that is wrong here, and the
positive direction is already correct in every case I measured. That is a small change and no
IN or has result would move -- only pruning becomes conservative for sets that actually
contain one of these values. Sweeping all pairs of a 22-value float corpus, the two comparisons
disagree only on zeros and NaNs and never on ordinary values or infinities, so -Inf/+Inf
need nothing here.

If you would rather this stayed documented behavior too, that is a fine answer and I will treat
it as part of the same docs family rather than open a code PR.

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
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 pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants