Skip to content

Fix skip indexes and partition pruning dropping rows whose Array or Map value holds a NULL or NaN - #116728

Open
groeneai wants to merge 9 commits into
ClickHouse:masterfrom
groeneai:minmax-index-array-nan-upper-bound
Open

groeneai wants to merge 9 commits into
ClickHouse:masterfrom
groeneai:minmax-index-array-nan-upper-bound

Conversation

@groeneai

@groeneai groeneai commented Aug 27, 2026 •

Copy link
Copy Markdown
Collaborator

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):

The minmax and set skip indexes, partition pruning and primary key analysis no longer skip a granule or part holding an Array or Map value with a NULL or NaN element, which made queries such as a > ['zzz'] return too few rows. For Array and Map columns with a Nullable or floating-point element, the minmax index 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 a minmax index or with PARTITION BY length(a), and 1 without them. NaN elements do the same (#121767).

Comparisons and IN sort a NULL or NaN element after every value, but IColumn::getExtremes of an Array or Map ranks it lowest for the max, and partial bounds are merged in Field order, where a nested NULL is smallest. So a matching row can lie above the stored max, and a merged min holding a NULL above 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 an Array or Map column (at any depth) with a Nullable or floating-point element, the minmax and set skip indexes and part-level pruning read the upper end as +inf and a lower end holding a NULL as -inf; primary key analysis stops using its part-level bound. Types holding Dynamic, Variant or JSON are unchanged. It replaces this PR's earlier writer change.

Trade-off: for these types the minmax index and part-level pruning no longer prune a > c and a >= c; they still prune a < c (a constant holding a NULL is #124700) and the lower side of = and IN, the set index 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_null fails 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 of 04327_106948_minmax_skip_index_nan now checks the lower side.

Supersedes #116655.

Closes: #121767
Related: #118945


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

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.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work labels Aug 27, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

Reviewed cold against the diff by a second model over four rounds, then adjudicated. Verdicts and
the evidence behind each are recorded; nothing was overridden without a source citation. Final
reviewed head 7408c0f7f7eeffe5329fb6c8034f0573b8afc709; the last round returned no findings.

Fixed in this PR

finding resolution
❌ The Map path bypassed the 1,000,000-element max_array_size_as_field guard. ColumnMap::getExtremes reached materialization through the nested ColumnArray, whose get refuses an oversized value; ColumnMap::get has no such limit, so a map row wider than the limit would have been materialized and serialized into .idx2 unbounded, where it is refused today. The two chosen Map rows are materialized through getNestedColumn and converted, mirroring ColumnMap::getExtremes. Ordering is unaffected: ColumnMap::compareAt already delegates to the nested column. Verified in both directions: a 1,000,001-entry row is refused exactly as on master, 1,000,000 is accepted on both, and removing the delegation accepts the oversized row.
⚠️ isIPv4 in the leaf allow-list could never decide: DataTypeIPv4::isValueRepresentedByNumber is already true. DataTypeIPv6 has no such override, so isIPv6 is load-bearing and stays. Dead term removed; an Array(Tuple(Float64, IPv4)) probe confirms the removal is a no-op.
⚠️ The new helper's empty-range early return left both output fields untouched, where ColumnArray::getExtremes assigns defaults first. Unreachable (update always sees at least one row), but the asymmetry is a trap, and the two fields live outside the per-column loop. Defaults assigned before the early return.
⚠️ Arms that compare an indexed row count against an unindexed one still pass if the index stops pruning altogether. Raised for the Map and GRANULARITY 2 carriers, then again for the widest admitted leaf combination. Exact Granules: assertions added for the Map carrier, for the multi-mark merge, and for Array(Tuple(Float64, String, UUID, LowCardinality(String), IPv6, Date)). Each is red on master by construction, so no mutant is needed to prove it live.
⚠️ The related-pull-request metadata was only inside the HTML comment, which does not render, while the rendered line used short references with two relationships on it. Actioned, late: the description now carries Related: <full URL> on its own line for each, as .claude/CLAUDE.md requires. This was declined in the first round on the true-but-insufficient ground that the comment block already held full URLs; a block that does not render cannot satisfy the rule, so the earlier verdict was wrong.
💡 No arm exercised a granule built from more than one update call, which is where the widened bound has to survive the accurateLess merge. A GRANULARITY 2 block in both mark orderings. One mutant per ordering: the two arms take opposite sides of the merge, so a single mutant provably cannot cover both.
💡 The changelog entry read as though an upgrade repairs existing tables. It now says granules written before the upgrade keep the old bound until the part is rewritten.
💡 The residual list said "a nested NULL", which reads as a value property. The allow-list rejects Nullable by type, so Array(Nullable(Float64)) keeps the narrow bound with no NULL anywhere. Reworded to "a nested Nullable type even with no NULL values".
💡 A test comment named a C++ function. Replaced with a statement of the observable property.

Raised and not actioned, with the reason

finding verdict
❌ Array(Tuple(Float64, Bool)) was reported as a granule-pruning defect introduced by the allow-list, since Bool is a UInt8 under a custom name and so carries two Field tags across a serialization round trip. The tag instability is real and the defect is real, but it is pre-existing and not introduced here, so it is disclosed rather than fixed. Measured on both binaries: the reported probe does not reproduce on either; the fixture that does reproduce needs a tied float prefix and no NaN at all, and is wrong on 5 of 14 predicates for Bool and 0 of 14 for UInt8, identically before and after. It also reproduces on Array(Bool) and Tuple(Float64, Bool), neither of which the allow-list admits, so the new branch cannot be a participant. Direction matches Field::Types::Bool = 28 against UInt64 = 1 with the tag compared first: upper bounds prune every granule, lower bounds none. The suggested exclusion was implemented and measured: it reverts the Bool carrier this PR fixes back to master's wrong answer and repairs nothing on the tag defect, which is why Bool stays admitted.
⚠️ The same tag asymmetry was then reported against EXPLAIN WHATIF, which evaluates a hypothetical granule in memory without a serialization round trip, so its bound keeps the pre-serialization tag while a real read sees the deserialized one. Every step is true and was verified, but the attribution is not: the path this change replaces, ColumnArray::getExtremes, materializes with the identical get(min_idx) / get(max_idx) after the identical single-pass loop. The only difference is the max comparison's NaN direction hint, so a pre-serialization tag is produced the same way before and after and the asymmetry has the same reach on both sides. It also needs a tied float prefix and no NaN, so it is outside this change's invariant; for the NaN case both consumers agree, because Float64 round-trips. A test here would pin a pre-existing cross-path divergence in an estimator.
⚠️ Asked for an exact-pruning assertion on each 6-row GRANULARITY 2 table showing the NaN granule kept and the finite one pruned. Declined as prescribed, and replaced. At index_granularity = 3 those tables hold ONE index entry spanning both marks, so the only outcomes are 2/2 and 0/2, and 2/2 is also what an unused index prints, so the arm would distinguish nothing. One table was widened to four marks instead, giving two entries and a 2/4 assertion that does distinguish.
⚠️ Asked for a pruning-preservation arm on the excluded Array(Nullable(Float64)) shape as well. Declined: this change cannot alter the excluded path. Both non-admitted branches are byte-identical to master, and all 14 excluded shapes were measured byte-identical. That fixture is also the counterexample proving the exclusion necessary, so adding a second granule to it risks the liveness it exists for.
💡 Suggested disclosing a top-level Nullable(Array(T)) index column as a further residual. Declined: the column cannot exist. CREATE TABLE ... Nullable(Array(Float64)) is Code: 43 ILLEGAL_TYPE_OF_ARGUMENT, and DataTypeArray::canBeInsideNullable and DataTypeMap::canBeInsideNullable both return false unconditionally. The reachable neighbour is the nested Nullable, which is already listed.

Insert cost

INSERT ... SELECT FROM numbers(3000000) per repetition, one table per shape, index_granularity = 8192,
minmax GRANULARITY 1 on the container column. ProfileEvents['MergeTreeDataWriterSkipIndicesCalculationMicroseconds']
from system.query_log keyed by log_comment; one server per binary with buildId asserted per arm.

shape admitted arm reps min us median us max us
Array(Float64) yes base 3 116974 118489 118865
Array(Float64) yes fix 3 116930 117409 117999
Array(String) no (float gate) base 3 125179 126365 128600
Array(String) no (float gate) fix 3 126269 126368 139725
Map(String, Float64) yes base 3 233252 235160 236273
Map(String, Float64) yes fix 3 233787 235520 272194
Map(String, Float64) yes fix, extra pass 5 228588 229414 231650

Every median is within 1% of its base counterpart and every min within 0.9%. The two high max cells on
the fix side are single-repetition outliers from neighbour load, not a trend: the later 5-repetition
Map pass spans 228588-231650, below the base median. Array(String) is the non-admitted control:
the
new branch adds a per-column flag lookup for excluded columns too, and it does not move the number.

@clickhouse-gh clickhouse-gh Bot closed this Aug 27, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Aug 27, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ca5b9d7]

Summary: ❌

job_name test_name status info comment
Upgrade check (amd_release) FAIL
Changed settings are not reflected in the settings changes history (see changed_settings.txt) FAIL cidb

AI Review

Summary

The PR widens reader-side container bounds without changing stored indexes. The fix remains incomplete for comparison constants containing nested NULL: lower-side pruning can still discard matching rows. One correctness blocker remains.

Findings

❌ Blockers

  • src/Storages/MergeTree/KeyCondition.cpp:1725 — [P1] A finite lower bound is unsafe against a nested NULL constant. For a Array(Nullable(String)) containing ['a'], [NULL], and ['c'] in one granule, WHERE a < CAST([NULL], 'Array(Nullable(String))') must return two rows. The helper keeps ['a'] as the lower bound; Range::intersectsRange orders [NULL] below ['a'] through Field comparison and rejects the granule despite the widened upper end. The same pre-check affects the set index and partition pruning. Decline these range atoms or use SQL-compatible endpoint comparison before preserving lower-side pruning.
Tests
  • ⚠️ Add a finite-lower-bound/nested-NULL-constant case to 05045_minmax_index_container_bound_nan_null for minmax, set, and partition pruning. Its existing null-constant fixture already has a NULL-holding lower bound, so both ends become unbounded and conceal this gap.
Missing context / blind spots
  • ⚠️ Runtime reproduction used official ClickHouse 26.10.2.103 and returned 0 indexed versus 2 full-scan rows for all three consumers. Persistence at PR head was established by tracing the current helper, atom construction, and range comparison; a PR-head run of the focused regression would complete runtime validation.
Final Verdict

❌ Block — Make pruning safe for nested NULL comparison constants and add the focused regression.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 27, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. A fixed 6-row fixture, no randomization and no timing: Array(Float64) with index_granularity = 3, rows [1.], [nan], [3.] then [100.], [150.], [200.]. SELECT count() FROM arr WHERE a > [500.] returns 0 with the index and 1 with use_skip_indexes = 0, Granules: 0/2.
b Root cause explained? Yes. The writer stored IColumn::getExtremes, which is the min and max aggregate pair: ColumnArray::getExtremes scans the low end under nan_direction_hint = 1 and the high end under -1, 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.
c Fix matches root cause? Yes. The high end is recomputed under the reader's own order instead of the aggregate one. No widened bound, no no-random-* tag, no data reduction, no defensive check. The low end is deliberately untouched: ascending-first under "NaN greatest" already is the total-order minimum.
d Test intent preserved / new tests added? Yes. One new stateless SQL test (SQL rather than a unit test) with 10 blocks and 27 reference rows, including two GRANULARITY 2 blocks that exercise the bound merged across two update calls, one per NaN position, and exact Granules: assertions for the Array, Map, Bool-leaf, cross-mark and widest-composite (six leaf types) carriers so an index that silently stopped pruning would not pass. No existing test was weakened, and 02982_minmax_nan_null_order, which pins the aggregate answers this change deliberately does not touch, passes with its reference unmodified.
e Both directions demonstrated? Yes, per block, on named Build IDs. Base 13023cad93cb1bae351d128ee0db072120b00387: 12 assertions red. Fix 0a2df01477a97b33f41999746f4d7e320dc6fb47: all 27 green, and 3 control blocks green on both. Each carrier additionally has a mutant that reddens that carrier alone and leaves every other block green. 50 randomized runs of the new test: 50 passed, 0 failed.
f Fix is general across code paths? Map is covered by delegating to its nested ColumnArray, which also keeps the max_array_size_as_field limit that ColumnMap::get does not enforce, and the writer is fixed at the source rather than guarded at the pruning site. Symmetric paths checked with their disposition: the top-K bulk-granule reader is unreachable for a container column, because ReadFromMergeTree requires isValueRepresentedByNumber; the part-level minmax writer has the same defect but its bound is also read as an aggregate by _minmax_count_projection, so it is disclosed and left alone; a top-level Tuple is excluded to avoid duplicating my own open #107074.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. 13 admitted shapes measured from 0 vs 1 on base to 1 == 1 on fix: Float32 as well as Float64, Array(Array(Float64)), Array(Tuple(...)) over String, UUID, IPv4, IPv6, Date, LowCardinality(String) and the custom-serialization leaves Bool, Enum8, Decimal64 and DateTime64, empty and varying-length arrays, and one granule fed by two blocks. Nullable, JSON, Dynamic and Variant are excluded because admitting them would introduce wrong results, proven by a mutant that adds Nullable to the allow-list and turns a currently correct answer of 2 into 0. The leaf sweep is what the allow-list rests on: SerializationBool is the only serialization in the tree that changes a Field's type tag on read, and a nested Bool consequently loses minmax pruning on a tied prefix both before and after this change, which the description discloses.
h Backward compatible? (maintainer-approved exception only) Yes. No new setting, no default change, so no SettingsChangesHistory.cpp entry; no index format or serialization change, and version 2's isNull() to POSITIVE_INFINITY remap does not fire for a NaN. 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. That is stated in the PR description.
i Invariants and contracts preserved? Yes. Both ends still bound the granule, now under the order KeyCondition actually compares with; the allow-list admits a type only when every node of its tree round-trips a single Field tag, so that order coincides with the recomputation's. The one admitted leaf where the reader's own comparison is already tag-unstable, nested Bool, is unaffected either way: it prunes identically before and after this change, measured, and reproduces on Array(Bool) and Tuple(Float64, Bool), which this change does not admit. Single-row and all-equal slices behave exactly as today; the empty-range case early-returns and is unreachable, since update guarantees at least one row. The multi-block widening uses accurateLess, the reader's order, and is measured. Columns are scanned as given and never materialized: compareAt and get are logical-row operations on the replicated, sparse and const wrappers, and a Map value is materialized through its nested ColumnArray, which preserves both the Map field type and the million-element materialization limit the replaced path enforced. Verified in both directions: a 1,000,001-entry Map row is refused with TOO_LARGE_ARRAY_SIZE on this change exactly as on master, a 1,000,000-entry row is accepted on both, and a mutant with the delegation removed accepts the oversized row.

Session id: cron:clickhouse-impl-self-slot-57:20260827-102900

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @shankar-iyer @hanfei1991, could you review this? A minmax skip index on an Array or Map column took its upper bound from IColumn::getExtremes, which ranks NaN lowest, while KeyCondition compares the stored range in the opposite order, so a granule holding a NaN was pruned even though its rows match the predicate. The writer now computes both ends in one compareAt scan for a narrow allow-list of container types, so a stored range can only widen.

@shankar-iyer shankar-iyer self-assigned this Aug 27, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit ca5b9d7b005357669b207b51a8e2e6b89d84ebf8 was not compared: the CI logs cluster did not answer (exception 241, code 500: { "meta": [ ], "data": [ ], "rows": 0, "exception": "Code: 24…).

See the job log for details.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 7408c0f

CI is fully finished at this commit and green. Both PR workflow runs conclude success, CIDB holds 0 FAIL/ERROR rows, and enumerating every job of all 8 runs at this head leaves exactly one job that is neither success nor skipped:

Check / test Reason Owner / fixing PR
request-reviews-fork (in a Documentation Team Review Requests run) Cancelled, not a test result: two pull_request_target dispatches of that workflow at this one commit superseded each other, and the same duplicate dispatch also produced the two PR runs below #116701 (ours, open)

Note for anyone reading the check list: this head carries two PR workflow runs, so roughly 175 check names appear twice and praktika's shared per-SHA result_pr.json is last-writer-wins. Both runs happen to be green here, so the duplication changes nothing, but the reading above comes from per-run check-runs and CIDB rather than that document. Config Workflow and Finish Workflow pass in both runs; the completion gate uses the later Finish Workflow (20:57:49Z).

Session id: cron:our-pr-ci-monitor:20260827-213000

@clickhouse-gh clickhouse-gh Bot added the comp-skip-index Skipping indexes (minmax, set, bloom) and their evaluation. label Sep 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 28, 2026

Copy link
Copy Markdown
Contributor

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.

alexey-milovidov and others added 5 commits October 11, 2026 20:34
# 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]>
@groeneai groeneai changed the title Fix minmax skip index pruning a granule whose Array or Map value contains a NaN Fix skip indexes and partition pruning dropping rows whose Array or Map value holds a NULL or NaN Oct 24, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
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
changed after the first two rows, so rows 1 and 2 were on an unpublished tree; the head pushed here was
reviewed twice, the second time with 0 findings.

# Sev Finding Verdict Evidence / action
1 ❌ Stored NULL-holding upper bounds (skip index and part-level minmax_<col>.idx) are misread by 26.3, 26.8 and 26.9 AGREE design replaced: no stored bound changes; parts written by this build read like 26.8-written ones on all three
2 ⚠️ "Rewritten by a merge" is false for part-level bounds (MergeTask combines the stored ones) AGREE claim removed; old parts are covered by the reader
3 💡 The description said the set index loses upper-side pruning, but it still evaluates its stored values AGREE, fixed in the text changelog and trade-off name only the minmax index and part-level pruning
4 💡 04327_106948_minmax_skip_index_nan: the comment's first sentence says the Array index keeps its pruning; now only the lower side noted, not blocking the following sentence states the upper end is unbounded
5 💡 The same widen-if-needed call shape is written at three call sites noted, not blocking the logic itself is one helper
6 💡 The per-granule copy also copies the right end it overwrites noted, not blocking matched types only: 7.9 -> 10.2 ms over 31k granules (debug)

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per
finding.

Session id: cron:clickhouse-review-self-slot-58:20261024-200600

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. 05045_minmax_index_container_bound_nan_null differs from its reference in 28 lines on master and in 21 lines on this PR's previous head; fixed rows, no randomness.
b Root cause explained? Yes. The max of IColumn::getExtremes for an Array or Map ranks a NULL or NaN element lowest, and partial bounds merge in Field order (nested NULL first), while comparisons and IN rank such an element above every value. A matching row can lie above the stored max, and a merged min holding a NULL above a row.
c Fix matches root cause? Yes. The readers of these bounds (minmax and set skip indexes, part-level pruning, primary key bounds) read the upper end of such a column as +inf and a lower end holding a NULL as -inf. No stored bound changes, so old parts and older versions are not affected.
d Test intent preserved / new tests added? Yes. 05045 keeps every earlier result query and adds NULL, set index, part-level, merge, primary key and min/max arms. Its upper-side pruning arms, and one arm of 04327_106948_minmax_skip_index_nan, now assert pruning on the lower side.
e Both directions demonstrated? Yes. Red on master and on the previous head, green on the fix (100 randomized runs). Each of 7 mutants reddens only its own arms.
f Fix is general across code paths? Yes. All four consumers of these bounds are covered; the _minmax_count_projection filter is not reached by a predicate on the column (measured), and served min/max values are unchanged.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Nullable, LowCardinality(Nullable), Map values, Array(Tuple), a top-level Tuple holding an Array, NaN, NULL with NaN, GRANULARITY 1 and 2, merged parts. Array(String) keeps upper-side pruning; Dynamic, Variant and JSON types are not matched.
h Backward compatible? (maintainer-approved exception only) Yes. No format, setting or stored bound changes. Parts written by 26.8 and master read correctly; parts written by this build read like 26.8-written ones on 26.3, 26.8 and 26.9.
i Invariants and contracts preserved? Yes. The shared bounds are never mutated (the widened copy is local to the call); the widened range contains every row of the granule or part in the order each atom compares; other types take the unchanged call.

Session id: cron:clickhouse-impl-self-slot-57:20261024-165600

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @shankar-iyer @CurtizJ, could you review this? getExtremes of an Array or Map ranks a NULL or NaN element lowest for the max while comparisons rank it highest, so a matching row can lie above the stored bound; for such columns the minmax and set skip indexes and part-level pruning now read the upper end as +inf (and a NULL-holding lower end as -inf) at read time, with no stored bound or format change.

@clickhouse-gh clickhouse-gh Bot added comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. and removed comp-skip-index Skipping indexes (minmax, set, bloom) and their evaluation. labels Oct 24, 2026
Range & range = widened[i];
range.right = POSITIVE_INFINITY;
range.right_included = true;
if (fieldHasNullInside(range.left))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - ca5b9d7

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
Upgrade check (amd_release) / Changed settings are not reflected in the settings changes history (see changed_settings.txt) not from this PR (it does not touch settings): v26.10.2.103-stable ships use_query_condition_cache_for_time_conditions = false after #127632, while master's settings history still says its default became true in 26.10. Every PR whose Upgrade check started after 2026-10-24 04:17Z reports the same 1 / 0 row #127687 (mine, open)
Mergeable Check, PR praktika rollups of the row above #127687 (the owner of the row above)

CIDB has no other FAIL or ERROR row on this head (the Bugfix validation rows are the expected inversion: the new test fails on master).

Session id: cron:our-pr-ci-monitor:20261025-010006

@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 19, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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-follow-up PR origin: groeneai's own out-of-scope finding during its PR work pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

minmax index prunes rows with NaN in Array/Map on non-negated comparisons

3 participants