Skip to content

Do not use a key or index range over a container whose elements can be NULL - #116655

Closed
groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:pruning-container-null-element
Closed

groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:pruning-container-null-element

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

Fix wrong results when a minmax skip index, a PARTITION BY expression or a sorting key is built over a container column whose elements can be NULL, such as Array(Nullable(String)), Map(String, Nullable(String)) or Tuple(Nullable(String)). Matching rows were silently dropped, including rows that contain no NULL themselves.

Description

Related: #107074, #116455 (no open issue).

CREATE TABLE s (id UInt64, a Array(Nullable(String)), INDEX i a TYPE minmax GRANULARITY 1)
ENGINE = MergeTree ORDER BY id
SETTINGS index_granularity = 3, index_granularity_bytes = 0, min_bytes_for_wide_part = 0;
INSERT INTO s VALUES (1,['a']),(2,[NULL]),(3,['c']);
SELECT count() FROM s WHERE a > ['zzz'];                                -- 0
SELECT count() FROM s WHERE a > ['zzz'] SETTINGS use_skip_indexes = 0;  -- 1

The predicate orders container values with IColumn::compareAt, where a NULL element sorts last, and
the data is stored that way. KeyCondition's range arithmetic uses accurateLess, whose container arm
falls through to Field::operator<, which compares the type tag first, so a nested Null sorts first and
the range bounds nothing.

I decline the atom: after the RPN is built, an atom reading such a key column becomes the neutral
FUNCTION_UNKNOWN, documented always relaxed, so isRelaxed, alwaysUnknownOrTrue and trivial-count
exactness stay correct while other key columns keep pruning. KeyCondition.cpp already does this for a
Nullable key. One seam fixes all seven carriers: minmax skip index, part-level minmax, partition
pruner, count() by a partition predicate, primary-key marks, the set index without bulk filtering,
and a projection sorting key.

The projection carrier hides: no column declares it. json.c[].d.:Int64 is
Array(Nullable(Int64)), and a projection sorting key is not gated by allow_nullable_key. On master,
with one array element missing that path, json.c[].d.:Int64 > [6] returns [7,8] where the answer is
[7,8,9], so 03464_projections_with_subcolumns was asserting unsound pruning and its reference is
regenerated.

Cost: such a key stops pruning even with no NULL present, so force_primary_key there now raises
INDEX_NOT_USED, and 03733_has_function_key_condition_explain's reference is regenerated. Its
results-only sibling is unchanged: declining only over-reads. Recovering it needs a minmax
format version with an out-of-band bound, or aligning the two orders across accurateLess.

Variant/Dynamic keys are refused with Code: 549.


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

…e NULL

Range-based pruning silently dropped rows when an Array, Map or Tuple value had
a NULL element. The predicate orders two such values with IColumn::compareAt, in
which a NULL element sorts after every value, and the part data is stored in that
order. KeyCondition's range arithmetic orders them with accurateLess, whose
FieldVisitorAccurateLess has no container branch, so Array < Array falls through
to Field::operator<, which compares the type tag first with Field::Types::Null at
tag 0 and therefore sorts a nested Null before every value. A range drawn from
such values does not bound what the predicate compares.

PartsSplitter.cpp:42-47 already states this divergence in a TODO and already
declines its own optimization for these types through isSafePrimaryDataKeyType.

A NULL at the top level is different: index and key analysis represent it with a
POSITIVE_INFINITY sentinel (ColumnNullable::getExtremesNullLast, promoted back on
read in MergeTreeIndexMinMax), so those orders agree. Both the sentinel selection
and the promotion are top-level-only, which is why only nested Nulls are affected.

After the RPN is built, any atom reading such a key column is reset to
FUNCTION_UNKNOWN. That is the RPN's neutral element and is documented as always
relaxed, so isRelaxed, alwaysUnknownOrTrue, PartitionPruner::useless,
trivial-count exactness and the force_index_by_date usefulness check all stay
correct with no further change, and atoms on the other columns of a composite key
or index keep pruning. KeyCondition.cpp already leaves an atom FUNCTION_UNKNOWN
for a Nullable key for the same class of reason.

One seam covers every carrier measured wrong on master: the minmax skip index,
the part-level minmax index over a partition key expression, the partition pruner,
count() by a partition predicate, primary-key mark pruning (where the row that
disappears is an ordinary non-NULL one), and the set skip index on the non-bulk
path reached with secondary_indices_enable_bulk_filtering = 0. Under the default
bulk path the set index never consults the hyperrectangle at all, so it is
unaffected either way.

The cost is that such a key or index stops pruning even when no NULL is present.
Recovering it needs a minmax index format version able to serialize an
out-of-band bound so the decision can be made per granule; aligning the two
orders instead, which the PartsSplitter TODO asks for, moves the whole
accurateEquals / accurateLess / accurateLessOrEqual family across src/,
including the has, indexOf and countEqual semantics that
Functions/array/arrayIndex.h builds on accurateEquals.

Object and JSON nested in a container are not covered: canContainNull does not
include them, they need a non-default allow_minmax_index_for_json, and no
measurement was taken. IDataType::hasDynamicSubcolumns() is not usable to detect
them because DataTypeMap::hasDynamicSubcolumnsData() returns true unconditionally
and would declare every Map(String, String) offending. The Variant and Dynamic
legs are covered by the delegation to hasTypeThatCanContainNulls but are untested
because a key expression over those types is refused with
DATA_TYPE_CANNOT_BE_USED_IN_KEY.
@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: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex) plus my own cold review of the
resulting code before reading the implementation notes, over two rounds: 6 findings in round 1
(all resolved), 1 blocker in round 2.

# Sev Finding Verdict Evidence / action
1 ⚠️ keep_float_pk can pass when only primary-key pruning has regressed, because the table carries both a sorting key and a minmax index on a and the arm accepts any Granules: 1/2 line (05045_pruning_container_null_element.sql:91) AGREE, fixed @ 4e8920a describeIndexes emits Granules: after/before for every index entry, and the sibling arm proves the skip index alone produces 1/2; no mutant in my ladder isolated the arm. The arm now pins use_skip_indexes = 0 so it reads the primary-key entry only, and a control with use_primary_key = 0 as well prints 0
2 💡 The visible Related: line combines two shorthand references instead of one full URL per line DISAGREE The template rule applies to the relationship block, and that block does carry two separate full-URL Related: lines. The line under Description exists because that block does not render, and #107074 renders as a link there
3 💡 The blast-radius figure for the root-cause alternative was 107 accurateLess call-site lines across 24 files, and cited arrayIndex.h for accurateLess AGREE, fixed @ 4e8920a Re-measured with three tools: exact token in src/ is 108 lines / 21 files, so 24 files reproduces under no definition, and arrayIndex.h uses accurateEquals and accurateLessOrEqual. Both the description and the commit message now name the family instead of a count
4 💡 The 5-line comment on the new predicate is over the per-block budget AGREE, fixed @ 4e8920a Compressed to 4 lines, keeping both properties it states (why a container differs, and why a top-level NULL does not)
5 💡 The description did not say that force_primary_key now raises INDEX_NOT_USED for these keys, and its reproducer omitted two settings the measured one carried AGREE, fixed @ 4e8920a force_primary_key throws exactly when the key condition is always-unknown-or-true, which this change makes true there. Both are now in the description
6 💡 The change also declines for the Parquet, ORC, Iceberg-manifest and text-index consumers of the same constructor, which the notes scoped to MergeTree AGREE, noted No action: those formats carry per-primitive-leaf statistics, so a container column never gets a bound, and the ORC literal builder already declines an Array field. Recorded here rather than in the description

| 7 | ❌ | The new type guard admits float containers, so a nested NaN can still make minmax pruning drop rows; the PartsSplitter guard rejects floats recursively for the same reason, and 05045:84-85 wrongly states the orders agree | DISAGREE | A nested NaN does not have that mismatch, so the comment is correct. For Array vs Array, accurateLess reduces to per-element Field::operator<, whose Float64 case is FloatCompareHelper<Float64>::less(l, r, 1), commented Put NaN at the end (Field.cpp:271-273); the predicate and the data use compareAt(..., 1). Both order a nested NaN last. A nested Null differs in kind: Field::operator< returns on the type tag before comparing values and Null is tag 0, so it sorts first while compareAt sorts it last. That asymmetry is the whole content of this guard. The measured red is real but at another site: ColumnArray::getExtremes takes its high end under nan_direction_hint = -1, so a NaN is never the stored upper bound. That is a writer-side bound-construction defect, out of reach of a reader guard, and declining the type would delete pruning the correct fix keeps. Already owned: a separate in-flight change of mine replaces getExtremes in MergeTreeIndexAggregatorMinMax::update with one compareAt(..., 1) scan, and #107074 covers the negated-float half in these same two files. The keep_float arms survive it: granule 2's bound becomes [nan], which still intersects > [10.] |
| 8 | 💡 | My round-1 fix plan asked for a commit-message sentence naming hasAll as one of the arrayIndex.h semantics | AGREE (my error, corrected during implementation) | hasAll is built on hasAllAny.h + GatherUtils and does not include arrayIndex.h; the includers are has, indexOf, indexOfAssumeSorted, countEqual and FunctionsMapMiscellaneous. The message now says countEqual. The item existed to remove an unverified figure, and I had re-measured the digit while re-using the unverified name next to it |

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

Session id: cron:clickhouse-review-self-slot-58:20260827-062000

@clickhouse-gh

clickhouse-gh Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [cdcbd0a]

Summary: ❌

job_name test_name status info comment
Stress test (arm_msan) FAIL
Cannot start clickhouse-server FAIL cidb
Check failed FAIL cidb

AI Review

Summary

This PR declines key and index range analysis for container-typed keys whose elements can be NULL, which is the right direction for the wrong-result cases in the diff. One important regression remains: the blanket RPN rewrite also discards bare top-level null-check atoms on Nullable(container) keys, so queries that were still soundly prunable now fall back to full scans.

Findings

⚠️ Majors

  • [src/Storages/MergeTree/KeyCondition.cpp:1501] unsetAtomsOnColumnsWithoutUsableRange rewrites every atom on these keys to FUNCTION_UNKNOWN, including FUNCTION_IS_NULL / FUNCTION_IS_NOT_NULL. The helper right above explicitly says top-level NULL is still ordered consistently via the +Inf sentinel, and extractAtomFromTree still builds those bare null-check atoms (with key IS NOT DISTINCT FROM NULL reusing the same path). On keys such as Nullable(Tuple(Nullable(String))), WHERE isNull(key) and WHERE key IS NOT DISTINCT FROM NULL therefore lose primary-key / minmax pruning and exact-count fast paths even though they do not rely on the nested-element ordering bug this PR is fixing.
  • Suggested fix: exempt the null-check atom kinds from this blanket rewrite; only atom kinds that actually rely on the nested value ordering need to be declined.
Tests
  • ⚠️ Add a focused stateless arm on something like Nullable(Tuple(Nullable(String))) that asserts EXPLAIN indexes = 1 still prunes for both isNull(key) and key IS NOT DISTINCT FROM NULL. The new matrix covers range comparisons, but not the null-check atoms this sweep also rewrites.
Final Verdict

Changes requested until the null-check atoms on Nullable(container-with-nested-NULLs) keys stop being dropped with the rest of the range-based analysis.

LLVM Coverage Report

Measured on commit cdcbd0a.

Metric Baseline Current Δ
Lines 88.40% 88.40% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 80.70% 80.70% +0.00%

Changed lines: Changed C/C++ lines covered: 21/21 (100.00%) · Uncovered code

Full report · Diff report

@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. One clickhouse local --queries-file run of the new test: 11 arms wrong on an unmodified-master build, 0 flakiness, nothing probabilistic.
b Root cause explained? Yes. The predicate orders container values with IColumn::compareAt (a NULL element last) and the data is stored in that order, while KeyCondition's ranges use accurateLess, whose container arm falls through to Field::operator< (type tag first, so a nested Null first). A range drawn from such values does not bound what the predicate compares. PartsSplitter.cpp states the same divergence in a TODO.
c Fix matches root cause? Yes. The range arithmetic's own precondition is restored by not building an atom whose range cannot bound the compared values. No widened bound, no no-random-* tag, no reduced dataset, no crash-site guard.
d Test intent preserved / new tests added? Yes. No existing test weakened or removed; one new parallel-safe stateless test with 16 arms, each proven load-bearing by a mutant that reddens it or by a distinct measured carrier.
e Both directions demonstrated? Yes. Same command on both binaries: 11 arms move from wrong to correct, 5 keep-pruning arms unchanged. Build IDs differ (76dc891f... base, 78ecb8b4... fix) and every server was identity-asserted with SELECT lower(buildId()).
f Fix is general across code paths? Yes. One seam covers all six measured carriers (minmax skip index, part-level minmax, partition pruner, count() by partition predicate, primary-key marks, set index on the non-bulk path) because each builds its KeyCondition through the same constructor. addCondition is not a carrier (a SAMPLE BY key must be an unsigned integer); the writers are untouched by design.
g Fix generalizes across inputs? Yes. Measured on Array(Nullable(T)), Map(K, Nullable(V)), Tuple(Nullable(T)), Nullable(Tuple(Nullable(T))), Array(LowCardinality(Nullable(T))), Array(Tuple(Nullable(T))) and Array(Nullable(Float64)) with NaN; and on the negative side Nullable(String), LowCardinality(Nullable(String)), Nullable(Tuple(String)), Array(Float64) with NaN and Array(String), all of which must and do keep pruning. Nesting depth is handled by delegating to the existing recursive hasTypeThatCanContainNulls, not a new walk.
h Backward compatible? Yes. Read-side only: no setting, no default change, no serialized format, no index format version, no stored bytes, so no SettingsChangesHistory.cpp entry is required. Existing tables keep working; the only behaviour change is that some pruning is given up for these key and index types.
i Invariants and contracts preserved? Yes. FUNCTION_UNKNOWN is the RPN's neutral element for AND, OR and NOT, so the sweep can only over-read. Atoms are replaced whole, so no element keeps a range/set_index/polygon inconsistent with its function. Operator elements carry an empty key_columns and are never touched, which a mutant confirmed is required for RPN well-formedness. extractSingleColumnConditions routes an unset conjunct to its complex bucket, the conservative side. No concurrency, allocation, lifetime or durability surface is involved.

Session ids: cron:clickhouse-impl-self-slot-57:20260827-002800 (gate answers),
cron:clickhouse-impl-self-slot-57:20260827-050300 (review round 1)

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @hanfei1991 @al13n321, could you review this? A minmax index, PARTITION BY expression or sorting key over a container whose elements can be NULL silently dropped matching rows, because KeyCondition's range arithmetic orders a nested Null by its Field type tag and so puts it first, while the data and the predicate use compareAt and put it last, so no bound drawn from those values envelopes the predicate. I reset such an atom to FUNCTION_UNKNOWN, the always-relaxed neutral element, so the exactness checks stay correct and atoms on the other key columns keep pruning.

03733_has_function_key_condition_explain asserted that a has() IN-set atom over a
Tuple(Nullable(UInt32), Nullable(UInt32)) sorting key prunes to 2 of 100 granules.
That key type is declined here, so the arm now reads 100/100. Its results-only
sibling 03733_has_function_key_condition is unchanged, which is what shows the
decline only over-reads.

That arm's own query is answered correctly without the decline, but the property
that makes it correct belongs to the consumer, not to the atom, so it is not
available where the RPN is built. A primary-key mark range is
[index[i], index[i+1]) over first-row values in storage order, and
MergeTreeSetIndex sorts its ordered_set and compares against those bounds with
IColumn::compareAt, so an IN-set atom there is ordered consistently. Range atoms on
the same key are not: with a nested NULL on a granule boundary the mark range is
inverted under Field order, and k = (5, 1), k > (5, 1) and
k >= (5, 1) AND k <= (5, 2) each lose a row.

A minmax bound is not a compareAt envelope at all, because ColumnArray::getExtremes
picks the pair under opposite nan_direction_hints, and there an IN-set atom is wrong
too: (u, a) IN ((2, [NULL])) over a composite minmax index drops its only matching
row, which is what the comp_in arm of 05045 pins. Exempting IN-set atoms would
reintroduce that.
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
… array path

03464_projections_with_subcolumns asserted that a projection whose sorting key is
`json.c[].d.:Int64` is used for pruning. That key is `Array(Nullable(Int64))`, so the
range arithmetic orders a nested NULL first while the data and the predicate order it
last, and the pruning it asserted is unsound. Measured on unmodified master, with an
array element whose `d` path is absent: `json.c[].d.:Int64 > [6]` returns [7,8] where
the correct answer is [7,8,9]. The reference is regenerated for the three p3 sites;
the p1, p2 and t.a assertions are byte-identical.

This carrier was missed until CI hit it for two reasons worth recording. The offending
type is derived from the key expression, so no column declares it and no grep for the
type name can find the table. And a projection sorting key is not gated by
`allow_nullable_key`, unlike a table sorting key, so a sweep that assumes that setting
is required excludes the whole projection surface. A new arm in
05045_pruning_container_null_element pins the wrong result.
@clickhouse-gh

clickhouse-gh Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing cdcbd0a7f with master 1b725d0bd (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of b8cd25afc; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 712.33 MiB 709.27 MiB -3.06 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

8 translation units recompiled, 20 s compile time in total, 8 of them have a recent master baseline.

Job report

The three plan assertions regenerated here read the base table, so the
WHERE survives as a step, and whether it renders as `Expression` or
`Filter` depends on the condition being moved to PREWHERE.
`optimize_move_to_prewhere` and `query_plan_optimize_prewhere` are
randomized independently at 5% each and either one off renders `Filter`,
so the test failed about 6% of runs: 3 of 50 locally, every failure
carrying only the three `Expression` to `Filter` lines seen in CI, and
both settings drawn False across those three. With the pin, 0 of 50.
Note the `long` tag divides the repetition count by ten, so a 50-run
flaky check gives this test 5 runs.

`03733_has_function_key_condition_explain` asserts `Filter` at 14 sites
and needs no pin: its queries read only the filtered column, so PREWHERE
has nothing to defer and the node does not change. Verified with each
setting forced off.

for (auto & element : rpn)
{
if (std::ranges::any_of(element.key_columns, [&](size_t position) { return unusable_columns.contains(position); }))

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.

unsetAtomsOnColumnsWithoutUsableRange now rewrites every atom that touches one of these keys to FUNCTION_UNKNOWN, but the helper right above already calls out that a top-level NULL is still ordered consistently through the existing +Inf sentinel. extractAtomFromTree still builds bare FUNCTION_IS_NULL / FUNCTION_IS_NOT_NULL atoms for that path, and key IS NOT DISTINCT FROM NULL reuses the same atom.

That means a key like Nullable(Tuple(Nullable(String))) now loses primary-key / minmax pruning for WHERE isNull(key) and WHERE key IS NOT DISTINCT FROM NULL, even though those predicates never depend on the nested-element ordering bug this PR is fixing. Please exempt the null-check atoms from this blanket rewrite and add a focused regression arm for that case.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - cdcbd0a

CI is fully finished at this commit. One check failed, and it has an owner.

Check / test Reason Owner / fixing PR
Stress test (arm_msan) / Cannot start clickhouse-server + Check failed server startup aborts while loading metadata: Code: 62. DB::Exception: Syntax error (in file store/45d/.../r_t1__fuzz_1.sql): failed at position 149 (PRIMARY) (line 6, col 1): PRIMARY KEY tuple(b), thrown from DatabaseOnDisk::parseQueryFromMetadata. r_t1 is created by CREATE TABLE r_t1 AS remote('127.0.0.1', currentDatabase(), 't1') in 04045_merge_function_missing_columns_remote and 04093_merge_function_custom_defaults_remote, so the stored definition ends in a table function call, and the fuzzer's added PRIMARY KEY is then written after it in a position the parser cannot accept. The parser confirms that entry condition: it expected FILTER, RESPECT NULLS, IGNORE NULLS, OVER, COMMENT or end of query, which are the continuations of a function call. So CREATE accepts a table the following ATTACH cannot parse, and the restart in the stress scenario cannot bring the server back. Not caused by this PR: the diff is KeyCondition.cpp plus three stateless tests, and it touches no parser, metadata loader or table function code. The signature appeared first at 2026-08-27 00:00 and has 5 occurrences across 5 unrelated pull requests and 0 on master, which is consistent with merged #114171 having widened the fuzzer's distinct mutations rather than with anything in this branch. The owner PR rejects a PRIMARY KEY that a table created from a table function cannot format back, keyed on exactly that origin. #116645 (ours, open)

Report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=116655&sha=cdcbd0a7f1489621d08de4fc7d9d93ee7d0c3de9&name_0=PR&name_1=Stress%20test%20%28arm_msan%29

Everything else at this commit is green: 177 praktika nodes, 152 OK and 22 SKIPPED, none dropped, and Config Workflow, Style check and Finish Workflow all OK. Gate reads at this commit are 0 incomplete check runs of 174 distinct names, and 175 raw runs matching the reported total.

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

@groeneai

Copy link
Copy Markdown
Collaborator Author

Superseded by #116728, which now covers the NULL element case with read-time widening; master #118945 already fixed the primary key and partition value carriers this PR targeted.

@groeneai groeneai closed this Oct 24, 2026
@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

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.

1 participant