Repository navigation
Fix skip indexes and part pruning dropping rows that hold a NaN under a negated float comparison - #107074
Conversation
…r negated float ranges Two related data-skipping bugs let MergeTree drop rows that match a negated float comparison, producing silent wrong results (issues ClickHouse#106533 and ClickHouse#106948). 1. KeyCondition negation rewrite (issue ClickHouse#106533). cloneDAGWithInversionPushDown rewrites not(comparison) via the inverse_relations map, e.g. not(greater(x, c)) into lessOrEquals(x, c). This algebraic identity is invalid under IEEE-754 when an operand can be NaN: not(NaN > c) is true while NaN <= c is false. Partition and primary-key pruning then evaluated the wrong condition and dropped the partition/granule where the value is NaN (e.g. sqrt(-1)). Skip the rewrite for the six comparison ops when an operand is a non-constant float column or a NaN constant; the trailing not() wrapper preserves correct semantics. Finite float constants and non-float types are unaffected. 2. minmax skip index loses NaN in mixed granules (issue ClickHouse#106948). The aggregator computes a granule's extremes with ColumnVector::getExtremes, which skips NaN (correct for SELECT min()/max()). A granule mixing finite values with NaN, e.g. [1.0, nan, 3.0], therefore stores the clean range [1.0, 3.0] with no trace of the NaN, so range analysis prunes it under a negated comparison even though the NaN row matches. NaN sorts after +inf in ClickHouse order, so the granule's true upper bound is NaN: detect any NaN in the granule slice and store NaN as the max, which trips the existing NaN guard in KeyCondition::checkInHyperrectangle. Widening a stored range can only cause conservative keeps, never wrong skips, so positive-range pruning is unaffected (a NaN granule is still pruned for val < 0, val > 500, etc.). Fix 1 covers the all-NaN granule; fix 2 covers the mixed one. Both bugs are regressions since v26.3. Adds regression tests covering partition pruning (04328) and the minmax skip index for all-NaN and mixed granules (04327). Closes: ClickHouse#106533 Closes: ClickHouse#106948 Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate
Validated on debug build of master |
|
cc @CurtizJ @KochetovNicolai — could you review this? It fixes two NaN data-skipping wrong-result bugs (#106533 partition pruning, #106948 minmax skip index): the |
|
Workflow [PR], commit [70ce784] Summary: ✅
AI ReviewSummaryThis PR weakens Final Verdict
LLVM Coverage ReportMeasured on commit 70ce784.
Changed lines: Changed C/C++ lines covered: 100/109 (91.74%) · Uncovered code |
Addresses two cases the initial minmax NaN fix missed (both wrong-result data-skipping bugs surfaced in review of ClickHouse#107074): 1. LowCardinality(Float*) / LowCardinality(Nullable(Float*)): the aggregator ran getExtremes and the NaN check on the LowCardinality column directly, whose ColumnLowCardinality::getExtremes materializes and delegates to the nested float. columnSliceHasNaN never unwrapped LowCardinality, so a mixed LC granule like [1.0, nan, 3.0]::LowCardinality(Float64) stored a finite [min, max] and reported no NaN, leaving the same wrong-skip this fix targets for plain Float. Now the column is materialized with convertToFullColumnIfLowCardinality before both the extremes computation and the NaN detection. 2. Nullable(Float*) granule containing both NULL and a non-null NaN: ColumnNullable::getExtremesNullLast records a NULLS_LAST +inf sentinel in field_max to remember the granule has NULL. The NaN-widening overwrote that sentinel with NaN, so a granule like (NULL, nan, 1.0) was stored as [1.0, NaN] instead of [1.0, +inf]; KeyCondition then evaluated isNull(val) against the non-null universe and could prune the granule that actually contains NULL. The widening is now skipped when field_max is the +inf sentinel (which keeps the granule under negated ranges anyway), preserving the NULL marker. The sentinel is the Null::PositiveInfinity value, so isPositiveInfinity() never matches a numeric +inf. Extends test 04327 with LowCardinality(Float64), LowCardinality(Nullable(Float64)) and NULL+NaN-in-one-granule cases, and pins min_bytes_for_wide_part = 0 alongside index_granularity_bytes = 0 so the fixed granule layout does not emit a wide-part warning under randomized settings. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (fixup
|
| # | Question | Answer |
|---|---|---|
| a | Deterministic repro? | Yes. On ee966c80 (this PR's prior HEAD), a minmax index on LowCardinality(Float64) / LowCardinality(Nullable(Float64)) with a mixed granule [1.0, nan, 3.0] returns 3 for NOT ((val >= 0.) AND (val <= 3.)) vs 4 with use_skip_indexes=0; a Nullable(Float64) granule with (NULL, nan, 1.0) returns 0 for val IS NULL vs 1 with the index off. Both reproduce on demand (no randomization needed). |
| b | Root cause explained? | Yes. (1) columnSliceHasNaN and getExtremes ran on the raw column; ColumnLowCardinality::getExtremes materializes+delegates to the nested float, but the NaN check never unwrapped LC, so an LC granule stored a finite [min,max] and reported no NaN → wrong skip. (2) ColumnNullable::getExtremesNullLast writes a NULLS_LAST +inf sentinel into field_max to mark "granule contains NULL"; the NaN-widening overwrote that sentinel with NaN, so (NULL, nan, 1.0) was stored as [1.0, NaN] instead of [1.0, +inf] → KeyCondition evaluated isNull(val) against the non-null universe and pruned a granule that actually has NULL. |
| c | Fix matches root cause? | Yes. (1) Materialize the column with convertToFullColumnIfLowCardinality() before both the extremes computation and columnSliceHasNaN, and unwrap LC inside the helper too. (2) Skip the NaN-widening when field_max.isPositiveInfinity() (the Null::PositiveInfinity sentinel, never a numeric +inf): +inf already keeps the granule under negated ranges, and preserving it keeps isNull(val) correct. No symptom-guarding — the fix is at the aggregation site where the range is stored. |
| d | Test intent preserved / new tests added? | Yes. Extended 04327_106948_minmax_skip_index_nan with LowCardinality(Float64), LowCardinality(Nullable(Float64)), and a Nullable(Float64) granule holding both NULL and NaN (asserting IS NULL is not pruned, the negated range keeps the granule, and a positive range it cannot satisfy still prunes). Added min_bytes_for_wide_part = 0 next to index_granularity_bytes = 0 so the pinned granule layout doesn't emit a wide-part warning under randomized settings. |
| e | Both directions demonstrated? | Yes. Without the fixup (ee966c80): LC=3, LCN=3, IS NULL=0 (all wrong). With the fixup (78903ada): LC=4, LCN=4, IS NULL=1, negated range=4, val > 500=0 — every use_skip_indexes result matches the use_skip_indexes=0 baseline. The original all-NaN/mixed-Float64 cases still pass; 00944_minmax_nan, 00944_minmax_null, 01016_null_part_minmax, and 04328 non-regress. |
| f | Fix is general, not a narrow patch? | Yes. The single materialization point covers Float32/Float64/BFloat16, Nullable, LowCardinality, and LowCardinality(Nullable(...)) uniformly (the helper checks all three float widths). The sentinel-vs-NaN distinction is handled at the one place the stored max is written. No symmetric site was left unpatched: the granule range is produced only in MergeTreeIndexAggregatorMinMax::update. |
Session id: cron:clickhouse-worker-slot-6:20260610-225430
The minmax skip index was made NaN-aware (a granule mixing finite floats with NaN stores its max as NaN so KeyCondition does not prune it under a negated comparison range its NaN rows satisfy). The part-level minmax index used by selectPartsToRead for partition/part pruning computed its hyperrectangle independently in IMergeTreeDataPart::MinMaxIndex::update and was not widened, so a part mixing finite floats with NaN (for example a nullable-float partition-key expression such as PARTITION BY isNull(val) with rows 1.0, nan, 3.0) stored a finite [min, max] and the whole part was pruned for NOT ((val >= 0) AND (val <= 3)) even though the NaN row satisfies the predicate. Extract the NaN-aware extremes calculation into getMinMaxIndexExtremes and call it from both the skip-index aggregator and the part-level index so the two keep identical NaN and NULL semantics. The NULLS_LAST +inf sentinel is preserved as before. Regression test in 04328 covers the part-level path with no explicit secondary index, asserting the part is kept for the negated range and still pruned by a positive range no value satisfies. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (commit f95a93d, part-level minmax NaN fix)
Non-regression: 00944_minmax_nan, 00944_minmax_null, 01016_null_part_minmax, 02982_minmax_nan_null_order, 04006_nullable_partition_minmax_merge, 04064_minmax_index_null_inf_ordering and the rest of the local minmax/partition-pruning family pass. Session id: cron:clickhouse-worker-slot-11:20260611-001600 |
The NaN granule's stored max is NaN, so an upper-bounded range conservatively reads it rather than pruning it; the previous comment claimed the granule was pruned. The result is unchanged (matches use_skip_indexes = 0), and a new EXPLAIN indexes = 1 assertion verifies that NaN-widening does not disable pruning entirely: the sibling all-finite granule [100, 200] is still pruned (Granules: 1/2). The countIf-over-EXPLAIN form keeps the assertion stable under settings randomization. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (fixup 0dbeabc — test pruning-claim correction)This fixup addresses the review comment that the
Session id: cron:clickhouse-worker-slot-5:20260611-045200 |
After NaN-widening, a part/granule whose stored max becomes NaN (or whose range carries the NULLS_LAST +Inf sentinel) is read conservatively for an upper-bounded range like val > 500, not pruned: KeyCondition::checkInHyperrectangle keeps intersects = true and only forces contains = false. The earlier comments claimed such parts/granules are still pruned, which is wrong. 04328: the single mixed part [1, nan, 3] is conservatively read (assert no Parts: 0/1). To still show that NaN-widening does not disable part-level pruning, a separate single-part all-finite table is pruned for val > 500 (assert Parts: 0/1). Two single-part tables keep the assertion merge-stable; a sibling part in the same partition would merge and collapse Parts: 1/2. 04327 NULL+NaN block: the NULL+NaN granule's stored range is [1, +Inf], so it is conservatively read while the sibling all-finite granule [100, 200] is pruned (assert Granules: 1/2). Skip-index granule pruning survives merges, so this assertion is merge-stable as written. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (fixup 3407618 — test-comment/assertion corrections on 04327 + 04328)
Session id: cron:clickhouse-worker-slot-3:20260611-053800 |
The minmax NaN-widening unwrapped LowCardinality but trusted ColumnSparse::getExtremes. The part-level minmax (IMergeTreeDataPart::MinMaxIndex::update) runs before sparse removal, and sparse blocks also arrive from sparse input or INSERT ... SELECT. For a sparse Float64 column whose part mixes finite values with NaN (e.g. [1, nan, 3]), ColumnSparse::getExtremes delegates to the values column and ColumnVector skips NaN, while columnSliceHasNaN only unwrapped LowCardinality and returned false. The part-level minmax then stored a finite [min, max] and could still prune NOT ((val >= 0) AND (val <= 3)), dropping the NaN row that satisfies it. Use convertToFullIfNeeded() in both getMinMaxIndexExtremes and columnSliceHasNaN. It strips Const, Replicated, Sparse and LowCardinality and recurses into subcolumns while preserving the top-level Nullable wrapper, so getExtremesNullLast and the NaN check see the nested float for every special representation, not just LowCardinality. Regression in 04328: a sparse Float64 part mixing finite floats with NaN must not be pruned for the negated range. use_statistics_for_part_pruning = 0 isolates the part-level minmax from the auto-statistics pruner (which use_skip_indexes = 0 does not disable).
Pre-PR validation gate (fixup a6aee30 — sparse-column NaN materialization)
Session id: cron:clickhouse-worker-slot-9:20260611-064200 |
The `Basic` and auto-statistics arms had the same gap the `minmax` arm just lost: both queried only a negated predicate, so `collectFloatColumnsUnderNegation` dropped `val` and neither reached `getKeyConditionForEstimates`. Measured on the same pair of builds: `val IN (nan)` returns 1 with the relaxation call and 0 without it on both, so all three implementations now exercise it. `statisticsHasMinMax` accepts `Basic` for any type represented by a number, so the `Float32 STATISTICS(basic)` arm and the `auto_statistics_types` arm feed the pruner the same NaN-free bounds the `minmax` arm does.
Their `IN (nan)` count alone reads the same as a full scan, so it could hold with the pruner never engaging at all. The finite `IN (150.)` part-count assertion the explicit `minmax` arm already carries pins that the pruner does use the set on these two fixtures as well: measured 1 on both.
…ng-minmax-keycondition
|
🕵 Merged The public CI at the previous head The one remaining red is That is the database-wide The fix #121134 ( |
…laxation The `val IN (nan)` arms added in the previous pass no longer reach `StatisticsPartPruner::getKeyConditionForEstimates`'s call to `relaxAtomsOverNaNHidingColumns`: master's `setElementsContainNaN` now declines a prepared set as soon as one of its elements is a `NaN`, so the atom is already unknown before the relaxation runs, and the assertions stayed green with the call deleted. Replace them with `sign(-val) = 1`, a chain of two monotonic functions over a column that is not under a negation, so it stays in the statistics map. Part 1's stored bounds are `[1, 3]`, which the chain maps to `sign([-3, -1]) = [-1, -1]`, so the atom reads as definitely false and the part is pruned - while row-wise `sign(-nan)` is `sign(nan)`, which is `1` and matches the hidden `NaN` row. Measured on two builds differing only in that call, for all three statistics implementations in the file (`auto_statistics_types = 'minmax'`, `Float32 STATISTICS(basic)`, and `auto_statistics_types = 'basic, uniq_v2'`): | | with the call | call deleted | |---|---|---| | `count()` for `sign(-val) = 1` | 1 | 0 | | `EXPLAIN indexes = 1` | `Parts: 2/2` | `Parts: 0/2` | The finite `IN (150.)` and `val < 10.` controls still assert `Parts: 1/2` on both builds, so no arm can pass by the pruner never pruning at all. The reference file is unchanged. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
🕵 Addressed the one unresolved review thread and pushed The bot was right that the They are now Measured on two builds differing only in that single call, for all three statistics implementations in the file (
The finite controls ( CI. The previous head |
CI finish ledger - a1dd6c8Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
Not caused by this PR, and the mechanism is absent rather than merely unlikely: this diff changes NaN The Session id: cron:our-pr-ci-monitor:20260921-113202 |
…ng-minmax-keycondition
|
🕵 Merged CI at the previous head The only two red rows are the I re-measured the noise floor directly from the
The flagged numbers are The mechanism is absent, not merely unlikely. This diff only weakens
The four arm shards that carry Related: #121090 |
…g tables New master test `04328_106533_partition_pruning_nan_inversion` (#107074) counts `EXPLAIN indexes = 1` lines: `Condition: (d in (-Inf` for the Decimal table and `Parts: 1/1` for the sparse table. The implicit minmax skip index on `d` / `val` adds one more matching line each (3 -> 4). Pin the setting on these two tables; the pruning results themselves are unchanged. https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=76867&sha=6d68d66456128c011fc04faba974a0609b47b253&name_0=PR&name_1=Fast%20test #76867 Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
… liveness probes to an integer key Add an `EXPLAIN indexes = 1` liveness probe with `use_statistics_for_part_pruning = 0` showing that `KeyCondition` still skips granules for `0 * k = 5`, and a matching check that it keeps every granule for `0 * k = 0` over a range ending at `+inf`. Also move the statistics liveness probes from the `Float64` table to a `UInt64` one: after #107074 the statistics pruner declines every function chain over a `Float` column (its min/max can hide a `NaN`), so the `Float64` probes could no longer report a `Statistics` entry on current master. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The float term in tryOptimizeTopK decides no answer, because buildIndexes refuses the same type afterwards, so deleting it left 04899 green. What the term does preserve is plan-based parallel replicas: a read chosen for TopK is kept local, and without the term a float sort column with dynamic filtering off is chosen and then gets no index. The new prdist arms use the EXPLAIN probe of 04838_pr_plan_based_top_k_filter. Deleting only the planner float term turns `prdist f64` from 1 to 0 and changes nothing else, and the pre-change test passes on that binary. The integer arm, which is chosen for TopK, reads 0, so the probe is able to. 04327 (from ClickHouse#107074) asserted TopK granule ordering on a Float64 minmax index (`Granules: 1/2`). This PR refuses float sort columns that ordering, since a stored bound cannot place a NaN where ORDER BY does: on master a column with leading all-NaN granules returns [nan,nan,nan] for ORDER BY v DESC LIMIT 3 instead of [9999,9998,9997]. The arm now asserts the refusal together with the threshold filter that still runs, so a change to the EXPLAIN format cannot turn it into a fake zero. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…runing_nan_negation` The `minmax` skip-index NaN defect (#106948) is fixed on master by #107074, so the test passes with the new default. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Closes: #106533
Closes: #106948
Related: #115151
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix a
minmaxskip index, asetskip index, part-level minmax pruning and statistics-based part pruning dropping rows that hold aNaNwhen the query negates a float comparison, for exampleWHERE NOT (val BETWEEN 0 AND 3). Closes #106533. Closes #106948.Description
getExtremesskipsNaN, so a granule holding(1.0, nan, 3.0)stores the finite bound[1.0, 3.0]. ANaNsatisfies no ordering comparison, soNOT (val <= 3)is true for that row, but range analysis over[1.0, 3.0]found the condition fully satisfied, so the enclosingNOTpruned the granule.The fix is at pruning time. After building each of the four conditions evaluated against a
getExtremes-derived hyperrectangle, atoms over a column that can hide aNaNare weakened withKeyCondition's existing mechanism:relaxedwhen onlycan_be_falseis unreliable, andFUNCTION_UNKNOWNwhen a hiddenNaNcan also make the atom true, i.e. a monotonic function chain or a set holding aNaN. Those two lose positive-direction pruning as well; every other positive predicate prunes as before. A primary-key column that can hide aNaNis instead left out of the part-minmax slot mapping, so mark-range analysis keeps the whole universe.This supersedes the earlier revision, which widened the stored maximum to
NaNat write time: other consumers read that field as a real extremum, soORDER BY val DESC LIMIT 1answered3instead of200andmax(val)answerednaninstead of3. Pruning-time marking also repairs pre-upgrade parts and drops the statistics file-format version that revision added.Fixed in passing: the
setskip index, which builds its bound identically, and aTuplekey column, including aNaNnested in anINset element. Not addressed, each unchanged from master and needing its own change: anArrayorMapbound, whose comparison orders aNaN; aNaNin the query constant against a key column that cannot hold one; Parquet row-group and page pushdown, plus the equivalent ORC and Hive paths; andconvert_query_to_cnf, which rewrites the negation upstream of index analysis.Workflow [PR]
Sync PR [sync-upstream/pr/107074]
Version info
26.10.1.462-master(included in26.10and later)