Skip to content

Fix wrong count and wrong DELETE when a NULL expression sits under NOT - #115152

Merged
nihalzp merged 4 commits into
ClickHouse:masterfrom
groeneai:groeneai/key-condition-null-under-not
Aug 20, 2026
Merged

nihalzp merged 4 commits into
ClickHouse:masterfrom
groeneai:groeneai/key-condition-null-under-not

Conversation

@groeneai

@groeneai groeneai commented Aug 17, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #112242

Requested by @ nihalzp in #112242 (comment) (reported by @ zlareb1).

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 wrong results when a WHERE clause contained a NULL expression under a NOT, for example SELECT count() FROM t WHERE NOT (id >= 20 AND NULL). Index analysis treated such a condition as provably true for the whole range, so the filter was skipped: count() returned rows the query rejects, and ALTER TABLE ... DELETE with that condition removed rows it should have kept.

Description

CREATE TABLE t (id UInt32) ENGINE = MergeTree ORDER BY id;
INSERT INTO t SELECT number FROM numbers(40);
SELECT count() FROM t WHERE NOT (id >= 20 AND NULL);   -- returned 40, correct is 20

Reading the rows returned 20, so count() and the row set disagreed on one predicate. A mutation was worse: ALTER TABLE t DELETE WHERE NOT (id >= 38 AND NULL) deleted all 40 rows, although the predicate is NULL for id 38 and 39, so those two had to survive.

Root cause. cloneDAGWithInversionPushDown pushes NOT to the leaves. For NOT (id >= 20 AND NULL), De Morgan turns the and into an or and pushes the inversion into both children; the all-NULL leaf is not recognized, so the tail wraps it in a literal not(), which RPNBuilder complements classically into "provably true for every row". Both steps hold only in two-valued logic: NOT NULL is NULL, which WHERE must reject.

The change. Before the node dispatch, an all-NULL node absorbs the inversion instead of receiving a not() wrapper, the same idiom the neighbouring materialize and trivial-cast branches use. It still folds to "never true" downstream, correct because NULL is not TRUE, and a non-negated x AND NULL keeps its exact fast path.

Absorbing the inversion substitutes the operand's type for the not() result type, so the guard is confined to boolean_context, the existing flag for positions where the caller discards the value. In a value position a negation would otherwise change type and drop valid rows. The all-NULL test needs both a column and a type check: toInt64OrNull('x') is typed Nullable(Int64), while if(id % 2, NULL, NULL) has no constant column.

Validation

Debug build of the base commit vs the same build with the change.

probe base with change correct
count() WHERE NOT (id >= 20 AND NULL) 40 20 20
same with toInt64OrNull('x') 40 20 20
same with CAST(NULL, 'Nullable(UInt8)') 40 20 20
same with if(id % 2, NULL, NULL) 40 20 20
same with materialize(NULL) 40 20 20
numbers(100) WHERE NOT (number = 5 AND NULL) LIMIT 10 9 10 10
minmax skip index, same predicate 40 20 20
ALTER DELETE WHERE NOT (id >= 38 AND NULL), survivors [] [38,39] [38,39]
count() WHERE id >= 20 AND NULL 0 0 0
numbers() WHERE number > 0 AND NULL LIMIT 10 0 fast 0 fast 0 fast
value position, ifNull(NOT materialize(CAST(NULL, 'Nullable(Int64)')), 0), rows 40 40 40
same with Nullable(Float64), rows 40 40 40

The new test fails on the base build, passes with the change, and passed 50/50 randomized runs. Deleting any one of the three parts of the guard makes it fail again on exactly the arms that part covers: the column test covers toInt64OrNull and CAST, the type test covers if(id % 2, NULL, NULL), the boolean_context test covers the two value-position arms. The unbounded numbers() lines pin the positive direction, which an earlier attempt at this fix turned into a hang.

The projection, KeyCondition and minmax test families were run on both builds: the same 23 tests fail either way, all on ZooKeeper and distributed connections unavailable in this sandbox, none mentioning the exact-count projection or KeyCondition.


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

groeneai and others added 3 commits August 17, 2026 09:06
cloneDAGWithInversionPushDown rewrites a filter so NOT is pushed to the
leaves. For NOT (id >= 20 AND NULL), De Morgan turns the and into an or and
pushes the inversion into both children; the all-NULL leaf is not recognized,
so the tail of the function wraps it in a literal not(). RPNBuilder then
consumes that not as a logical operator and complements the inner ALWAYS_FALSE
classically, which claims the range is provably true for every row.

De Morgan and that complement are only valid in two-valued logic. NOT NULL is
NULL, which WHERE must reject, so the rewritten predicate is not equivalent to
the original and every consumer that trusts can_be_false = false skips the
filter.

Absorb the inversion at such a node instead, the same idiom the neighbouring
materialize and trivial-cast branches use. The node still folds to "never
true" downstream, which is correct because NULL is not TRUE. The guard sits
inside need_inversion, so a non-negated x AND NULL keeps its exact fast path;
relaxing that path instead was tried and turned an instantly empty
numbers() ... LIMIT 10 query into an unbounded read.

The predicate needs both a column and a type test: toInt64OrNull('x') is
typed Nullable(Int64) so the type test misses it, and if(id % 2, NULL, NULL)
carries no constant column so the column test misses it. Dropping either half
makes the new test fail on exactly the case that half covers.

Measured on a debug build, base versus fixed: count() over the reported
predicate 40 -> 20, numbers LIMIT pushdown 9 -> 10, minmax skip index
40 -> 20, and ALTER TABLE ... DELETE WHERE NOT (id >= 38 AND NULL) stopped
deleting the two rows the predicate is NULL for ([] -> [38,39]).

Closes: ClickHouse#112242
The previous commit absorbed the inversion at any all-NULL node. That
substitutes the operand's type for the Nullable(UInt8) that not() would have
produced, which is invisible where only truthiness is consumed but not where
the negation supplies a value: the else-branch of the function re-resolves a
parent whose argument types changed, so

  WHERE length(reinterpretAsFixedString(
      ifNull(NOT materialize(CAST(NULL, 'Nullable(Int64)')), 0))) = 1

turned from true into false for every row. Measured on a 40-row table, the
row set went 40 -> 0 while the predicate itself still evaluates to 1 on both
builds, and primary key analysis pruned every granule. That is a wrong result
in the opposite direction, dropping valid rows rather than over-counting them.

Restrict the absorption to boolean_context, which the header documents as
"pass true only when the caller uses predicate_ as a filter: it tests each
row for truthiness and discards the value". tryRewriteCoalesceCondition
already gates the same class of truthiness-preserving, value-changing rewrite
on that flag. Every consumer of the original defect reaches the leaf with the
flag set, so all five carriers, the numbers LIMIT pushdown, the minmax skip
index and the ALTER DELETE case stay fixed; only the value positions change
back.

Dropping any one of the three parts of the condition reddens exactly the arms
that part covers: the column test covers toInt64OrNull and CAST, the type
test covers if(id % 2, NULL, NULL), and boolean_context covers the two value
positions. A negation of Nullable(Int8) or Nullable(Nothing) is unaffected
either way, since neither changes the result width.

The test also gains no-parallel-replicas and no-replicated-database. It greps
EXPLAIN for the exact-count projection, which is suppressed when reading from
remote replicas, so without the tags the positive assertion can fail and the
negative one can pass vacuously.
The projection assertions in 04909_key_condition_null_under_not depend on
whether a granule lies wholly inside the range the condition is definitely
true for, and the table did not fix index_granularity, so the test runner
randomized it into the CREATE statement.

Exactness is not decided by KeyCondition::matchesExactContinuousRange alone.
When that returns false, MergeTreeDataSelectExecutor falls back to
genericExclusionSearch, which marks a range exact per granule whenever the
granule's mask cannot be false. The fixed predicate is definitely true on any
granule inside ids [0,19], so at a granularity of 19 or less those granules
are exact, the exact count projection legitimately engages, and the assertion
that it is absent returns 1 instead of 0. Measured: the flip is exactly at 19,
and the count stays correct at every granularity, so this was a test flake
rather than a residual defect. Its rate would have been about 1 in 3449 on
release builds and 0 on debug builds, where the randomizer floor is 100 -
which is why the debug 50/50 run could not have caught it.

Pin index_granularity on the table rather than adding
no-random-merge-tree-settings, so every other randomized merge tree setting
stays live. Also add an assertion that primary key analysis still produces a
bounded condition on the key, so the absent-projection assertion cannot pass
merely because the condition degraded to a full scan. That assertion prints 0
on the base build, where key analysis prunes every granule, so it detects the
bug directly rather than only guarding against vacuity.

Co-Authored-By: Claude Fable 5 <[email protected]>
@groeneai

groeneai commented Aug 17, 2026 •

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

An independent model reviewed this change against the ClickHouse review skill. Two substantive
findings; a final re-review after both were resolved returned nothing.

⚠️ Exact-count assertion was index_granularity-dependent: AGREED, fixed. The test asserted
that _exact_count_projection is absent for the repaired predicate, but the table did not pin
index_granularity, which the runner randomizes over [1, 65536]. Exactness is not decided only by
matchesExactContinuousRange(): when that declines, genericExclusionSearch still marks a granule
exact if every row in it matches, so at granularity <= 19 the repaired predicate legitimately uses
the projection and the assertion flips. The count stays correct at every granularity, so this was a
test flake rather than a residual defect. The table now pins index_granularity, matching the two
sibling exact-count tests, plus a mechanism assertion so the negative arm cannot pass merely because
the condition degraded to a full scan. The debug and sanitizer randomizer floor is 100, which is why
randomized reruns had not surfaced it.

❌ indexHint bypasses the fix: DISAGREED. The claim needs indexHint(cond) to filter rows,
so that 40 instead of 20 would be wrong. It does not filter: executeImpl returns a constant 1
per row and never evaluates its arguments, so the argument selects index ranges only. The documented
behaviour is that indexHint returns more data than the equivalent condition, and
01739_index_hint asserts exactly that over-inclusion. A stale hidden DAG can only widen the
granule set, costing pruning precision rather than correctness, and it predates this change.

💡 Nits closed without action: optimize_trivial_count_query is randomized but does not gate this
path; the test number was re-verified unused on current master.

@clickhouse-gh

clickhouse-gh Bot commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [16d21de]

Summary: ✅


AI Review

Summary

This PR fixes a real correctness bug in KeyCondition normalization: when NOT was pushed onto an all-NULL leaf, index analysis could treat the negated branch as provably true and skip filtering, which in turn broke exact-count queries and ALTER TABLE ... DELETE predicates. The added guard is scoped to boolean-only contexts, which preserves the value-typed NOT cases the PR description calls out, and the new stateless test exercises the main affected carriers (NULL, typed NULL, materialize, a non-constant all-NULL branch, exact-count projection, and mutation filtering). I did not find a remaining correctness issue in the current head revision.

Missing context / blind spots
  • ⚠️ I did not run the new test locally because this checkout does not have a prepared build directory, so the review is based on the current code, diff, and prior PR discussion rather than local execution.
Final Verdict

✅ No new blocking findings.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.90% 86.90% +0.00%
Functions 91.90% 92.00% +0.10%
Branches 79.30% 79.30% +0.00%

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

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate

| # | Gate | Result |
| a | Deterministic repro | Yes. SELECT count() FROM t WHERE NOT (id >= 20 AND NULL) on a 40-row MergeTree returns 40 on the base build every run; correct is 20. No randomization or timing needed. |
| b | Root cause explained | Yes. cloneDAGWithInversionPushDown pushes NOT to the leaves by De Morgan; an all-NULL leaf is not recognized, so the tail wraps it in a literal not(), which RPNBuilder complements classically into "provably true". NOT NULL is NULL, so the rewritten predicate is not equivalent to the original. |
| c | Fix matches root cause | Yes. The inversion is absorbed at the leaf where it would otherwise be applied unsoundly. No consumer is patched, no exactness flag is widened, no setting is added. |
| d | Test intent preserved / test added | Yes. New 04909_key_condition_null_under_not; no existing test was changed or weakened, and no existing reference line changed. |
| e | Demonstrated both directions | Yes. The test fails on the base build (16 differing lines) and passes with the change; 50/50 randomized runs pass. Three independent mutations of the guard condition each redden exactly the arms they drop, and nothing else. |
| f | General across code paths | Yes. All KeyCondition construction sites go through ActionsDAGWithInversionPushDown, so one site covers every consumer. Verified: exact-count projection (40 to 20), numbers LIMIT pushdown (9 to 10), minmax skip index (40 to 20), ALTER DELETE ([] to [38,39]). Partition pruner, set skip index and primes already agreed with their row sets and still do. |
| g | Generalizes across inputs | Yes. All three parts of the guard are required and each was proven load-bearing by mutation. Checked on UInt32, String, Date, Nullable, LowCardinality and Array key columns; nullIf, toUInt32OrNull, CAST(NULL,'Nullable(Nothing)'), nested AND, an OR branch and NULL-first argument order. Value positions checked separately across Nullable(Int8/Int16/Int64/Float64/Nothing), where only a width change from the not() result type is observable. All count-versus-row-set oracle pairs agree. |
| h | Backward compatible | Yes. No setting, no serialization or format change, so no SettingsChangesHistory entry. Results change only for queries that were returning wrong answers. |
| i | Invariants and contracts preserved | Yes. handled_inversion means the inversion is fully absorbed, which holds here and matches the existing materialize and trivial-cast uses. The only re-application site is bypassed by the early return, and the outer entry point passes need_inversion = false. The rewrite is additionally confined to boolean_context, the existing flag marking a position where the caller tests truthiness and discards the value, so the node's type is never substituted where the value is consumed. |

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @alesapin @shankar-iyer, could you review this? Key analysis pushed a NOT to the leaves by De Morgan without recognizing an all-NULL leaf, so the negated condition became provably true for the whole range and the filter was skipped: count() over-counted, the minmax skip index over-counted, and ALTER DELETE removed rows whose predicate was NULL. The fix absorbs the inversion at an all-NULL node, confined to boolean_context so a value-position negation keeps its type.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 17, 2026
@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 19, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 16d21ded2 with master 8a4969205 (stripped binary size, per-symbol sizes and ThinLTO time; 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 702.08 MiB 699.05 MiB -3.03 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

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

Job report

@nihalzp
nihalzp added this pull request to the merge queue Aug 20, 2026
Merged via the queue into ClickHouse:master with commit e6b4a3f Aug 20, 2026
175 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 20, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Aug 22, 2026
…oss-type-set-exactness-nonnullable

The sole conflict is the accurateCastOrNull target guard in
tryPrepareSetColumnsForIndex. Master's side is taken and this branch's local
setIndexKeyTypeSupportsAccurateCastOrNull is deleted.

Master reached the same fix through ClickHouse#115152 and ClickHouse#114233, which export
canBeAccurateCastOrNullTarget from CastOverloadResolver.h and call it at three
guards. That is what the local helper's own commit message asked for: the
throwing validator and the predicate now share one implementation instead of
mirroring each other by hand, so they cannot drift.

The two forms are not equivalent and master's is narrower. For a Nullable key
type the local helper recursed into the nested type and could proceed, while
master keeps the outer canBeInsideNullable test, which DataTypeNullable does not
override and therefore answers false. Master declines there, exactly as the
pre-fix guard did, so taking master's side removes a widening this branch had
introduced rather than losing coverage.

The five predicates carrying this PR's contract are untouched and still absent
from master.
pull Bot pushed a commit to erickirt/ClickHouse that referenced this pull request Sep 6, 2026
`cloneDAGWithInversionPushDown` pushes an inversion through every `not`, which makes two of
them cancel out. That is only truthiness-preserving: `not(not(x))` is `x != 0`, a `UInt8` in
`{0, 1}`, not `x` itself. Where the value is merely truth-tested that is exactly what index
analysis wants, but in a value position the substitution changes what the enclosing function
is applied to.

So `(NOT NOT c0) > -0.5`, which is true for every row, reached index analysis as
`c0 > -0.5`, and pruning dropped every part, granule and partition whose values are
negative:

    CREATE TABLE t (c0 Int64) ENGINE = MergeTree ORDER BY c0;
    INSERT INTO t SELECT number - 1000 FROM numbers(1000);
    INSERT INTO t VALUES (0);

    SELECT count() FROM t WHERE (NOT (NOT c0)) > -0.5;  -- 1, must be 1001
    SELECT sum((NOT (NOT c0)) > -0.5) FROM t;           -- 1001

The same shape reached primary-key pruning, partition pruning and statistics-based part
pruning; it reproduces on 26.7. Keep `not` as an ordinary function in a value position, where
the atom stays opaque to index analysis. A truth-tested `NOT` is still pushed down as before.

This is the sibling of the all-NULL case fixed in ClickHouse#115152: an inversion may only be absorbed
by a node whose negation equals its two-valued complement, and only where the value is
discarded.

Found by SQLancer: every wrong-result oracle in the 2026-08-25 nightly run - `KeyCondition`,
`ViewEquivalence`, `SubqueryMaterialize`, `PartitionMirror`, `CountOptimization`,
`TLPGroupBy`, `TLPDistinct`, `TLPAggregate` - hit this one predicate shape.

Related: ClickHouse#115152
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 groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Exact-count optimization + KeyCondition folding constant NULL as false: SELECT count() ... WHERE NOT (key >= c AND NULL) counts rows the WHERE rejects

4 participants