Skip to content

Stop PK-range join sharding at a key column that can hold a NaN - #118918

Merged
alexey-milovidov merged 1 commit into
masterfrom
fix-join-shard-by-pk-nan-117873
Sep 10, 2026
Merged

alexey-milovidov merged 1 commit into
masterfrom
fix-join-shard-by-pk-nan-117873

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 8, 2026 •

Copy link
Copy Markdown
Member

The PK-range join sharding (query_plan_join_shard_by_pk_ranges) splits the parts of both sides into layers by primary-key ranges and filters every layer with greater(tuple(pk), tuple(border)). An IEEE comparison answers false for NaN against anything, so a row with a NaN key fails the filter of every layer - including the last one, which only has a lower bound - and is dropped at read time. With a Float primary key holding NaN, SELECT count() FROM l INNER JOIN r ON l.k = r.k returned 1000 instead of 1025, and a LEFT JOIN lost the NaN rows of the left table entirely: the merge join's own comparator treats NaN as equal to NaN, so those rows do participate in the join without the optimization.

Every other consumer of splitIntersectingPartsRangesIntoLayers - the FINAL split, the distributed FINAL bucketing in ReadFromMergeTree and optimizeLazyFinal - already gates on isSafePrimaryKey, which rejects Float32/Float64/BFloat16, Nullable, and containers of those. The join path had no such check. Since it splits by a primary-key prefix, the check is applied per column while the common prefix is being computed: an unsafe column ends the prefix instead of disabling the optimization for the whole table, so a key like (id UInt64, x Float64) joined on id keeps sharding.

Closes: #117873

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):

Fixed rows being silently dropped from a join when query_plan_join_shard_by_pk_ranges is enabled and the primary key is a floating-point column containing NaN.


Workflow [PR]
Sync PR [sync-upstream/pr/118918]

Version info

  • Merged into: 26.9.1.1097 (included in 26.9 and later)

The layer split of `query_plan_join_shard_by_pk_ranges` filters every
layer with `greater(tuple(pk), tuple(border))`. An IEEE comparison
answers false for `NaN` against anything, so a row with a `NaN` key
fails the filter of every layer - including the last one, which only has
a lower bound - and is dropped at read time. With a `Float` primary key
holding `NaN` the join silently returned fewer rows: the merge join's
own comparator treats `NaN` as equal to `NaN`, so those rows do
participate in the join when the optimization is off.

Every other consumer of `splitIntersectingPartsRangesIntoLayers` gates
on `isSafePrimaryKey`, which rejects `Float32`/`Float64`/`BFloat16`,
`Nullable` and containers of those. The join path had no such check.
Since it splits by a primary key *prefix*, the check is applied per
column while the common prefix is computed: an unsafe column ends the
prefix, so a key like `(id UInt64, x Float64)` joined on `id` keeps
sharding.

`isSafePrimaryDataKeyType` moves out of the anonymous namespace of
`PartsSplitter.cpp` to be declared alongside `isSafePrimaryKey`.
@clickhouse-gh

clickhouse-gh Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d3b4605]

Summary: ✅


AI Review

Summary

This PR fixes the row-loss bug in query_plan_join_shard_by_pk_ranges by stopping PK-range join sharding at the first primary-key component whose type can carry NaN or similar unsafe values. The implementation path looks consistent, but the new regression coverage does not actually prove the distinctive contract introduced here: that an unsafe later PK component shortens the usable prefix instead of disabling sharding for the whole key.

Tests
  • ⚠️ [tests/queries/0_stateless/05159_join_shard_by_pk_ranges_float_nan.sql:30] The added control uses an all-UInt64 key, so it never exercises the new prefix-truncation behavior. If findCommonPrimaryKeyPrefixByJoinKey were changed to reject any PK that merely contains an unsafe later column, this PR would still pass. Please add a mixed key such as ORDER BY (id, x) joined on id, and pin the plan with an EXPLAIN / Sharding: assertion or another direct proof that the join is still sharded.
Final Verdict

⚠️ Needs a focused mixed-key regression test before merge.

LLVM Coverage Report

⚠️ No coverage measurement for commit d3b4605: incomplete coverage measurement: 1 of 21 shard profiles are missing: LLVM_COVERAGE_FILE_it_6.profdata.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 8, 2026
DROP TABLE t_join_shard_left;
DROP TABLE t_join_shard_right;

-- An integer key still shards: the same counts with the optimization on and off.

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.

The new behavior worth pinning here is not just that a fully safe key still returns the right rows; the existing query_plan_join_shard_by_pk_ranges tests already cover ordinary safe-key sharding. This UInt64 control would still pass if findCommonPrimaryKeyPrefixByJoinKey started rejecting any PK that merely contains a float in a later component, which is exactly the mixed-key regression this patch claims to avoid. Please replace or extend it with a mixed key such as ORDER BY (id, x) joined on id, and add an EXPLAIN / Sharding: assertion (or another direct plan-level proof) that the join is still sharded.

@clickhouse-gh clickhouse-gh Bot added the comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... label Sep 9, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 9, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing d3b4605d5 with master 9c307529d (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

119 translation units recompiled, 1273 s compile time in total, 119 of them have a recent master baseline.

Job report

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Trivial.

@alexey-milovidov alexey-milovidov self-assigned this Sep 9, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 9, 2026
Merged via the queue into master with commit 56dc742 Sep 10, 2026
174 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-join-shard-by-pk-nan-117873 branch September 10, 2026 02:15
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 10, 2026
pull Bot pushed a commit to admariner/ClickHouse that referenced this pull request Sep 23, 2026
…loat key

A join runtime filter is a pre-filter: the join re-evaluates its own condition
afterwards, so a filter that passes too many rows is harmless, while one that
rejects a row the join would have matched loses that row for good.

ExactSetRuntimeFilter::finishInsert replaced set membership with the SQL `equals`
function (`notEquals` for the negated, ANTI-join filter) as soon as the build
side collapsed to a single distinct key. Hash tables compare float keys bitwise,
deliberately, and `equals` does not agree with that: NaN is not equal to itself,
so the non-negated filter rejected NaN rows the join does match, and 0.0 equals
-0.0, so the negated filter rejected rows ANTI owed as non-matched. A plain inner
join on an all-NaN Float64 key returned no rows at stock defaults, and the
correlated scalar subquery in the linked issue came back NULL because the filter
had emptied the probe arm of the join it was decorrelated into.

Take the shortcut only where `equals` agrees with a bitwise comparison. The
predicate descends the key type, so it also covers a float inside Array, Tuple,
Map or LowCardinality, and it matches JSON at the root because a float can appear
on a path discovered while reading, which is not among the type's static
children.

Variant and Dynamic need no term: canContainNull is true for both, so the
adjacent !argument_can_have_nulls check already sends them to the Set path.
Measured, not assumed.

The same shape was used in ClickHouse#118918 for the sibling primary-key range sharding
NaN bug. Releases 26.7 and 26.8 carry the same shortcut, so this is not a
master-only regression.

Closes: ClickHouse#119679
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... pr-bugfix Pull request with bugfix, not backported by default 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.

PK-range join sharding silently drops rows when a Float primary key contains NaN (query_plan_join_shard_by_pk_ranges)

2 participants