Repository navigation
Do not prune by a min/max range when a positive IN set holds NaN - #117453
Conversation
`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
|
Workflow [PR], commit [c79438d] Summary: ❌
AI ReviewSummaryThis PR fixes the real scalar floating-point Findings
Final VerdictStatus:
LLVM Coverage ReportMeasured on commit c79438d.
Changed lines: Changed C/C++ lines covered: 32/37 (86.49%) · Uncovered code |
Build profile diff (arm_release)Comparing commit See the job log for details. |
…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.
…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]>
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) |
There was a problem hiding this comment.
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.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes to CHANGELOG.md):
Fixed
WHERE f IN (nan)silently losing theNaNrows of a floating-point column: statistics-based part pruning and theminmaxskip index use ranges that excludeNaN, so a part or granule holdingNaNwas pruned even thoughINmatchesNaN.Documentation entry for user-facing changes
INmatchesNaNbit-exactly —SELECT nan IN (nan)is1— unlike a comparison, which is always false forNaN. But min/max-based pruning works with ranges produced byIColumn::getExtremes, which deliberately skipsNaN, so a part or granule that holdsNaNnext to finite values gets aNaN-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
MergeTreetable — automaticBasicstatistics are materialized onINSERTanduse_statistics_for_part_pruningdefaults to1: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 positiveINis 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 aNaNand 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 tradehasalready makes for floating-point arrays. Statistics-based part pruning needs no exclusion of its own — it evaluates the estimates through aKeyConditionbuilt withrequire_ready_sets, so an unbuilt subquery set is declined there and a ready set holding aNaNis declined by the new check, while aNaN-free set such asf IN (1.5)keeps pruning.Closes: #116927
Related: #113417
Workflow [PR]
Sync PR [sync-upstream/pr/117453]
Version info
26.10.1.300-master(included in26.10and later)