Skip to content

Do not prune by a min/max range when a positive IN set holds NaN - #117453

Merged
alexey-milovidov merged 9 commits into
masterfrom
fix-in-nan-minmax-pruning-116927
Sep 20, 2026
Merged

alexey-milovidov merged 9 commits into
masterfrom
fix-in-nan-minmax-pruning-116927

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

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 to CHANGELOG.md):

Fixed WHERE f IN (nan) silently losing the NaN rows of a floating-point column: statistics-based part pruning and the minmax skip index use ranges that exclude NaN, so a part or granule holding NaN was pruned even though IN matches NaN.

Documentation entry for user-facing changes

IN matches NaN bit-exactly — SELECT nan IN (nan) is 1 — unlike a comparison, which is always false for NaN. But min/max-based pruning works with ranges produced by IColumn::getExtremes, which deliberately skips NaN, so a part or granule that holds NaN next to finite values gets a NaN-free range, the set-vs-range intersection finds no overlap, and it is pruned even though row-wise evaluation of the same filter matches those rows.

Both arms fire at pure default settings on a plain MergeTree table — automatic Basic statistics are materialized on INSERT and use_statistics_for_part_pruning defaults to 1:

CREATE TABLE s1 (k UInt64, f Float64) ENGINE = MergeTree ORDER BY k;
SYSTEM STOP MERGES s1;
INSERT INTO s1 SELECT number, if(number < 13, nan, 1.5) FROM numbers(100000);
INSERT INTO s1 SELECT number + 200000, 2.5 FROM numbers(1000);

SELECT count() FROM s1 WHERE f IN (nan);       -- 0, the truth is 13
SELECT count() FROM s1 WHERE f IN (nan, 2.5);  -- 1000, the truth is 1013

The fix for #113417 taught the statistics pruner to skip a floating-point column under a negating function, on the assumption that only a negation can make a floating-point predicate true for NaN. A positive IN is the counterexample: it is a set-membership test, not a comparison.

The guard goes into KeyCondition, which can inspect the elements: it declines the set atom only when the set really contains a NaN and a key column is floating-point. The atom serves every index at once, so declining it also forgoes the primary key for that predicate, which is the same trade has already makes for floating-point arrays. Statistics-based part pruning needs no exclusion of its own — it evaluates the estimates through a KeyCondition built with require_ready_sets, so an unbuilt subquery set is declined there and a ready set holding a NaN is declined by the new check, while a NaN-free set such as f IN (1.5) keeps pruning.

Closes: #116927
Related: #113417


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

Version info

  • Merged into: 26.10.1.300-master (included in 26.10 and later)

`IN` matches `NaN` bit-exactly - `SELECT nan IN (nan)` is `1` - unlike a
comparison, which is always false for `NaN`. But min/max-based pruning works
with ranges produced by `IColumn::getExtremes`, which deliberately skips
`NaN`, so a part or granule that holds `NaN` next to finite values gets a
`NaN`-free range, the set-vs-range intersection finds no overlap, and it is
pruned even though row-wise evaluation of the same filter matches those rows.

Both arms fire at pure default settings on a plain `MergeTree` table -
automatic `Basic` statistics are materialized on `INSERT` and
`use_statistics_for_part_pruning` defaults to `1`:

    CREATE TABLE s1 (k UInt64, f Float64) ENGINE = MergeTree ORDER BY k;
    SYSTEM STOP MERGES s1;
    INSERT INTO s1 SELECT number, if(number < 13, nan, 1.5) FROM numbers(100000);
    INSERT INTO s1 SELECT number + 200000, 2.5 FROM numbers(1000);

    SELECT count() FROM s1 WHERE f IN (nan);       -- 0, the truth is 13
    SELECT count() FROM s1 WHERE f IN (nan, 2.5);  -- 1000, the truth is 1013

The fix for #113417 taught the statistics pruner to skip a floating-point
column under a negating function, on the assumption that only a negation can
make a floating-point predicate true for `NaN`. A positive `IN` is the
counterexample: it is a set-membership test, not a comparison. It now skips
such a column too - whether the set actually holds a `NaN` is not knowable
there, since it may come from a subquery.

`KeyCondition` can inspect the elements, so it declines the set atom only
when the set really contains a `NaN` and a key column is floating-point. The
atom serves every index at once, so declining it also forgoes the primary key
for that predicate, which is the same trade `has` already makes for
floating-point arrays.

Closes: #116927
Related: #113417
@clickhouse-gh

clickhouse-gh Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c79438d]

Summary: ❌

job_name test_name status info comment
Build profile diff ERROR

AI Review

Summary

This PR fixes the real scalar floating-point IN (...nan...) mis-pruning in both statistics-based part pruning and minmax/primary-key range checks, and the updated test now covers the restored NaN-free statistics path. One regression remains: the new NaN guard also disables sound pruning for array-typed keys, where the carrier's range generation already preserves NaN ordering instead of dropping it.

Findings

⚠️ Majors

  • [src/Storages/MergeTree/KeyCondition.cpp:2851] fieldContainsNaN now descends into Array, so setElementsContainNaN rejects IN / NOT IN atoms for keys such as Array(Float64) and Tuple(Array(Float64)) whenever the set contains a NaN. That is broader than the actual bug: ColumnArray::getExtremes picks whole-array minima/maxima via compareAt, and Field equality for arrays keeps NaN consistent too, so these carriers were already safe. The new guard therefore turns previously sound primary/minmax pruning into unknown and regresses those queries to extra reads. Suggested fix: restrict the check to carriers whose getExtremes can really drop NaN, and add a focused regression over an array-typed key.
Final Verdict

Status: ⚠️ Request changes
Minimum required actions:

  • Narrow the NaN guard so it does not reject safe array-carried float values.
  • Add a regression that proves pruning still works for an Array(Float64) key with ... IN (...nan...).

LLVM Coverage Report

Measured on commit c79438d.

Metric Baseline Current Δ
Lines 88.40% 88.40% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 80.60% 80.70% +0.10%

Changed lines: Changed C/C++ lines covered: 32/37 (86.49%) · Uncovered code

Full report · Diff report

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

clickhouse-gh Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing commit c79438d7ebe6b4f948f9f662dc31bfbd6b56c6df with master failed: RuntimeError: CI logs cluster query failed: SELECT file, countIf(side = 'pr') AS pr_cou….

See the job log for details.

@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 4, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 7, 2026
…e transform

Both changes are review asks.

`fieldContainsNaNAnywhere` was a private copy of a walk `MergeTreeData.cpp` already had as
`containsOrderInconsistentValue`, differing only in its predicate. Walking `Array`, `Tuple`, `Map` and
`Object` is a property of the value, not of key analysis, so the walk moves to `Field` as
`anyFieldSatisfies(field, predicate)`, next to `isNaNField`, and both call sites go through it: key
analysis passes `isNaNField`, the minmax bound check passes `isNull() || isNaNField()`. Only a
declaration is added to `Field.h`; the body lives in `Field.cpp`, where it keeps the explicit worklist
of its neighbours (`Field::destroyContainerIteratively`, the copy constructor) because a bound read
from a part is not depth-bounded by the parser. The claim that a recursive walk overflows the stack is
gone from the comment.

`applyDeterministicDagToColumn` did two jobs: it converted the constant to the type the transform
consumes, which is where a NaN is born, and then applied the transform, so its caller could not see
the converted value and received it through a `bool *` out-parameter. It is now composed of
`convertColumnForDeterministicDag` and `executeDeterministicDag`, with its two lambdas as
`finalizeTransformedColumn` and `castColumnWithoutNulls`.
`canConstantBeWrappedByDeterministicFunctions` calls the two steps in turn and checks the single
converted `Field` between them, so both the out-parameter and the loop that turned column rows back
into `Field`s for a one-row constant are gone. The `IN` path still calls the composed wrapper, and can
adopt the same check when ClickHouse#117453 lands.

The direct-CAST fast path converts and transforms in one step, so it exposes no intermediate value to
check. Skipping it there costs nothing: `FunctionCast` (`FunctionsConversion.h:4963`) does not override
`isInjective`, so it inherits `false` from `IFunctionBase::isInjective` (`IFunction.h:263`) and an atom
over that path is not exact either way. This is what the removed out-parameter reported.

Behaviour is unchanged. The 31-probe carrier matrix is byte-identical to the published head's, and
05055_key_condition_nan_normalized_constant, 04950_minmax_count_projection_unusable_bound,
02982_minmax_nan_null_order, 00944_minmax_nan, 00944_minmax_null,
01710_minmax_count_projection_count_nullable, 03913_minmax_statistics_nan_ubsan_error,
04306_keycondition_nan_equality and 04401_key_condition_is_not_distinct_from all match their
references.
alexey-milovidov and others added 2 commits September 10, 2026 08:27
…runing-116927

# Conflicts:
#	src/Storages/MergeTree/KeyCondition.cpp
Address review: the statistics-side exclusion was widened to every
positive set-membership function, which dropped the floating-point column
from `StatisticsPartPruner` as soon as an `IN` mentioned it. That regressed
safe queries such as `f IN (1.5)`: the column was never considered for
part pruning, so the whole part was read.

The exclusion is not needed there. `StatisticsPartPruner` checks the
estimates through a `KeyCondition` built with `require_ready_sets`, so an
unbuilt subquery set is already declined, and
`KeyCondition::tryPrepareSetIndexForIn` now declines a ready set whose
elements contain a `NaN`. The predicate then becomes unknown for every
range-based check at once, which is exactly the guard the bug needs, while
a `NaN`-free set keeps pruning.

Narrow the statistics-side exclusion back to the negation family and cover
the safe path with `EXPLAIN indexes = 1` assertions for
`use_statistics_for_part_pruning = 1`: `f IN (1.5)` still prunes the part
that holds only `2.5`, and `f IN (nan)` has no `Statistics` entry at all.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
alexey-milovidov and others added 3 commits September 10, 2026 18:34
clickhouse-test randomizes `use_statistics` and `materialize_statistics_on_insert`;
when the latter is `0`, the freshly inserted parts carry no `basic` statistics,
so the `EXPLAIN indexes = 1` checks for a `NaN`-free set found no `Statistics`
entry and no `Parts: 1/2` line. Both runs of the flaky check that failed had
`--materialize_statistics_on_insert False`. The test now pins both settings.

The test is also renumbered from `05094` to `05227`, the current tail.

CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117453&sha=3f1749f7dd545274da9082df52129fddab022a7e&name_0=PR&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20flaky%20check%29
PR: #117453

Co-Authored-By: Claude Fable 5.1 <[email protected]>
return true;
}

if (field.getType() == Field::Types::Array)

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.

This array recursion is too broad. The IN/range mismatch only exists when the carrier's getExtremes drops NaN, but ColumnArray::getExtremes does not do that: it picks whole array rows via compareAt, and compareAt already has a defined NaN ordering. Set::execute is also hash-based over the nested elements, so Array(Float64) (and Tuple(Array(Float64))) still agrees with the range check even when a set element contains NaN.

By descending into Field::Types::Array here, setElementsContainNaN now declines those safe carriers and turns previously sound primary/minmax pruning into unknown for any ... IN (...nan...) over an array-typed key. Please keep the guard to the carriers whose range generation actually strips NaN, and add a focused regression on an Array(Float64) key so this does not silently become a pruning slowdown.

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

Tolerable.

@alexey-milovidov alexey-milovidov self-assigned this Sep 20, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 20, 2026
Merged via the queue into master with commit b813390 Sep 20, 2026
175 of 177 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-in-nan-minmax-pruning-116927 branch September 20, 2026 20:53
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 20, 2026
@clickhouse-gh clickhouse-gh Bot added comp-key-condition Analysis of a filter against a key. KeyCondition turns a WHERE condition into ranges over the pri... and removed comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-key-condition Analysis of a filter against a key. KeyCondition turns a WHERE condition into ranges over the pri... 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.

Positive IN (nan) silently loses NaN rows: statistics part pruning and minmax skip index use NaN-free ranges

2 participants