Repository navigation
Conversation
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]>
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.
Severity: ❌ blocker, Session id: cron:clickhouse-review-slot-10:20260730-002100 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-46:20260729-235600 |
|
cc @antaljanosbenjamin @rschu1ze, could you review this? The join runtime filter's single-distinct-value fast path evaluated the filter as |
|
Workflow [PR], commit [cbd05c5] AI ReviewSummaryThis PR fixes the one-distinct-value runtime-filter fast path so it no longer uses SQL Final Verdict✅ No new findings. |
|
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:
Happy to push a one-line correction for the last point if you want it. |
|
Following up on the ruling above, because I hit the same value class in a different place and I
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 4One row satisfies neither the predicate nor its negation. The same fixture with an ordinary value I want to be clear about what I am not asking. Whether If the latter, the mechanism already exists: If you would rather this stayed documented behavior too, that is a fine answer and I will treat |
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
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixes wrong results in
JOINon floating-point keys when the join runtime filter's build side has exactly one distinct value. The single-value fast path compared keys withequals/notEqualsinstead of the bitwise key identity theJOINitself uses, so rows withNaNkeys were dropped fromINNER JOINresults and rows with-0.0keys were dropped fromLEFT ANTI JOINresults.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,
finishInsertImpltakes a fast path evaluating the filter asvalue == const, orvalue != constfor ANTI, instead of a set lookup. TheJOINcompares keys bitwise viabitEqualsinHashTable.h, and SQL comparison disagrees with that on floats in both directions:nan = nanis false while the two bit patterns are the same key, so the positive filter drops a row theJOINwould have matched.0.0 = -0.0is true while the keys differ, so the negated filter drops a row belonging in theLEFT ANTI JOINoutput. NoNaNis involved in this one.Both return silently wrong results on default settings:
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
Setpath, which is byte-wise and already agrees with theJOIN. This mirrors the!argument_can_have_nullsclause on the same line, and keeps the optimization for every type where it is sound. The type test usesisFloat, notisNativeFloat, which would excludeBFloat16, and walks the type tree withIDataType::forEachChild, coveringTuple,Array,MapandArray(Tuple(...))keys. AJSONkey declines outright: its dynamic paths are not in the static type, so a float in one cannot be ruled out.Nullablekeys 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
isNativeFloatand covers neither signed zero norJSON.New test
04653_join_runtime_filter_float_key_identity: 37 rows, of which 18 return0before the fix and1after; the other 19 are unchanged controls. Carriers:Float64,Float32,BFloat16,LowCardinality(Float64), mixed widths, multi-keyINNERandLEFT ANTIoverTuple(Float64, Int64),Array(Float64),Map(String, Float64),Array(Tuple(Float64, Int64)),JSONandTuple(JSON), and the three hash algorithms. Controls:Nullable(Float64),Decimal64(2)andInt64keys keep the fast path, and-0.0 INNER JOIN 0.0andnan LEFT ANTI JOIN nanstay empty, since there the filter was too permissive rather than too strict and theJOINrejects 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
Int64andDecimal64keys while every SQL row still passed.Liveness:
Logtables so the probe-size cutoff cannot suppress the filter even at its default;EXPLAIN PLANandRuntimeFilterRowsCheckedassertions per planner branch that the filter is present and actually ran; andquery_plan_join_swap_tablepinned, 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.