Skip to content

Fix skip indexes and part pruning dropping rows that hold a NaN under a negated float comparison - #107074

Merged
alexey-milovidov merged 59 commits into
ClickHouse:masterfrom
groeneai:fix-nan-range-pruning-minmax-keycondition
Sep 22, 2026
Merged

alexey-milovidov merged 59 commits into
ClickHouse:masterfrom
groeneai:fix-nan-range-pruning-minmax-keycondition

Conversation

@groeneai

@groeneai groeneai commented Jun 10, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #106533
Closes: #106948
Related: #115151

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 a minmax skip index, a set skip index, part-level minmax pruning and statistics-based part pruning dropping rows that hold a NaN when the query negates a float comparison, for example WHERE NOT (val BETWEEN 0 AND 3). Closes #106533. Closes #106948.

Description

getExtremes skips NaN, so a granule holding (1.0, nan, 3.0) stores the finite bound [1.0, 3.0]. A NaN satisfies no ordering comparison, so NOT (val <= 3) is true for that row, but range analysis over [1.0, 3.0] found the condition fully satisfied, so the enclosing NOT pruned 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 a NaN are weakened with KeyCondition's existing mechanism: relaxed when only can_be_false is unreliable, and FUNCTION_UNKNOWN when a hidden NaN can also make the atom true, i.e. a monotonic function chain or a set holding a NaN. Those two lose positive-direction pruning as well; every other positive predicate prunes as before. A primary-key column that can hide a NaN is 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 NaN at write time: other consumers read that field as a real extremum, so ORDER BY val DESC LIMIT 1 answered 3 instead of 200 and max(val) answered nan instead of 3. Pruning-time marking also repairs pre-upgrade parts and drops the statistics file-format version that revision added.

Fixed in passing: the set skip index, which builds its bound identically, and a Tuple key column, including a NaN nested in an IN set element. Not addressed, each unchanged from master and needing its own change: an Array or Map bound, whose comparison orders a NaN; a NaN in the query constant against a key column that cannot hold one; Parquet row-group and page pushdown, plus the equivalent ORC and Hive paths; and convert_query_to_cnf, which rewrites the negation upstream of index analysis.


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

Version info

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

…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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. minmax index ON returns 0/wrong vs use_skip_indexes=0 returns 3/correct for the all-NaN granule, and 0 vs 1 for the mixed [1.0, nan, 3.0] granule, every run on master fc73f46. Partition-pruning half: count() WHERE NOT (sqrt(c0) > 10) on (1),(-1) returns 1/wrong vs 2/correct.
b Root cause explained? Two sites. (1) KeyCondition::cloneDAGWithInversionPushDown rewrites not(x > c) to x <= c via inverse_relations; invalid for NaN since not(NaN>c)=true but NaN<=c=false, so the partition/granule with NaN is dropped. (2) MergeTreeIndexAggregatorMinMax::update uses ColumnVector::getExtremes, which skips NaN, so a mixed granule stores [1.0,3.0] and hides the NaN, letting range analysis prune it under the negation.
c Fix matches root cause? Yes. (1) Skip the inverse_relations rewrite for the six comparison ops when an operand is a non-constant float column or NaN constant. (2) When a granule slice contains NaN, store NaN as the granule max (NaN sorts after +inf), tripping the existing right.isNaN() guard in checkInHyperrectangle. No widening of assertions or blanket tags.
d Test intent preserved / new tests added? New tests 04327 (minmax skip index: all-NaN + mixed granule + positive-range-still-prunes + equality-on-NaN-granule) and 04328 (partition pruning). Existing 00944_minmax_nan, 00944_minmax_null, 01016_null_part_minmax still pass unchanged.
e Demonstrated both directions? Yes. Both new tests FAIL on master HEAD and PASS with the fix. Isolated each fix: minmax-only leaves the all-NaN case broken; KeyCondition-only leaves the mixed granule broken; both together fix all cases. Confirmed on the real server path (force_data_skipping_indices='idx_val' returns the correct 4, proving the index is used, not bypassed).
f Fix is general, not a narrow patch? Yes. columnSliceHasNaN covers Float32/Float64/BFloat16 and the Nullable wrapper. Both pruning sites that consume KeyCondition (partition pruning and the minmax skip index) are covered. Widening a minmax range is correctness-safe (only conservative keeps, never wrong skips), verified: NaN granules are still pruned for val < 0, val > 500. The bad state is fixed at its origin (the rewrite site and the aggregator), not at the symptom.

Validated on debug build of master fc73f46. Session: cron:clickhouse-worker-slot-0:20260610-193410

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @CurtizJ @KochetovNicolai — could you review this? It fixes two NaN data-skipping wrong-result bugs (#106533 partition pruning, #106948 minmax skip index): the KeyCondition negation rewrite not(x>c) -> x<=c is invalid for NaN, and MergeTreeIndexAggregatorMinMax loses NaN in mixed granules because getExtremes skips it. This supersedes #106568 (which fixed only the partition-pruning half of #106533).

@clickhouse-gh

clickhouse-gh Bot commented Jun 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [70ce784]

Summary: ✅


AI Review

Summary

This PR weakens KeyCondition atoms in the minmax, set, part-level minmax, and statistics-pruning paths so negated float comparisons do not prune away rows that carry NaN, and it adds focused stateless coverage for those paths. On the current head I did not find any new live correctness, compatibility, or safety issues in the claimed scope; the earlier bot findings are either fixed in the current code or explicitly documented by the author as out of scope for this change.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit 70ce784.

Metric Baseline Current Δ
Lines 88.00% 88.00% +0.00%
Functions 91.70% 91.80% +0.10%
Branches 79.30% 79.30% +0.00%

Changed lines: Changed C/C++ lines covered: 100/109 (91.74%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 10, 2026
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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (fixup 78903ada addressing the review of ee966c80)

# 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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (commit f95a93d, part-level minmax NaN fix)

# Question Answer
a Deterministic repro? Yes. CREATE TABLE t (id UInt64, val Nullable(Float64)) ENGINE = MergeTree PARTITION BY isNull(val) ORDER BY id SETTINGS min_bytes_for_wide_part = 0; INSERT INTO t VALUES (1, 1.0), (2, nan), (3, 3.0); SELECT count() FROM t WHERE NOT ((val >= 0.) AND (val <= 3.)); returns 0 on the pre-fix binary every time (EXPLAIN indexes=1 shows the part-level Min-Max index with Parts: 0/1).
b Root cause explained? getExtremes/getExtremesNullLast skip NaN, so IMergeTreeDataPart::MinMaxIndex::update stored a finite [1, 3] for a part mixing finite floats with NaN. selectPartsToRead feeds that hyperrectangle to KeyCondition::checkInHyperrectangle; the rewritten or((val in (3,+Inf)), (val in (-Inf,0))) finds [1,3] disjoint from both, so the whole part is pruned, even though the NaN row satisfies the negation. The part-level path is independent of the skip-index aggregator fixed earlier in this PR.
c Fix matches root cause? Yes. The NaN-aware extremes logic is factored into getMinMaxIndexExtremes and called from both the skip-index aggregator and MinMaxIndex::update. A NaN in the slice widens the stored max to NaN, which trips the existing right.isNaN() guard in checkInHyperrectangle so the part is kept. The NULLS_LAST +inf sentinel is preserved (no overwrite when max is already +inf).
d Test intent preserved / new tests added? New regression in 04328_106533_partition_pruning_nan_inversion exercising the part-level path with NO explicit secondary index: asserts the part is kept for the negated range (oracle: use_skip_indexes = 0) and still pruned by a positive range no value satisfies (val > 500). No existing test weakened.
e Both directions demonstrated? Yes. Pre-fix snapshot binary: idxON=0 (WRONG) vs use_skip_indexes=0 oracle=1. Post-fix: idxON=1=oracle. Positive-range pruning still works (idxON=0=oracle for val > 500).
f Fix is general, not a narrow patch? Yes. This addresses the sibling code path flagged by the reviewer: the same hidden-NaN invariant existed in the part-level minmax separately from the skip index. The shared getMinMaxIndexExtremes ensures both paths keep identical NaN/NULL semantics. One remaining manifestation (pre-fix on-disk .idx2 files read after upgrade) is a format-versioning question raised separately in the review thread and deferred to the MergeTree owners rather than changing the on-disk format unilaterally.

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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (fixup 0dbeabc — test pruning-claim correction)

This fixup addresses the review comment that the val > 500 pruning claim in 04327_106948_minmax_skip_index_nan.sql was unverified. No source change in this commit.

# Question Answer
a Deterministic repro? Yes. EXPLAIN indexes = 1 SELECT count() FROM t_minmax_nan_mixed WHERE val > 500 deterministically shows Granules: 1/2 on the fixed binary: the [1, NaN] granule is kept (conservatively read), only the finite [100, 200] granule is pruned. The prior comment claimed the NaN granule was pruned, which EXPLAIN contradicts.
b Root cause explained? The NaN-widening stores the mixed granule's max as NaN; KeyCondition::checkInHyperrectangle forces contains = false whenever the right bound is NaN, so an upper-bounded range like val > 500 conservatively READS that granule instead of pruning it. The old test comment asserted the opposite (pruned), so the documented contract was wrong even though the result row count happened to match.
c Fix matches root cause? Yes. The comment now states the NaN granule is conservatively read, and the new assertion verifies the actual contract worth holding: NaN-widening does not disable pruning entirely, the sibling all-finite granule is still pruned (Granules: 1/2).
d Test intent preserved / new tests added? Strengthened. The test now asserts the index behaviour directly via EXPLAIN indexes = 1, not just the final result, closing the gap the reviewer identified. The original result-count assertions are unchanged.
e Both directions demonstrated? Yes. With the full fix the test passes; on the pre-fix master snapshot binary the .reference differs (the negated-range and mixed-granule rows are wrong), so the test catches the regression. The new EXPLAIN-subquery line returns 1 only when pruning still partially works.
f Fix is general, not a narrow patch? N/A for this fixup (test-only correction). The two open code-path concerns from this review round (pre-upgrade .idx2 skip-index reads and pre-upgrade part-level .idx reads) are tracked together on their threads, pending the owners' on-disk-format-versioning decision; both will be solved with one consistent conservative-read/versioning approach.

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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (fixup 3407618 — test-comment/assertion corrections on 04327 + 04328)

# Question Answer
a Deterministic repro? Yes. EXPLAIN indexes = 1 SELECT count() ... WHERE val > 500 is deterministic. 04328 NaN part: countIf(... 'Parts: 0/1' ...) = 0 (conservatively read); separate finite part: = 1 (pruned). 04327 NULL+NaN: countIf(... 'Granules: 1/2' ...) = 1.
b Root cause explained? After NaN-widening, a part/granule whose stored max is NaN (or whose range carries the NULLS_LAST +Inf sentinel) has KeyCondition::checkInHyperrectangle keep intersects = true for val > 500; only contains is forced false. So it is read conservatively, not pruned. The old comments claimed such parts/granules are pruned, which is wrong.
c Fix matches root cause? Yes. Comments now state conservative read; assertions check the real EXPLAIN indexes = 1 contract (the NaN/NULL part-or-granule is read, the sibling all-finite one is pruned). No production code touched.
d Test intent preserved / new tests added? Yes. Both still verify indexed result == unindexed result, AND now additionally assert that NaN-widening does not disable pruning entirely (the all-finite part/granule is still pruned). Stronger than before.
e Both directions demonstrated? Yes. Verified via clickhouse local end-to-end: both .sql files match their .reference exactly. Assertions confirmed stable across compact/wide parts, index_granularity 1/8192, and across OPTIMIZE FINAL merges.
f Fix is general, not a narrow patch? N/A for production code (test-only fixup). The same conservative-read contract is now asserted in both affected spots: the 04328 part-level test and the 04327 NULL+NaN block, matching the assertion already on the 04327 mixed-finite block. Made 04328 merge-stable (two single-part tables) rather than a same-partition sibling that would merge and break a Parts: 1/2 assertion.

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (fixup a6aee30 — sparse-column NaN materialization)

# Question Answer
a Deterministic repro? Yes. CREATE TABLE t (id UInt64, val Float64) ENGINE = MergeTree PARTITION BY (val > 1e30) ORDER BY id SETTINGS ratio_of_defaults_for_sparse_serialization = 0.9, min_bytes_for_wide_part = 0; then 1000 rows of 0. (so val serializes Sparse) plus (2000, 3.0), (2001, nan), OPTIMIZE FINAL. SELECT count() ... WHERE NOT ((val >= 0.) AND (val <= 3.)) SETTINGS use_statistics_for_part_pruning = 0 returns 0 on no-fix master vs oracle 1; EXPLAIN indexes = 1 shows the part-level Min-Max Parts: 0/1. Deterministic.
b Root cause explained? The part-level minmax (IMergeTreeDataPart::MinMaxIndex::update) runs before sparse removal, and sparse blocks also arrive from sparse input / INSERT ... SELECT. The shared getMinMaxIndexExtremes only materialized LowCardinality, so ColumnSparse::getExtremes was trusted: it delegates to the values column and ColumnVector::getExtremes skips NaN, while columnSliceHasNaN (LowCardinality-only unwrap) returned false. The part-level minmax then stored a finite [min, max] for a [1, nan, 3] sparse part, so KeyCondition pruned the whole part under the negated range that the NaN row satisfies.
c Fix matches root cause? Yes. Both getMinMaxIndexExtremes and columnSliceHasNaN now call convertToFullIfNeeded() instead of convertToFullColumnIfLowCardinality(). It strips Const/Replicated/Sparse/LowCardinality and recurses into subcolumns while preserving the top-level Nullable wrapper, so the nested float (and its NaN) is visible to getExtremesNullLast and the NaN check for every special representation.
d Test intent preserved / new tests added? New regression in 04328: a sparse Float64 part mixing finite floats with NaN must not be pruned for the negated range (index ON == use_skip_indexes=0 oracle == 1), and EXPLAIN indexes = 1 asserts the part-level Min-Max does not prune it. use_statistics_for_part_pruning = 0 isolates the minmax path from the auto-statistics pruner (which use_skip_indexes = 0 does not disable). All prior cases unchanged.
e Both directions demonstrated? Yes. On the pristine no-fix master snapshot the new block yields 0, 1, 1 (wrong: index drops the NaN row, part pruned); with the fix it yields 1, 1, 0 (correct). The full updated 04328 differs from the reference on the no-fix binary and matches with the fix.
f Fix is general, not a narrow patch? Yes. Rather than special-casing Sparse, convertToFullIfNeeded() normalizes every special representation (Const, Replicated, Sparse, LowCardinality, and nested subcolumns) before extrema and NaN detection, so the same hidden-NaN class cannot recur via another carrier. Non-regression: 00944_minmax_nan, 00944_minmax_null, 01016_null_part_minmax, 02982_minmax_nan_null_order, 04064_minmax_index_null_inf_ordering, and the existing 04327/04328 cases all pass. The dense path is unaffected (no subcolumns -> no copy).

Session id: cron:clickhouse-worker-slot-9:20260611-064200

groeneai and others added 3 commits September 20, 2026 20:04
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.
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master into the branch and pushed as ae3012159cf2 — the branch had fallen 281 commits behind. The merge was clean (no conflicts), there are no test-number collisions for 04327_106948_minmax_skip_index_nan, 04328_106533_partition_pruning_nan_inversion or 04350_106533_statistics_pruning_nan_inversion, and all six touched translation units (KeyCondition.cpp, ReadFromMergeTree.cpp, MergeTreeDataSelectExecutor.cpp, MergeTreeIndexMinMax.cpp, MergeTreeIndexSet.cpp, StatisticsPartPruner.cpp) compile against the merged tree.

The public CI at the previous head 0ac18b2f was fully green — every build, Fast test, Style check, Unit tests, Stateless tests, Integration tests, Stress test, Upgrade check and the flaky checks passed, and the AI Review verdict was ✅ Approve. The 05227_storage_settings_unknown_name red that dominated the earlier heads is gone now that #121163 has merged. There are no unresolved review threads.

The one remaining red is CH Inc sync, and it is not ours. Its status description is tests failed, not conflicts found or build failed: the private sync PR ClickHouse/clickhouse-private#60445 merges cleanly (MERGEABLE) and every Build job is green; exactly one job failed, Stress test (arm_asan_ubsan, meta in keeper), with Failures: 1/8:

Logical error: RWLockImpl::getLock(): RWLock is already locked in exclusive mode
  (requested for query_id 'A', which already holds B lock(s); current owner query_ids: C) (STID: 2043-36a4)
Stack trace functions: DB::RWLockImpl::getLock, DB::IStorage::tryLockTimed, DB::IStorage::lockExclusively,
                       DB::StorageAlias::truncate, DB::InterpreterDropQuery::executeToTableImpl

That is the database-wide TRUNCATE over an Alias table, i.e. open issue #121129: InterpreterDropQuery::executeToDatabaseImpl shares one table_context, so the parallel per-table truncate tasks all carry the same query id and StorageAlias::truncate re-acquires an exclusive lock the target's own task already holds. It is fleet-wide and independent of this branch — the same STID: 2043-36a4 fired nine times in the last day on eight unrelated pull requests (#119230 twice, #116585, #112930, #118415, #120875, #121092, #120942) and on master itself (e6b360bb, BuzzHouse (amd_tsan), 2026-09-20 01:04:40Z). Nothing in this diff touches InterpreterDropQuery, StorageAlias or RWLockImpl; it only weakens KeyCondition atoms over float carriers that can hide a NaN in the minmax / set / part-pruning / statistics paths.

The fix #121134 (Skip Alias tables in a database-wide TRUNCATE) is open and unmerged, so merging master again cannot clear this row, and a second fixing PR would only duplicate it. Once it lands, CH Inc sync should go green here on its own.

Related: #121129
Related: #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]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Addressed the one unresolved review thread and pushed a1dd6c8ab2d0.

The bot was right that the val IN (nan) arms are dead probes. Master's setElementsContainNaN (4440da68a88e, "Do not prune by a min/max range when a positive IN set holds NaN") makes tryPrepareSetIndexForIn bail as soon as a set element is a NaN, so the atom is already unknown before StatisticsPartPruner::getKeyConditionForEstimates calls relaxAtomsOverNaNHidingColumns. With that call deleted, all three arms stayed green.

They are now sign(-val) = 1. That is a chain of two monotonic functions over a column that is not under a negation, so it survives collectFloatColumnsUnderNegation and stays in stats_column_name_to_type_map. Part 1's stored bounds are [1, 3]; the chain maps them to sign([-3, -1]) = [-1, -1], 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. This exercises the monotonic_functions_chain branch of the relaxation, the one that sets FUNCTION_UNKNOWN rather than just relaxed.

Measured on two builds differing only in that single call, for all three statistics implementations in the file (auto_statistics_types = 'minmax', Float32 STATISTICS(basic), 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 controls (val < 10. and val IN (150.)) still assert Parts: 1/2 on both builds, so no arm can pass by the pruner simply never pruning. The reference file is unchanged — the fixed build reproduces it byte for byte.

CI. The previous head ae3012159cf2 was green apart from CH Inc sync, whose description is tests failed, not conflicts found or build failed: the private sync PR merges cleanly with every Build job green, and the single failing job (Stress test (arm_asan_ubsan, meta in keeper), Failures: 1/8) is the fleet-wide RWLockImpl::getLock(): RWLock is already locked in exclusive mode through DB::StorageAlias::truncate, i.e. open issue #121129 (STID: 2043-36a4 fired nine times in a day on eight unrelated pull requests and on master itself). Its fix #121134 is open and unmerged, so merging master cannot clear it. CI is now re-running on the new head.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - a1dd6c8

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Performance Comparison (arm_release, master_head, 1/6) / set_index #0 dashboard-verdict gate (#120927). client_time 0.0276 to 0.0358 (+29.3%) against this query's own learned threshold of 0.94, so the shard's own report calls it unstable, never slower. The fixture is test_in (a UInt32) ORDER BY a with no skip index, queried with read_overflow_mode = 'break', so the work done depends on which thread reaches the row budget first #121090 (mine, open)
Performance Comparison (arm_release, master_head, 5/6) / and_compare_chain_derived #2 same gate. client_time 0.0156 to 0.0195 (+25.2%) against a learned threshold of 0.59; the shard's own report calls the query success. Same query and test were flagged the same way at +15.1% on an unrelated PR 11 hours earlier #121090 (mine, open)
Mergeable Check, PR praktika rollups of the two rows above, no independent failing leaf #121090 (mine, open)

Not caused by this PR, and the mechanism is absent rather than merely unlikely: this diff changes NaN
handling under negated float comparisons in KeyCondition, the minmax and set skip indexes and the
statistics part pruner. set_index has a UInt32 key, no skip index, no statistics and no negation;
and_compare_chain_derived #2 is ... INNER JOIN ... WHERE l.v < r.k AND 9900000 < l.v over two
ORDER BY tuple() tables, i.e. no key, no float, no negation, no skip index. The four arm shards that
carry too long, unstable and faster counts without a dashboard verdict all report OK, which is
what isolates the failing element to the gate.

The NOT_FAILED rows on the amd_llvm_coverage s3 jobs are the "succeeded but still blacklisted"
marker on passing tests, not failures, and their jobs are green.

Session id: cron:our-pr-ci-monitor:20260921-113202

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master into the branch and pushed as 70ce7846e64e — the branch had fallen 244 commits behind. The merge was clean (no conflicts), there are no test-number collisions for 04327_106948_minmax_skip_index_nan, 04328_106533_partition_pruning_nan_inversion or 04350_106533_statistics_pruning_nan_inversion, and all six touched translation units (KeyCondition.cpp, ReadFromMergeTree.cpp, MergeTreeDataSelectExecutor.cpp, MergeTreeIndexMinMax.cpp, MergeTreeIndexSet.cpp, StatisticsPartPruner.cpp) compile against the merged tree. The diff against master is still exactly the same 13 files, +828/-14.

CI at the previous head a1dd6c8ab2d0 was green everywhere that matters. Every build, Fast test, Style check, Unit tests, Stateless tests, Integration tests, Stress test, Upgrade check, Build profile diff, SQLLogic/SQLStorm and the flaky checks passed, and CH Inc sync is now SUCCESS — the RWLockImpl::getLock(): RWLock is already locked in exclusive mode failure through DB::StorageAlias::truncate (#121129) that held it red on the earlier heads did not recur. There are no unresolved review threads and the AI Review verdict is ✅ Approve.

The only two red rows are the master_head performance dashboard verdicts, and they are noise. Both are the Performance Comparison dashboard gate (#121090) firing while the shard's own report classifies the query as unstable/success rather than slower — the machine-readable all-query-metrics.tsv across all six arm shards reports 7 faster, 0 slower over 3496 queries.

I re-measured the noise floor directly from the checks table, restricted to pull_request_number = 0, i.e. master-vs-master runs where nothing at all changed between the two binaries, over the last 21 days:

query master-only runs p05 p50 p95 |new−old|/old over 25% worst deviation
set_index #0 345 22 ms 28 ms 36 ms 24.1% of runs 69.6%
and_compare_chain_derived #2 346 15 ms 18 ms 22 ms 11.8% of runs 57.1%

The flagged numbers are set_index #0 27.6 ms → 35.8 ms (+29.3%) and and_compare_chain_derived #2 15.6 ms → 19.5 ms (+25.2%). Every one of those four values falls inside its query's own master-only p05–p95 band, and a deviation of that size already occurs in a quarter (respectively an eighth) of runs that compare master against itself. and_compare_chain_derived #2 was refuted the same way on an unrelated PR yesterday.

The mechanism is absent, not merely unlikely. This diff only weakens KeyCondition atoms over float carriers that can hide a NaN, at four call sites: the minmax skip index, the set skip index, part-level minmax and the statistics part pruner.

  • set_index #0 is SELECT count() FROM test_in WHERE a IN (SELECT rand(1) FROM numbers(200000)) over CREATE TABLE test_in (a UInt32) ENGINE = MergeTree ORDER BY a — an integer primary key, no skip index, no statistics, no float column and no negation, so typeMayHideNaN is false for every column and relaxAtomsOverNaNHidingColumns has nothing to relax. It also runs with max_rows_to_read = 200001, read_overflow_mode = 'break', so the work performed depends on which thread reaches the row budget first — which is exactly why its own history is this wide.
  • and_compare_chain_derived #2 is SELECT count() FROM t_chain_derived_join AS l INNER JOIN t_chain_derived AS r ON l.k = r.k WHERE l.v < r.k AND 9900000 < l.v over two ENGINE = MergeTree ORDER BY tuple() tables — no key, no float, no negation, no skip index, no statistics.

The four arm shards that carry too long, unstable and faster counts but no dashboard verdict all report OK, which is what isolates the failing element to the gate rather than to the measurement. The gate fix #121090 is open and unmerged, so merging master cannot clear these two rows on its own; Mergeable Check and PR are pure rollups of them with no independent failing leaf.

Related: #121090

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 22, 2026
Merged via the queue into ClickHouse:master with commit c3047f7 Sep 22, 2026
177 checks passed
@robot-ch-test-poll robot-ch-test-poll added pr-synced-to-cloud The PR is synced to the cloud repo pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR labels Sep 22, 2026
alexey-milovidov added a commit that referenced this pull request Sep 23, 2026
…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]>
alexey-milovidov added a commit that referenced this pull request Sep 25, 2026
… 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]>
@robot-clickhouse robot-clickhouse added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 25, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 29, 2026
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]>
alexey-milovidov added a commit that referenced this pull request Oct 1, 2026
…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]>
@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

blocker This issue / pr blocks a new release can be tested Allows running workflows for external contributors comp-key-condition Analysis of a filter against a key. KeyCondition turns a WHERE condition into ranges over the pri... groeneai-origin-request PR origin: a maintainer pinged or directed groeneai groeneai-origin-unknown PR origin: unclassified (legacy task) pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet