Skip to content

Do not build a key range from a NULL or a NaN nested in a Tuple - #118944

Merged
alexey-milovidov merged 20 commits into
masterfrom
pk-tuple-nested-nan-null-118687
Oct 12, 2026
Merged

alexey-milovidov merged 20 commits into
masterfrom
pk-tuple-nested-nan-null-118687

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 9, 2026 •

Copy link
Copy Markdown
Member

Field::isNull and Field::isNaN only look at the top level of a Field, so a NULL or a NaN nested in a Tuple slips past every check built on them. A whole-tuple comparison carries exactly that, and primary-key analysis then treats such a value as an ordinary point of key order:

  • A constant with a nested NaN produced a real key range. At row level t <= (nan, 3) is false for every row, but in key order NaN sorts above every ordinary value, so every granule was judged wholly inside (-Inf, (nan, 3)] and the exact-count projection counted its rows without evaluating the filter: count() answered 8 where SELECT * returned nothing. Once a key transform maps the constant into key space (ORDER BY toString(t)), a nested NULL does the same: '(NULL,1)' = '(NULL,1)' matches in key space while t = (NULL, 1) is NULL for every row.
  • A NaN nested in a granule bound is the mirror case: the granule holding it can never be proven wholly inside a comparison range, because the row-level comparison is false there while key order gives the value a definite position. count() answered 6 where the same predicate returned 2 rows.

A constant that holds a nested NULL or NaN no longer produces an atom, so the granules are read and the filter decides. On the bound side only the containment claim is dropped - intersects is left as computed, so every pruning decision stays the over-approximation the two-valued range algebra requires. The bound side covers a nested NULL as well as a nested NaN: WHERE rejects a row whose comparison is NULL just as it rejects a false one, so a granule whose bound holds one cannot be claimed to match wholly either - the same reasoning mayReadNullKeyValue already applies to a flat Nullable key column.

Closes: #118687
Closes: #118837
Closes: #117819
Related: #117501

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

Fixed count() counting rows that the filter rejects when a whole-tuple comparison against a Tuple primary key involves a NULL or a NaN nested in the constant, or a NaN nested in the key data.


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

Version info

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

`Field::isNull` and `Field::isNaN` only look at the top level of a
`Field`, so a `NULL` or a `NaN` nested in a `Tuple` slips past every
check built on them. A whole-tuple comparison carries exactly that, and
primary key analysis treated such a value as an ordinary point of key
order.

On the constant side that produced a real key range. At row level
`t <= (nan, 3)` is false for every row, but in key order `NaN` sorts
above every ordinary value, so every granule was judged wholly inside
`(-Inf, (nan, 3)]` and the exact-count projection counted its rows
without evaluating the filter. Once a key transform maps the constant
into key space (`ORDER BY toString(t)`), a nested `NULL` does the same:
`'(NULL,1)' = '(NULL,1)'` matches in key space while `t = (NULL, 1)` is
`NULL` for every row. Such a constant no longer produces an atom, so the
granules are read and the filter decides.

On the bound side a granule whose bound holds a nested `NaN` or `NULL`
can never be proven wholly inside a comparison range - `WHERE` rejects a
row whose comparison is `NULL` just as it rejects a false one - so only
the containment claim is dropped. `intersects` is left as computed,
which keeps every pruning decision the over-approximation the two-valued
range algebra requires.
@clickhouse-gh

clickhouse-gh Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [13c3a58]

Summary: ✅


AI Review

Summary

This PR hardens KeyCondition around whole-Tuple comparisons that hide nested NULL / NaN values, and the current head includes the follow-up fixes discussed on the earlier review threads. I reviewed the current diff, read the existing discussion, and checked the relevant KeyCondition paths plus the new stateless coverage. I do not see any remaining correctness, pruning-safety, or exact-count regressions attributable to the changes in the current head.

Missing context / blind spots
  • ⚠️ I could not run the new stateless test locally because this checkout does not contain a prepared build directory or test binary; a local clickhouse build would close that gap.
Final Verdict

✅ No new findings.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 9, 2026
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 9, 2026
alexey-milovidov added a commit that referenced this pull request Sep 9, 2026
The `t <= (5., 3)` count is answered by the implicit projection, which
claims a granule whose bound holds a NULL nested in the tuple matches
wholly - a separate defect of the range algebra, fixed by the
`KeyCondition` change in #118944, not by the boundary repair here. Turn
the projection off for that one query so the test witnesses only what
this change fixes.
@clickhouse-gh

clickhouse-gh Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 13c3a589c with master 2e77cbc01 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 18b5a991f; 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 778.13 MiB 778.83 MiB +721.13 KiB (+0.09%)

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.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

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

Job report

@alexey-milovidov

Copy link
Copy Markdown
Member Author

The one red check, AST fuzzer (amd_release, oracle), is a pre-existing bug on master and not related to this change. Its partitioning oracle found SELECT id FROM tab WHERE hasToken(str, 'foo') over the table of 02346_text_index_nullable: the three legs return 7 rows where the table has 5.

The cause is the text index's virtual-column substitution on a Nullable indexed column, which this pull request does not touch (it only changes KeyCondition). Minimal repro on a build without this change:

CREATE TABLE tab (id UInt32, str Nullable(String), INDEX idx(str) TYPE text(tokenizer = 'splitByNonAlpha')) ENGINE = MergeTree ORDER BY id;
INSERT INTO tab VALUES (1,'hello world'),(2,NULL),(3,'foo bar'),(4,NULL),(5,'hello foo');

SELECT groupArray(id) FROM (SELECT id FROM tab WHERE NOT hasToken(str, 'foo') ORDER BY id);
-- [1,2,4]
SELECT groupArray(id) FROM (SELECT id FROM tab WHERE NOT hasToken(str, 'foo') ORDER BY id SETTINGS use_skip_indexes = 0);
-- [1]  <- correct: hasToken(NULL, 'foo') is NULL, so NOT of it is NULL and `WHERE` rejects the row

EXPLAIN actions = 1 shows why: the filter becomes NOT CAST(__text_index_idx_hasToken_… AS Nullable(UInt8)). The virtual column is a plain UInt8 that holds 0 for a NULL row, and the cast cannot bring the NULL back, so the negation turns it into a match. MergeTreeIndexConditionText already refuses the affix-pattern form on a Nullable indexed column for exactly this reason (affix_patterns_allowed); the token-search substitution needs the same refusal.

alexey-milovidov and others added 2 commits September 17, 2026 06:39
…-null-118687

# Conflicts:
#	src/Storages/MergeTree/KeyCondition.cpp
…IN` on a nested `NULL` or `NaN`

The key-bound check walks `Field`s read from stored key data, so a recursive
descent would map the nesting depth of a value to native stack depth. Reuse
`anyFieldSatisfies`, whose explicit worklist keeps it off the stack, with a
non-capturing predicate; the constant side and the bound side ask the same
question, so the two helpers collapse into one `hasNullOrNaNInside`.

The set-index path built by `tryPrepareSetIndexForIn` was suspected of the
same wrong-results hole through `IN` / `NOT IN`. It is not: both the set index
and the row-level `IN` compare whole tuples by hash, so a nested `NULL` or a
`NaN` matches its identical copy on both sides, and an unpacked set literal
drops the element whose top-level `Nullable` column is `NULL` on both sides as
well. Pin that `count()` agrees with the real read for a literal set, a
subquery set, a key transform and partition pruning.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, the one red check, AST fuzzer (amd_release, oracle), is the pre-existing text-index bug analysed above (NOT hasToken over a Nullable indexed column returns the NULL rows). It still reproduces on master merged today. It is tracked in #106922 and a fix is in progress in #113332. Please check that the fix there covers the NOT hasToken direct-read substitution, or provide it in a separate PR if it does not.

Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator

Checked: #113332 does cover the NOT hasToken direct-read substitution, so no separate PR is needed on coverage grounds, and nothing on this branch needs to change. That check clears when #113332 lands.

I measured it at today's master rather than quoting an older run. Two Debug binaries from one tree: master 2e92c9d68a4a4 (build id c26629de70ac5626) and the same master with refs/pull/113332/head c11a652e merged (build id 784da8c1d136e0ea). Oracle is an index-free table holding the same five rows of 02346_text_index_nullable.

arm no index master + #113332
your three-leg total on hasToken(str, 'foo') 5 7 5
NOT hasToken(str, 'foo') [1] [1,2,4] [1]
NOT hasToken(str, toLowCardinality('foo')) [1] [1,2,4] [1]
NOT hasAllTokens(str, 'foo bar') [1,5] [1,2,4,5] [1,5]
NOT hasAnyTokens(str, 'foo bar') [1] [1,2,4] [1]
PREWHERE NOT hasToken(str, 'foo') [1] [1,2,4] [1]
LowCardinality(Nullable(String)) column [1] [1,2,4] [1]
NOT hasPhrase(str, 'foo bar'), support_phrase_search = 1 [1,5] [1,2,4,5] [1,5]

It repairs the substitution rather than declining it, which is the interesting part relative to the affix_patterns_allowed refusal you pointed at. EXPLAIN actions = 1, same site:

master:    NOT CAST(__text_index_idx_hasToken_2300... AS Nullable(UInt8))
+ #113332: NOT if(str.null, NULL, __text_index_idx_hasToken_2300...)

EXPLAIN indexes = 1 still shows Name: idx and the virtual column is still read, so granule pruning and the direct read survive. findNullableDataArgument skips constant arguments and keys on the non-const Nullable argument, and addNullsOfArgument wraps the replacement node itself, so the needle spelling cannot matter; the two spellings and the LowCardinality column above are the arms I ran.

One practical note: #113332 has had no new commit since 2026-09-03 and now conflicts with master. The conflict is a single hunk in MergeTreeIndexTextPreprocessor.h, where master renamed isLowerOrUpper() to isASCIILowerOrUpper() while that branch adds two accessors in the same block; keeping both sides is the entire resolution, and that is the build measured above.

My earlier fix for this, #107078, was closed as replaced by #113332, so I am not opening a competing PR on my own initiative. If you would rather have the wrong result off master without waiting for the rest of that branch, I can put up a separate PR carrying only the null restoration at the substitution site, credited to #113332, plus the regression test. Your call.

alexey-milovidov and others added 2 commits September 24, 2026 07:03
…-null-118687

# Conflicts:
#	src/Storages/MergeTree/KeyCondition.cpp
…h ordinary bounds

A granule of `Tuple(Int32, Nullable(Int32))` values `(2, 1), (2, NULL), (3, 0)` has the
bounds `[(2, 1), (3, 0)]`, so the bound check in `checkInHyperrectangle` does not fire,
while the middle row compares as `NULL`. `rangeOfKeyColumnMayHoldNull` now also reports
a composite key column (`Tuple`, `Array`, `Map`) whose type may carry a `Nullable` or a
floating-point value below its top level, so `mayReadNullKeyValue` drops `can_be_false`
for it in both the dense and the sparse path. Pruning is unaffected.

The `KeyCondition.cpp` part of this change went into the preceding merge commit by
mistake; this commit adds the tests. Without the fix `count()` returns 3 for the
`NULL` case while the real read returns 2.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai thanks for the measurement - no separate PR needed; the fuzzer red here clears once #113332 lands. Meanwhile this branch is merged with master again and the remaining review thread (a nested NULL/NaN inside a granule with ordinary bounds) is addressed in abadb08.

alexey-milovidov and others added 2 commits October 2, 2026 12:42
…an claim it

The type-based guard added for a `NULL` or a `NaN` hiding inside a granule of a
composite key dropped `can_be_false` for every atom over such a key column, so an
upper-bounded comparison like `t <= (1000., 0)` over a `Tuple(Float64, Int32)` key
lost exact counting. That broke the control in
`05136_117819_exact_count_nan_in_tuple_key`, which pins that only right-unbounded
range atoms are affected.

Key order puts a value with a nested `NULL` or `NaN` above every value sharing its
prefix, and at row level the comparison against an ordinary constant is then
greater, false, or `NULL`, all of which `WHERE` rejects for an upper-bounded range.
So only a range atom that reaches `+inf` (or a negated range, a set, a polygon) can
claim such a value as matching; restrict the nested check to those atoms. Pin the
upper-bounded cases in `05161_pk_tuple_nested_nan_null`.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118944&sha=abadb08e492d5aa9f873191cbe350c63a0b85672&name_0=PR
PR: #118944

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
…es a `NULL`

`canConstantBeWrappedByDeterministicFunctions` marked an atom exact when the key
transform is injective, but a transform like `toString` maps a `Tuple` value with a
nested `NULL`, e.g. `(NULL, 1)`, to an ordinary key value `'(NULL,1)'`. The row-level
comparison of such a value is `NULL`, which `WHERE` rejects, while the index compares
the key as unequal to the constant, so a negated atom (`t != (2, 1)`) claimed the
granule as wholly matching and `count()` counted the row. `mayReadNullKeyValue` could
not see it, because the key type is a plain `String`.

Now the atom is not exact when the column the transform consumes may hold a `NULL`
that the key type does not reveal: a nested `NULL`, or a top-level `NULL` mapped to a
non-`Nullable` key. Only `can_be_false` is affected, pruning is unchanged.

#118944

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
alexey-milovidov and others added 2 commits October 4, 2026 17:35
…le`-only and range-only

`Array` and `Map` comparisons are `compareAt`-based, so they never hide a nested
`NULL` or `NaN` from the index. Set atoms compare whole tuples by hash on both
sides, so `IN` / `NOT IN` keep their exact `can_be_false`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
…` or `NaN`

`deterministicTransformMayHideNull` and `hasNullOrNaNInside` walked every
nested type and value, so an `Array(Nullable(T))` or a `Map` key lost exact
atoms (and the exact-count fast path) for no correctness reason: their
comparison is `compareAt`-based and answers a definite value for a nested
`NULL`. Both now descend only through `Tuple`s, matching
`keyTypeMayHoldNestedNullOrNaN`. Add test cases for `Array` and `Map` keys.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
alexey-milovidov and others added 2 commits October 6, 2026 14:20
…ed `NULL`

`<=>` compares a `Tuple` element-wise in the null-safe way, so `t <=> (NULL, 1)`
is true for the row `(NULL, 1)`, and key order places a nested `NULL` the same
way for the key and the constant. The new early return for a `NULL` nested in
the constant and the nested-`NULL` exactness downgrade of a deterministic key
transform are about comparisons that answer `NULL`, which `<=>` never does, so
skip both for it. A nested `NaN` is still rejected: `(nan, 1) <=> (nan, 1)` is
false.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Good enough.

@alexey-milovidov alexey-milovidov self-assigned this Oct 9, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 9, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to a conflict with the base branch Oct 9, 2026
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
alexey-milovidov and others added 2 commits October 10, 2026 11:40
…tinctFrom` exception

`anyFieldSatisfies` also descends `Array` and `Map`, where a nested `NaN` compares as an
ordinary value (`[nan] <=> [nan]` is true). Use a `Tuple`-only walk, shared with
`hasNullOrNaNInside`, and add `<=>` cases on `Array(Float64)` and
`Tuple(Array(Float64), UInt8)` keys to `05161_pk_tuple_nested_nan_null`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118944&sha=e0ccbaa4f6ab491cf01dfae3250d3e4af8faa1f4&name_0=PR&name_1=Stateless%20tests%20%28arm_asan_ubsan%2C%20azure%2C%20sequential%29 (the job hit its 9000 s timeout at test 1165 of 1180 with every test passing so far) and provide a fix in a separate PR. If the fix is already in progress, link it here.

The other two red tests in that run (05233_constraint_graph_negated_ordered_comparison, 05316_secret_arguments_declared_by_engines) already have fixes on master (1586d94cccd, 351f549fe5b), which are now merged into this branch.

@groeneai

Copy link
Copy Markdown
Collaborator

The fix is already in progress: #123849 splits Stateless tests (arm_asan_ubsan, azure, sequential) into 2 hash batches. On its latest head both batches passed, in about 63 and 90 minutes against the 150-minute limit. @ Algunenano is handling its merge.

Your reading of the run at e0ccbaa is right: job.log shows 1165 of 1180 tests reached (1070 OK, 95 skipped, none failed), and the last one finished 2 seconds before Timeout exceeded [9000]. Nothing in this PR needs to change.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai thanks - noted that the sequential ASan job timeout is handled by #123849. The latest CI run on this branch is fully green, and there are no open review threads, so this PR needs no further changes.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 12, 2026
Merged via the queue into master with commit 3e9ab2b Oct 12, 2026
164 checks passed
@alexey-milovidov
alexey-milovidov deleted the pk-tuple-nested-nan-null-118687 branch October 12, 2026 03:27
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 12, 2026
aschoube added a commit to aschoube/ClickHouse that referenced this pull request Oct 13, 2026
…le-nullable-element

ClickHouse#118944 already fixes the exact
count over a `Tuple` key with a `Nullable` element: `KeyCondition::mayReadNullKeyValue`
now covers a `NULL` nested in a `Tuple` key column through
`keyTypeMayHoldNestedNullOrNaN`. Take master's `KeyCondition` and
`MergeTreeDataSelectExecutor` and keep the test as a regression test for
ClickHouse#124155: it fails before that
change and passes after it.
evillique pushed a commit to evillique/ClickHouse that referenced this pull request Nov 18, 2026
`checkInHyperrectangle` asks `mayReadNullKeyValue` whether a wholly matching
range may hold a NULL, and since ClickHouse#118944 that calls
`keyTypeMayHoldNestedNullOrNaN` for every such range of a negated range atom
(e.g. `WHERE c2` over a `UInt8` key column, analysed as `c2 NOT IN [0, 0]`).
The helper unwrapped the key type with `removeLowCardinality` /
`removeNullable`, which return `DataTypePtr` by value, so every call made
shared_ptr copies of the table's key type objects. All analysis threads share
those objects, so the reference-count cache line bounced between cores:
`perf` puts 99.6% of the helper's samples on its `lock incq` / `lock xadd`
instructions, and on the query of ClickHouse#131715 primary key analysis takes 20.3 s
of CPU at 8 threads instead of 7.3 s.

The answer depends only on the type, so unwrap through references and raw
pointers instead, with the same checks in the same order. At one thread the
copies were cheap and the time is unchanged.

Add a performance test with many wholly matching ranges in parts analysed in
parallel, and three cases to 05161 that each fail when one of the helper's
unwrap steps is dropped (a NULL in an inner Tuple, under
LowCardinality(Nullable), below a Nullable(Tuple) key). The float check is
not covered: the condition already relaxes those atoms.

Closes ClickHouse#131715

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