Skip to content

Fix NaN handling in accurateLess/accurateEquals for index range analysis - #98964

Merged
alexey-milovidov merged 10 commits into
masterfrom
fix-nan-pk-index-binary-search
Mar 16, 2026
Merged

alexey-milovidov merged 10 commits into
masterfrom
fix-nan-pk-index-binary-search

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Mar 7, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Fix FieldVisitorAccurateLess and FieldVisitorAccurateEquals to handle NaN correctly for float comparisons. They used plain IEEE 754 < and == which makes NaN incomparable, breaking Range::intersectsRange and Range::containsRange.
  • Use FloatCompareHelper with nan_direction_hint = 1, consistent with Field::operator< and ClickHouse's sort order where NaN is placed after all normal values.
  • This fixes a "Inconsistent KeyCondition behavior" exception in debug builds when the primary key index contains NaN values and the binary search path is used in markRangesFromPKRange.

AST fuzzer report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=744485a03e0c78561cc7f820e9b43decf2cea69d&name_0=MasterCI&name_1=AST%20fuzzer%20%28amd_debug%29

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

Fix exception "Inconsistent KeyCondition behavior" in debug builds when primary key contains NaN float values, by making accurateLess and accurateEquals handle NaN consistently with ClickHouse sort order. Closes #98075.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Note

Medium Risk
Changes comparison semantics for floating-point Field values (including cross-type comparisons) used in index range analysis, which can affect primary key range pruning and related query planning. Risk is moderate because it’s localized but touches core comparison logic and NaN edge cases.

Overview
Fixes NaN handling in FieldVisitorAccurateLess and FieldVisitorAccurateEquals by using FloatCompareHelper (with nan_direction_hint = 1) so NaNs have a consistent ordering/equality behavior during index range analysis.

Adds/updates regression tests to cover NaN values in primary-key indexes (including nullable and LowCardinality(Nullable(Float32))) and adjusts an existing NaN-with-fill expected output.

Written by Cursor Bugbot for commit f8c9aed. This will update automatically on new commits. Configure here.

Version info

  • Merged into: 26.3.1.725

alexey-milovidov and others added 2 commits March 6, 2026 21:45
…ey index contains NaN

NaN values in float primary key columns broke the binary search in
`markRangesFromPKRange` because `Range::intersectsRange` gives wrong
results for IEEE 754 NaN (NaN is incomparable - `x < NaN` returns
false for all x). This caused the binary search to incorrectly extend
the matching range into NaN territory, leading to a "Inconsistent
KeyCondition behavior" exception in debug builds.

The fix converts NaN values in the primary key index to
`POSITIVE_INFINITY` before passing them to `KeyCondition::checkInRange`,
similar to how NULL values are already converted. This is correct
because NaN is sorted after all normal float values in ClickHouse,
just like `POSITIVE_INFINITY` in `Range` comparison semantics.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=744485a03e0c78561cc7f820e9b43decf2cea69d&name_0=MasterCI&name_1=AST%20fuzzer%20%28amd_debug%29

Co-Authored-By: Claude Opus 4.6 <[email protected]>
…rkaround

Move the fix to the root cause: `FieldVisitorAccurateLess` and
`FieldVisitorAccurateEquals` used plain IEEE 754 `<` and `==` for
same-type float comparisons, which makes NaN incomparable (all
comparisons return false). This broke `Range::intersectsRange` and
`Range::containsRange` which rely on these functions.

Now use `FloatCompareHelper` with `nan_direction_hint = 1` (NaN at
the end), consistent with ClickHouse sort order and `Field::operator<`.

Revert the previous workaround in `MergeTreeDataSelectExecutor` that
converted NaN index values to `POSITIVE_INFINITY`.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Mar 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7429403]

Summary: ✅


AI Review

Summary

This PR fixes NaN handling for index range analysis by changing accurateLess and accurateEquals behavior and adding regression coverage in KeyCondition tests. However, the comparator change is global and affects non-index code paths; the updated 03239_nan_with_fill.reference shows a behavior change (SELECT 1 ORDER BY nan WITH FILL FROM 1 now emits an extra 0), which is a correctness regression outside the targeted fix.

Missing context

  • ⚠️ Full CI for this PR is still pending, so I cannot confirm whether additional regressions exist.

Findings

  • ❌ Blockers
    • [src/Common/FieldAccurateComparison.cpp:53,141] Global NaN ordering/equality changes in accurateLess and accurateEquals alter shared comparison semantics outside PK range analysis. This leaks into unrelated features (WITH FILL), evidenced by the changed expected output in tests/queries/0_stateless/03239_nan_with_fill.reference.
    • Suggested fix: keep shared accurateLess/accurateEquals semantics unchanged and introduce a dedicated NaN-aware comparator (or scoped flag/path) used only by key-range/index analysis.

Tests

  • ⚠️ Add/keep a regression test that explicitly guards WITH FILL behavior for ORDER BY nan to ensure index-range fixes do not change filling semantics.

ClickHouse Rules

Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ⚠️ User-visible behavior changed in WITH FILL output due to shared comparator semantics.
SettingsHistory.cpp ➖
Safe rollout ⚠️ Scope leak from index-specific fix into unrelated query behavior.
Compilation time ✅

Final Verdict

  • Status: ⚠️ Request changes
  • Minimum required actions:
    • Scope NaN-aware ordering/equality to index/range analysis code paths only.
    • Restore/freeze WITH FILL behavior (or justify intentional change with explicit design discussion and dedicated user-facing docs/tests).

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Mar 7, 2026

@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.

LGTM

The change to `accurateLess` makes NaN greater than all normal values
(consistent with ClickHouse sort order). This means `ORDER BY nan WITH
FILL FROM 1` now correctly generates a fill row at value 1 before the
NaN data row. The fill row's non-fill SELECT column gets its default
value (0).

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@PedroTadim

Copy link
Copy Markdown
Member

Closes #98075 ?

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Yes.

@nihalzp nihalzp self-assigned this Mar 7, 2026
alexey-milovidov and others added 6 commits March 8, 2026 19:32
…e/ClickHouse into fix-nan-pk-index-binary-search
…curateEquals`

The AST fuzzer found that when comparing integer values (e.g. UInt8
from `isNull`) against Float64 NaN values in the primary key index,
the cross-type comparison path in `FieldVisitorAccurateLess` and
`FieldVisitorAccurateEquals` delegated to `accurate::lessOp` /
`accurate::equalsOp` which return false for any NaN comparison.
This violates ClickHouse sort order where NaN is greater than all
normal values, causing "Inconsistent KeyCondition behavior" exception.

The previous fix only handled same-type float comparisons via
`FloatCompareHelper`. This commit extends NaN handling to the
cross-type arithmetic comparison path, and adds the fuzzer-found
`LowCardinality(Nullable(Float32))` test case to the regression test.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
…search path

The previous fix to `FieldVisitorAccurateLess`/`FieldVisitorAccurateEquals` was
insufficient. The root cause: when the key range left bound is NaN, all values
in the range are NaN (since NaN sorts last), so no SQL comparison condition can
be true. But `Range::intersectsRange` incorrectly returned true for NaN ranges,
because NaN has a defined position in ClickHouse's sort order (after +inf)
while SQL treats NaN as incomparable.

This caused the binary search in `markRangesFromPKRange` to include NaN marks
in the result range, then the exact range verification found `can_be_false=true`
(from the existing NaN workaround), triggering the "Inconsistent KeyCondition
behavior" assertion.

Fix: when `key_range.left.isNaN()`, also set `intersects = false` (not just
`contains = false`). Also revert the incorrect `03239_nan_with_fill.reference`
change since `WITH FILL` uses `Field::operator<`, not `accurateLess`.

Add fuzzer-found reproducer: `LowCardinality(Float32)` with identical PREWHERE
and WHERE conditions (`0 < col`) that triggers the binary search with exact
range verification.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Comment thread src/Common/FieldAccurateComparison.cpp Resolved
The `accurateLess` change makes NaN ordered (greater than all values),
which causes `WITH FILL FROM 1` to insert a fill row before the NaN row.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Mar 16, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 83.70% 83.70% +0.00%
Functions 23.90% 23.90% +0.00%
Branches 76.20% 76.30% +0.10%

PR changed lines: PR changed-lines coverage: 100.00% (44/44, 0 noise lines excluded)
Diff coverage report
Uncovered code

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Restore/freeze WITH FILL behavior (or justify intentional change with explicit design discussion and dedicated user-facing docs/tests).

The change is alright.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Mar 16, 2026
Merged via the queue into master with commit eea8ff0 Mar 16, 2026
159 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-nan-pk-index-binary-search branch March 16, 2026 21:17
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Mar 16, 2026
zlareb1 added a commit to zlareb1/ClickHouse that referenced this pull request Mar 17, 2026
…98964)

PR ClickHouse#98964 fixed `checkInHyperrectangle` in `KeyCondition.cpp` to handle NaN
correctly in index range analysis. The PR's own test (`04031`) uses
`index_granularity = 1`, so each value is in its own granule and the
`left.isNaN()` branch (first granule boundary) is hit for the NaN granule.

With `index_granularity = 8192` all values land in a single granule whose
right bound is NaN. This exercises the `key_range.right.isNaN()` branch at
`KeyCondition.cpp:4205` that was not covered by the PR's own test.

Also adds a `Nullable(Float32)` variant with NaN and NULL in the same granule.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
github-merge-queue Bot pushed a commit that referenced this pull request Mar 18, 2026
…e-coverage

Add NaN-in-PK index range test with multi-row granule (PR #98964)
@nihalzp nihalzp added the post-approved Approved, but after the PR is merged. label Mar 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

post-approved Approved, but after the PR is merged. 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.

Logical error: Inconsistent KeyCondition behavior (STID: 5182-684a)

4 participants