Repository navigation
Fix skip indexes and partition pruning dropping rows whose Array or Map value holds a NULL or NaN - #116728
Fix skip indexes and partition pruning dropping rows whose Array or Map value holds a NULL or NaN#116728groeneai wants to merge 9 commits into
Array or Map value holds a NULL or NaN#116728Conversation
A `minmax` skip index on an `Array` or `Map` column returned too few rows. With rows `[1.]`, `[nan]`, `[3.]` in one granule, `SELECT count() ... WHERE a > [500.]` returned 0 with the index and 1 with `use_skip_indexes = 0`. `[nan] > [500.]` is true, because arrays compare through `compareAt`, a total order that ranks a `NaN` element above every number. `MergeTreeIndexAggregatorMinMax::update` stored the pair from `IColumn::getExtremes`, which is the `min` and `max` aggregate answer. `ColumnArray::getExtremes` scans the low end under `nan_direction_hint = 1` and the high end under `-1`, deliberately mirroring `SingleValueDataBase::getSmallestIndex` and `getGreatestIndex`, and a `NaN` is ordered last in both directions, so a value containing one is never selected as either bound. `KeyCondition` then compares that range under `accurateLess`, where such a value is the largest, so `Range::intersectsRange` reports no intersection for a predicate the granule's rows satisfy. The defect is an aggregate-oriented extrema API used as a pruning bound, so the fix belongs in the index layer. `getExtremes` itself is unchanged, and `02982_minmax_nan_null_order`, which pins its aggregate answers, passes with its reference untouched. For admitted index columns `update` now computes both ends in one scan under a single `compareAt(..., 1)` instead of calling `getExtremes`. Only the high end was wrong: the min scan is already a single-order scan under hint 1, and ascending-first under "NaN greatest" is the total-order minimum. The loop shape and the comparison count match what `ColumnArray::getExtremes` already performed, and the per-column flags are derived once per index per metadata snapshot rather than in the aggregator, which `MergeTreeDataPartWriterOnDisk` rebuilds inside the per-granule loop. Insert cost is unchanged, measured over 3M rows with `MergeTreeDataWriterSkipIndicesCalculationMicroseconds`. A column is admitted iff it is a top-level `Array` or `Map`, its type tree holds a float, and every node in that tree yields a single `Field` type tag. Tag stability is a correctness condition: `Field::operator<` compares the tag before the value, so a `Nullable` or `Dynamic` node orders by tag at the `Field` level and by something else under `compareAt`, and the two orders diverge. Admitting `Nullable` was measured to introduce wrong results on a shape that is correct today. Being an allow-list, `Nullable`, `Object`, `Dynamic`, `Variant`, `Nothing` and anything added later are excluded without being named, which matters because `minmaxIndexValidator` returns early on `attach`, so an attached table can carry a `minmax` index on any type. The float requirement is only a cost gate: without a float the two hints cannot disagree, and dropping it was measured to change no result. Pruning is preserved. A NaN-free granule is still skipped, and so are `Array(String)` and `Array(LowCardinality(String))` granules, which the cost gate excludes from the new path. Not addressed, each measured: the part-level `minmax` index has the same defect through a `PARTITION BY` expression, but its bound is also read as an aggregate by `_minmax_count_projection`; a nested `NULL` reproduces the failure with no `NaN` present and no stored bound can fix it, because `Field::operator<` ranks a nested `Null` first while `compareAt` ranks it last; a top-level `Tuple` is left to the separate scalar and `Tuple` change; and `JSON`, `Dynamic` and `Variant` are reachable through `ATTACH` but excluded by the gate. This is a write-path fix, so parts already on disk keep the bound their writer computed until a merge, an `OPTIMIZE` or a re-insert rewrites them.
Review round 1. `getTotalOrderExtremes` materialized the two chosen rows with `IColumn::get`, which for a top-level `Map` is `ColumnMap::get` and has no size limit. The path it replaced was capped: `ColumnMap::getExtremes` delegates to the nested `ColumnArray`, whose `get` throws `TOO_LARGE_ARRAY_SIZE` above `max_array_size_as_field`. A row whose `Map` holds more than a million entries is refused by the writer today; without the cap it would be accepted, built as an unbounded `Map` field on the insert path and serialized whole into `.idx2` as the granule bound. Materialize through the nested `ColumnArray` and convert the resulting `Array` fields to `Map`, as `ColumnMap::getExtremes` does. Ordering is unaffected because `ColumnMap::compareAt` already forwards to the nested column, so the argmax under the same hint is the same row. Verified in both directions: a 1,000,001-entry row is refused exactly as on master, a 1,000,000-entry row is accepted on both, the same oversized row still inserts into a table with no `minmax` index, and removing the delegation accepts it. Also drop the `isIPv4` term from the allow-list, which can never decide anything because `DataTypeIPv4::isValueRepresentedByNumber` already returns true, unlike `DataTypeIPv6`; and assign the empty-range defaults before the early return, mirroring `ColumnArray::getExtremes`. Add two `GRANULARITY 2` test blocks. They are the only arms whose bound is merged across two `update` calls, and the merge takes a different side of its comparison depending on which mark holds the `NaN`, so one block cannot cover both. Each is pinned by its own mutant that reddens that block alone and leaves every `GRANULARITY 1` block green.
Review round 2 asked three things of the test, and none of them needs a source change: the source is byte for byte the one reviewed in round 1. Assert pruning, not only row counts. The Map arm and the two GRANULARITY 2 arms compared an indexed count against an unindexed one, so they would still pass if the index stopped pruning altogether. Each now also asserts an exact Granules count. The first-mark table grows from 6 rows to 12 so that it holds four marks and therefore two index entries: at six rows a GRANULARITY 2 index has a single entry spanning both marks, whose only outcomes are 2/2 and 0/2, and 2/2 is also what an unused index prints. Cover the custom-serialization class. The allow-list admits any type whose every node round-trips a single Field tag, and nothing had exercised a leaf whose serialization re-tags on read. Array(Tuple(Float64, Bool)) is now a shipped arm, and Enum8, Decimal64 and DateTime64 leaves were measured alongside it. Bool turns out to be the only serialization in the tree that re-tags a Field, and a nested Bool loses pruning on a tied prefix both before and after this change, which the description now discloses. Excluding it was measured and is worse: it gives back the wrong answer this change fixes for that shape and repairs nothing. Drop the C++ call and branch names from a test comment in favour of the property being observed.
Review round 3. Test only, and the source is byte for byte the one reviewed in round 1. The two `t_mixed` arms compared an indexed count against an unindexed one, so they would still pass if the index stopped pruning altogether. `Array(Tuple(Float64, String, UUID, LowCardinality(String), IPv6, Date))` is the widest shape the allow-list admits, and nothing in the test or in the recorded measurements asserted a granule count for it. The single-leaf `Array(String)`, `Array(LowCardinality(String))` and `NaN`-free `Array(Float64)` shapes were covered; the composite was not. The new arm reads `Granules: 1/2` from `EXPLAIN indexes = 1`, which pins both directions at once: numerator 1 says the granule holding the `NaN` is no longer skipped, and denominator 2 alongside it says the granule of finite values still is. Without this change the stored bound excludes the `NaN`, both granules are prunable, the plan prints `Granules: 0/2` and the arm reads 0, so the arm is red on master without needing a mutant. If pruning were lost for the shape the plan would print `Granules: 2/2` and the arm would also read 0. It selects `sum(id)` rather than a bare `count`, because a trivial-count plan emits no read step for the assertion to match, and it pins `use_skip_indexes_on_data_read`, which the test runner randomizes and which makes the arm read 0 when it is 1. The predicate is byte for byte the one the two existing arms use, so all three read the same comparison.
Internal second-model reviewReviewed cold against the diff by a second model over four rounds, then adjudicated. Verdicts and Fixed in this PR
Raised and not actioned, with the reason
Insert cost
Every median is within 1% of its base counterpart and every min within 0.9%. The two high |
|
Workflow [PR], commit [ca5b9d7] Summary: ❌
AI ReviewSummaryThe PR widens reader-side container bounds without changing stored indexes. The fix remains incomplete for comparison constants containing nested Findings❌ Blockers
Tests
Missing context / blind spots
Final Verdict❌ Block — Make pruning safe for nested |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-self-slot-57:20260827-102900 |
|
cc @shankar-iyer @hanfei1991, could you review this? A |
Build profile diff (arm_release)Commit See the job log for details. |
CI finish ledger - 7408c0fCI is fully finished at this commit and green. Both
Note for anyone reading the check list: this head carries two Session id: cron:our-pr-ci-monitor:20260827-213000 |
|
Dear @shankar-iyer, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself. |
# Conflicts: # src/Storages/MergeTree/MergeTreeIndexMinMax.h
`IDataType::forEachChild` was removed from master and its callers moved to `forEachInTypeTree` from `DataTypes/TypeTree.h`, which also visits the root. The visited set is unchanged for every type the allow-list admits (`Array`, `Map`, `Tuple`, `LowCardinality`, `Nullable` expose the same children as before), and a type whose children are newly enumerated (`QBit`, `AggregateFunction`, `Function`) already fails the allow-list at its own node. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The next commit makes every reader of these bounds treat the upper end of an `Array` or `Map` column with a `Nullable` or floating-point element as unbounded, so the comparison-order upper bound this writer stored is never read. Its lower end is the same value `IColumn::getExtremes` returns (both take the minimum under `nan_direction_hint = 1` in the same scan), so the granules it writes become byte-identical to master's again. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…s unbounded `IColumn::getExtremes` of an `Array` or `Map` takes the max under `nan_direction_hint = -1`, so a value with a `NULL` or `NaN` element is never the stored max, and partial bounds are merged in `Field` order, where a nested `Null` sorts first. Comparisons and `IN` sets order such an element after every value, so a row like `[NULL]` or `[nan]` can satisfy `a > ['zzz']` while lying above the stored upper bound, and a merged lower bound holding a `NULL` can lie above a row. The `minmax` and `set` skip indexes, part-level minmax pruning by the partition key, and primary key analysis that borrows that part-level bound then skip granules and parts that hold matching rows. No stored bound is changed: a bound holding a `NULL` or `NaN` is misread by every supported release before 26.10, and nothing tells granules written before such a writer change from those written after. Instead, every consumer of these bounds now reads, for a column whose type is an `Array` or `Map` at any depth with a `Nullable` or floating-point element, the upper end as `+inf` and a lower end holding a `NULL` as `-inf`. Primary key analysis no longer uses the part-level bound of such a column. Types holding `Dynamic`, `Variant` or `JSON` are left as they are. Lower-side pruning (`a < c`, the lower end of `=`, `IN`, `BETWEEN`) is kept; upper-side pruning (`a > c`, `a >= c`) is given up for these column types only. Existing parts are covered by the same reader. The test of the previous commits is renamed and extended to NULL elements, the set index, the part-level index, merges and primary key analysis. Its upper-side pruning arms on float containers, and the same arm of `04327_106948_minmax_skip_index_nan`, now assert the lower side. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Remove the comment on getColumnsMayHideValueAboveMax, which restates its signature. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Array or Map value holds a NULL or NaN
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex) plus my own cold review. The design
Severity: ❌ blocker / Session id: cron:clickhouse-review-self-slot-58:20261024-200600 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-self-slot-57:20261024-165600 |
|
cc @shankar-iyer @CurtizJ, could you review this? |
| Range & range = widened[i]; | ||
| range.right = POSITIVE_INFINITY; | ||
| range.right_included = true; | ||
| if (fieldHasNullInside(range.left)) |
There was a problem hiding this comment.
[P1] Handle nested NULL constants before preserving the lower bound
A NULL-free lower bound is still unsafe when the comparison constant contains a nested NULL. For a Array(Nullable(String)) with one granule containing ['a'], [NULL], and ['c'], a < CAST([NULL], 'Array(Nullable(String))') must match two rows. This helper leaves the lower bound at ['a'] and widens only the upper end. KeyCondition builds (-Inf, [NULL]) for the predicate, and Range::intersectsRange compares container elements in Field order, where [NULL] < ['a'], so it still rejects the entire granule. The set pre-check and partition pruning inherit the same false negative.
Please decline range atoms with nested NULL constants, or compare their endpoints using the column's SQL ordering, before retaining lower-side pruning. Add coverage with a finite stored lower bound and a NULL-holding constant: the existing null-constant test starts from a NULL-holding lower bound, widens both ends, and misses this case. The baseline reproduction on 26.10.2.103 returns 0 indexed versus 2 unindexed rows for all three consumers; tracing the current helper and comparison code shows why this fix leaves it unchanged.
CI finish ledger - ca5b9d7Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
CIDB has no other Session id: cron:our-pr-ci-monitor:20261025-010006 |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
The
minmaxandsetskip indexes, partition pruning and primary key analysis no longer skip a granule or part holding anArrayorMapvalue with aNULLorNaNelement, which made queries such asa > ['zzz']return too few rows. ForArrayandMapcolumns with aNullableor floating-point element, theminmaxindex and partition pruning no longer prune on the upper side of a range (a > c,a >= c).Description
On 26.8.21.12, with
a Array(Nullable(String))and rows['a'],[NULL],['c'],SELECT count() FROM t WHERE a > ['zzz']returns 0 with aminmaxindex or withPARTITION BY length(a), and 1 without them.NaNelements do the same (#121767).Comparisons and
INsort aNULLorNaNelement after every value, butIColumn::getExtremesof anArrayorMapranks it lowest for the max, and partial bounds are merged inFieldorder, where a nestedNULLis smallest. So a matching row can lie above the stored max, and a merged min holding aNULLabove a row.No stored bound changes: releases before 26.10 misread a
NULL-holding bound, and old granules cannot be told from new ones. Instead, for anArrayorMapcolumn (at any depth) with aNullableor floating-point element, theminmaxandsetskip indexes and part-level pruning read the upper end as+infand a lower end holding aNULLas-inf; primary key analysis stops using its part-level bound. Types holdingDynamic,VariantorJSONare unchanged. It replaces this PR's earlier writer change.Trade-off: for these types the
minmaxindex and part-level pruning no longer prunea > canda >= c; they still prunea < c(a constant holding aNULLis #124700) and the lower side of=andIN, thesetindex still prunes by its stored values; other types (Array(String)) are unaffected. Analyzing 31k such granules takes 10.2 instead of 7.9 ms (debug build).Validation:
05045_minmax_index_container_bound_nan_nullfails on master and passes with the fix (100 randomized runs); old parts read correctly, and 26.3, 26.8 and 26.9 read parts written by this build like 26.8-written ones. The upper-side pruning arm of04327_106948_minmax_skip_index_nannow checks the lower side.Supersedes #116655.
Closes: #121767
Related: #118945
Workflow [PR]
Sync PR [sync-upstream/pr/116728]