Skip to content

Keep null-aware set atoms out of the nullable-key exact-count safeguard - #121089

Open
groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:groeneai/keycondition-null-set-exactness
Open

groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:groeneai/keycondition-null-set-exactness

Conversation

@groeneai

@groeneai groeneai commented Sep 19, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #90461

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

...

Description

On a debug or sanitizer build, SELECT count() over a Nullable primary key aborts with
Logical error: 'Inconsistent KeyCondition behavior' when the filter's set holds a NULL:

Reproducer
CREATE TABLE t (x Nullable(UInt64)) ENGINE = MergeTree ORDER BY x
SETTINGS allow_nullable_key = 1, index_granularity = 1;
INSERT INTO t VALUES (1), (2), (3), (4), (NULL), (NULL), (NULL);
SELECT count() FROM t WHERE has(CAST([NULL], 'Array(Nullable(UInt64))'), x);
SELECT count() FROM t WHERE x IN (SELECT arrayJoin(CAST([NULL], 'Array(Nullable(UInt64))'))) SETTINGS transform_null_in = 1;

The #96844 carrier is the same shape at scale. Its server.log shows the atom is nullIn and the
table holds 48 NULL rows, written by two divideOrNull(number, NULL) inserts that the report's
generated reproducer drops, which is why that paste answers 0 instead of aborting.

It takes the server down mid-job, from markRangesFromPKRange. Found by
AST fuzzer (amd_debug, targeted) on #115919 @ a8e3557f
(report)
and on #96844 @ 8c888f34
(report).

Root cause. count() from the implicit exact-count projection asks KeyCondition for exact mark
ranges. An ordinary comparison is NULL for a NULL key value, so checkInHyperrectangle forces
can_be_false on every atom that answers NULL for one, except IS NULL/IS NOT NULL, which answer
definitely. Set membership comparing a NULL as an ordinary element answers definitely too
(nullIn(NULL, {NULL}) is 1; has alike). But the RPN maps in, nullIn and has onto one
FUNCTION_IN_SET, so the safeguard could not tell them apart: it overrode the set index's
already-exact verdict, and the ranges stopped matching matchesExactContinuousRange.

Change. Carry the distinction on the RPN element and skip those atoms in both
mayReadNullKeyValue overloads, but only over a bare key: a monotonic wrapper is not applied to the
NULL stand-in bound, so for a wrapped key the algebra cannot describe what the wrapper does to a NULL
row, and the safeguard stays. can_be_true is untouched, so pruning is unaffected and every count
stays the one a plain read returns.

Validation. The abort is deterministic before and silent after for nullIn, globalNullIn and
has over ascending, descending and LowCardinality(Nullable) keys; in, notIn, notHas and
NULL-free has counts are unchanged. 05083_nullable_key_exact_count commits the nullIn, has,
descending, wrapped-key and negated-set arms on both index representations, plus
EXPLAIN projections = 1 assertions that fail without the fix in a release build; the negated-set,
global and notHas arms each flip on one builder's flag alone. The rest was measured only.


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

groeneai and others added 3 commits September 19, 2026 17:31
`SELECT count()` answered from the implicit exact-count projection asks
KeyCondition for exactly matching mark ranges. A `Nullable` key column
analyses a NULL as the `+inf` stand-in of the `NULLS LAST` order, and an
ordinary comparison is NULL - so `WHERE` drops the row - for such a key,
which the two-valued range algebra cannot express. checkInHyperrectangle
therefore forces `can_be_false` on any atom that answers NULL for a NULL
argument, and excludes `IS NULL` / `IS NOT NULL`, which answer definitely.

A set-membership atom that compares a NULL as an ordinary element answers
definitely too, and deserves the same exclusion. `transform_null_in`
rewrites `x IN (subquery)` to `nullIn`, where `nullIn(NULL, {NULL})` is 1
and `nullIn(5, {NULL})` is 0; `has` needs no rewrite at all, and
`has([NULL], NULL)` is 1 while `has([3], NULL)` is 0. Neither got an
exclusion, because the RPN maps `in`, `nullIn` and `has` onto the same
FUNCTION_IN_SET, so the safeguard could not tell them apart. The set index
already returned the correct exact verdict for the NULL tail; the safeguard
then overrode it, one mark was trimmed that did not need to be, and
matchesExactContinuousRange's claim no longer matched the ranges actually
produced - reported as `Inconsistent KeyCondition behavior` and, on a debug
or sanitizer build, an abort that takes the server down mid-job. In a
release build the exact range is dropped and the optimization declines.

Carry the distinction on the RPN element instead of widening the function
enum, and skip those atoms in both the dense and the sparse
mayReadNullKeyValue. Only `can_be_false` is affected, so no pruning
decision and no query result changes for any other atom.

Exclude them only over a bare key. A set atom also carries the key's
monotonic-function chain, and applyMonotonicFunctionsChainToRange does not
apply that chain to an infinite bound, because the -Inf/+Inf indicator is
itself a `Null`-typed Field. On an all-NULL granule the algebra therefore
compares the set element against untransformed bounds, and so cannot see
that the wrapper redefines the predicate for a NULL row - or refuses it, as
a `CAST` to a non-Nullable type does. Exempting such an atom would let the
projection answer a count for a query that raises
CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN when the rows are read, making the
answer depend on whether the projection was used. Any chain keeps the
safeguard, with no attempt to classify which functions throw:
monotonicChainSupportsNullAtom already resolves the same hazard the same
way for the `IS NULL` atom, and names this `CAST` case in its comment. A
null set index falls through to the switch, so the exclusion fails closed.

Reproduced on a debug build as a deterministic abort on both index
representations: `nullIn` on an ascending, a descending and a
`LowCardinality(Nullable)` key, `globalNullIn`, and `has` over an array
holding a NULL on an ascending, a descending and a
`LowCardinality(Nullable)` key. Every one is silent after the change, and
the counts of the ordinary three-valued `in` and `notIn`, of `notHas`, and
of `has` over an array without a NULL are unchanged. A wrapped key still
raises rather than being answered from the projection, on both index
representations, for a tuple-literal set and for `has`. The regression test
pins `use_lightweight_primary_key_index_analysis` to 0 and to 1 for every
null-set carrier it covers, each against a truth arm that reads the rows, so
neither mirror of mayReadNullKeyValue can regress unobserved; two of its arms
assert through `EXPLAIN projections = 1` that the exact-count projection was
actually used, one per representation, which is what fails without the change
in a release build, where the debug-only consistency check is compiled out.

Co-Authored-By: Claude Opus 5 <[email protected]>
(cherry picked from commit 3c869f046547cc5b15a602e0ddf51890cdc08ecc)
The three FUNCTION_NOT_IN_SET builders the previous commit flags
(`notNullIn`, `notHas`, `globalNotNullIn`) had no arm that reddens when
their flag is removed: every negated arm in the test uses a set that holds
a NULL, and the exemption is not load-bearing there. An all-NULL granule
matches a NULL set element, so the set atom already answers
`{true, false}`, `NOT` flips it, `can_be_true` is false, the granule is
pruned, and the safeguard's `!can_be_false` precondition never holds.

Assert on a set that holds no NULL instead. Over a bare all-NULL key
`nullIn(NULL, {0})` is definitely false, so the negation is definitely true
and every granule is exact; without the exemption nothing is exact,
`exact_count` stays 0 and the projection is declined outright. The arm
reads the projection name out of `EXPLAIN projections = 1` rather than the
`Exact count optimization is applied` description, because a fully exact
read replaces the ReadFromMergeTree node with ReadFromPreparedSource and
that description is only rendered for a partially exact read.

Measured on a debug build: the arm answers 1 on both index
representations with the change, 0 on master, and 0 when only the
`notNullIn` flag statement is removed, which is what ties it to that
builder. 50 randomized repetitions pass, so no setting neuters it.

Co-Authored-By: Claude Opus 5 <[email protected]>
Drop the duplicated reason for the bare-key restriction from the mayReadNullKeyValue doc: the same property is stated at the guard that uses it, a few lines above.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 19, 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; 2 full passes plus 1 delta recheck over
2 fix rounds; 1 gate finding, 0 on the published tree), plus my own cold read of the diff each round.

# Sev Finding Verdict Evidence / action
1 ⚠️ The negated half of the change had no oracle: every NOT IN arm used a set holding a NULL, where the exemption is not load-bearing, so the flag on notNullIn / notHas / globalNotNullIn could be deleted with the suite green (05083_nullable_key_exact_count.sql) AGREE, fixed @ 3bb8b6f Added a bare key under a negated set: over an all-NULL key x NOT IN (0) is definitely true per granule, so every range is exact with the fix and none is without it. The EXPLAIN projections = 1 assertion measures 1 on both index representations with the fix, 0 on master, and 0 when only the notNullIn flag statement is removed, which is what ties it to that builder
2 ⚠️ A flagged set with two or more elements, and any negated set atom, is analysed by the generic exclusion search rather than by matchesExactContinuousRange, so that branch is governed by the same exemption yet untested DISAGREE Measured, not argued: for x NOT IN (1, 2, 3, 4) and for a two-element flagged set the trace lacks the with exact ranges substring that MergeTreeDataSelectExecutor.cpp:2529 prints only for a non-null exact_ranges, so exactness is never computed, mayReadNullKeyValue never runs, and master measures identically to the fix. An arm of that shape could not fail in either direction. The branch IS reached with exact ranges by the arm in row 1, which is where the exemption is observable
3 💡 The exemption is tested only where it prevents the abort, not where a monotonic wrapper must keep the safeguard DISAGREE The two wrapped-key groups do discriminate the chain guard: a same-type CAST is monotonic for any bounds, so it lands in indexes_mapping[].functions, applyMonotonicFunctionsChainToRange leaves an infinite bound untransformed, and the set index then reports an exact {false, true} that NOT flips to {true, false}. Deleting && !element.set_index->hasMonotonicFunctionsChain() makes those arms answer 3 instead of raising CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN
4 💡 The new early return in atomIsNullForNullArgument precedes the exhaustive switch, so its coupling to FUNCTION_IN_SET / FUNCTION_NOT_IN_SET is implicit AGREE Noted, not changed. All six builders that set the flag also set one of those two functions, and the && element.set_index conjunct makes a null set index fall through to the switch, so it fails closed
5 💡 Breadth left uncommitted: no LowCardinality(Nullable), globalNullIn, globalNotNullIn or notHas arm, and the new negated-set block pins its count on one index representation while asserting the plan on both AGREE Noted, not changed. The named forms collapse onto the two RPN shapes the file already pins on both representations, so an arm each would be volume; the unpinned count is bounded by the exact-count sum being representation-independent and by the positive arms pinning it on both

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by a fix round are auto-dropped.

Session id: cron:clickhouse-review-slot-10:20260919-203700

@clickhouse-gh clickhouse-gh Bot closed this Sep 19, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e1c22c8]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) FAIL
05210_lightweight_update_materialized_cte_in_ignore FAIL cidb
01513_optimize_aggregation_in_order_memory_long NOT_FAILED cidb

AI Review

Summary

This PR fixes the exact-count projection analysis for null-aware set-membership predicates on Nullable MergeTree keys by distinguishing ordinary in/notIn atoms from nullIn/notNullIn/has/notHas and their global forms inside KeyCondition. After reading the current diff, the touched code paths, the regression test expansion, and all prior thread replies, I do not see any remaining correctness, safety, or test-coverage issues that still warrant changes.

Final Verdict
  • Status: ✅ Approve

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 4db7eb9

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

Check / test Reason Owner / fixing PR
Performance Comparison (arm_release, master_head, 5/6) / set_index #1 dashboard confirmed_regression, client_time 0.0484 -> 0.0737 (+52.2%); the shard's own report says 4 too long, 1 slower, 1 unstable. The benchmark reddens independently of the diff under test: over the last 7 days set_index #1 is classed slower on 91 distinct pull requests and 102 distinct heads, among them #118708, which changes only ci/jobs/build_profile_diff_job.py and ci/jobs/scripts/log_cluster.py and therefore has no query-performance surface at all. Both failing shard jobs also carry the harness labels under-utilized CPU and disk-almost-full #121090 (mine, open)
Performance Comparison (arm_release, master_head, 1/6) / order_by_read_in_order #1 dashboard confirmed_regression, client_time 0.0172 -> 0.0215 (+25.2%); report says 4 too long, 1 faster, 1 slower. Same pattern: classed slower on 236 distinct pull requests and 320 distinct heads over the last 7 days #121090 (mine, open)
Performance Comparison (arm_release, master_head, 4/6) / space_filling_curve #1 dashboard confirmed_regression, client_time 0.8052 -> 0.9323 (+15.7%), while this shard's own report reports no slower at all (6 too long, 1 unstable), which is the exact shape the dashboard-verdict gate merged on 2026-09-19 (#120927) introduced #121090 (mine, open)
Build profile diff job-level RuntimeError: CI logs cluster query failed traceback out of ci/jobs/build_profile_diff_job.py, so a non-ok CI logs cluster response aborts the job instead of degrading to "no baseline". The job only reads build_time_trace on the logs cluster and neither builds nor runs the server, so it is not reachable from this diff. Measured over the last 24 hours: 389 rows across 348 distinct pull requests #118708 (mine, open)
Finish Workflow, Mergeable Check, PR praktika rollups of the rows above, no independent failure #121090 (mine, open) and #118708 (mine, open)

Session id: cron:our-pr-ci-monitor:20260920-110135

`globalNullIn` and `globalNotNullIn` are separate `atom_map` entries from
`nullIn` and `notNullIn`, so the exemption is written by four builders and the
existing arms could not see a regression in the global pair: with
`null_is_ordinary_value` dropped from the `globalNullIn` builder the file still
passed 3/3, and the same held for `globalNotNullIn`.

One arm per spelling, over the two fixtures the file already creates, in the
shapes that were measured to flip. With the `globalNullIn` builder mutated the
positive arm raises `Inconsistent KeyCondition behavior` from
`markRangesFromPKRange`; with the `globalNotNullIn` builder mutated the negated
arm's plan assertion goes 1 to 0 and no other line of the file changes. 20/20
green on the unmutated tree under randomized settings.
`null_is_ordinary_value` is written by six atom_map builders. The file's only
`NOT has` arm applies `CAST(x, 'UInt64')` to the key, and
`atomIsNullForNullArgument` skips the exemption once the set index carries a
monotonic functions chain, so that arm answers the same way with and without
the `notHas` flag statement: deleting that one statement left the file green
3/3.

The new arm keeps the key bare and takes a constant array holding no NULL, so
`NOT has` is definitely true for every NULL key value, every selected range
stays exact and the implicit exact-count projection answers the count.
Deleting `null_is_ordinary_value` from the `notHas` builder alone now flips
exactly one line of the reference, 1 to 0, and no other line; unmutated, the
file is 20/20 OK under randomized settings.

`HasToInPass` does not rewrite this shape: it bails on a Nullable array
element type and on a Nullable needle, so the atom reaches `KeyCondition` as
`notHas` and is folded there through `inverse_relations`.
@clickhouse-gh

clickhouse-gh Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit e1c22c817f7cd00b19f528087b3b43f2de7ffcf9 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

@clickhouse-gh

clickhouse-gh Bot commented Oct 1, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

⚠️ AI verdict: not_sure — 4 query(s) regressed out of 36 analysed

These ClickBench slowdowns are very unlikely to come from this PR, which changes no aggregation code. The PR only changes how KeyCondition decides whether nullIn, has() and related set atoms on a bare Nullable key keep the exact-count projection exact, and ClickBench has no Nullable key columns. Thirteen GROUP BY-heavy ClickBench queries are about 13% to 53% slower with higher CPU time, three of the six source runs shared one host, and no TPC-H query moved. Nine flagged queries are downgraded to not sure; Q16, Q17, Q18 and Q32 (+44.8%, +27.5%, +45.5%, +53.1%) keep their regression verdicts because the deltas are too large to override, but a rerun on separate hosts should be done before acting on them.

clickbench

🔴 4 regressed · ⚠️ 10 inconclusive

Flagged queries (14 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🔴 16 regression 546 790 +44.8% <0.0001 aggregation: The +44.8% is too large to override, but the diff does not touch this GROUP BY path and the query's history is noisy. Rerun on separate hosts before acting on it.
🔴 17 regression 244 311 +27.5% <0.0001 aggregation: The +27.5% is too large to override, but this aggregation does not run the changed exact-count NULL logic. Rerun on separate hosts to confirm.
🔴 18 regression 892 1298 +45.5% <0.0001 aggregation: The +45.5% is too large to override, but the measurements were noisy and the diff does not touch high-cardinality GROUP BY execution. Rerun before attributing it to this PR.
🔴 32 regression 716 1096 +53.1% <0.0001 aggregation: The +53.1% is too large to override, but this wide GROUP BY never reaches the changed KeyCondition code. Rerun on separate hosts before treating it as real.
⚠️ 8 not_sure 341 385 +12.9% <0.0001 aggregation: The diff only changes NULL-key exactness checks for the exact-count projection, which this GROUP BY scan over non-Nullable columns never runs. The +12.9% matches the slowdown on other heavy aggregations.
⚠️ 10 not_sure 165 192 +16.4% <0.0001 aggregation: This aggregation does not reach the changed set-membership NULL handling in KeyCondition. The +16.4% fits the shared source-host slowdown, not a code effect.
⚠️ 12 not_sure 254 290 +14.2% <0.0001 aggregation: There is no nullIn or has() atom on a Nullable key here, so the changed code cannot affect this query. The +14.2% tracks the slowdown seen across all heavy GROUP BY queries.
⚠️ 13 not_sure 353 422 +19.4% <0.0001 aggregation: The PR touches only exact-count projection eligibility, which this GROUP BY query does not use. The +19.4% fits the host-wide slowdown.
⚠️ 14 not_sure 327 369 +12.8% <0.0001 aggregation: The changed KeyCondition branch only runs for Nullable primary-key atoms, which ClickBench does not have. The +12.8% is consistent with source-side host variance.
⚠️ 15 not_sure 160 191 +19.4% <0.0001 aggregation: This aggregation never evaluates the changed NULL-exactness check. The +19.4% matches the shared slowdown on the source runs.
⚠️ 28 not_sure 1060 1192 +12.4% <0.0001 aggregation: This one is borderline and noisy on both sides. The PR's KeyCondition change does not apply to this query.
⚠️ 31 not_sure 274 308 +12.6% <0.0001 aggregation: The source median sits inside master's normal range, and the query does not use the changed set-membership NULL handling.
⚠️ 33 not_sure 1138 1343 +18.0% <0.0001 aggregation: The source median of 1343 ms is inside master's normal range, and the diff does not touch this aggregation path.
⚠️ 34 not_sure 1147 1313 +14.5% <0.0001 aggregation: The source median of 1313 ms is inside master's normal range, and the diff does not touch this aggregation path.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 47ff7373-af16-46ae-93ff-b71a38bdc9d1
  • MIRAI run: fde555a0-eeaf-4e74-848a-a14f8bb5666b
  • PR check IDs:
    • clickbench_2638419_1790826334
    • clickbench_2638425_1790826335
    • clickbench_2638436_1790826335
    • tpch_adapted_1_official_2638462_1790826335
    • tpch_adapted_1_official_2638476_1790826335
    • tpch_adapted_1_official_2638490_1790826335

…on-null-set-exactness

# Conflicts:
#	src/Storages/MergeTree/KeyCondition.cpp
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - e1c22c8

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
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 05210_lightweight_update_materialized_cte_in_ignore not from this PR (it only changes KeyCondition and adds a stateless test): UNKNOWN_TABLE for the reused MATERIALIZED CTE _materialized_cte_c_* on a parallel replica; 144 of 144 reruns with the same settings passed #123121 (mine, open)
Mergeable Check, PR praktika rollups of the row above #123121 (mine, open)
Sync - CH Inc sync (private, not actionable by me)

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261013-030009

@azat

azat commented Oct 13, 2026

Copy link
Copy Markdown
Member

@nihalzp maybe you can take a look?

@clickhouse-gh

clickhouse-gh Bot commented Nov 13, 2026

Copy link
Copy Markdown
Contributor

Dear @nihalzp, 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.

@nihalzp nihalzp self-assigned this Nov 13, 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 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-request PR origin: a maintainer pinged or directed groeneai pr-ci

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants