Repository navigation
Fix wrong count and wrong DELETE when a NULL expression sits under NOT - #115152
Conversation
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]>
Internal second-model reviewAn independent model reviewed this change against the ClickHouse review skill. Two substantive
❌ 💡 Nits closed without action: |
|
Workflow [PR], commit [16d21de] Summary: ✅
AI ReviewSummaryThis PR fixes a real correctness bug in Missing context / blind spots
Final Verdict✅ No new blocking findings. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 7/7 (100.00%) · Uncovered code |
Pre-PR validation gate| # | Gate | Result | |
|
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. |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
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 units7 translation units recompiled, 20 s compile time in total, 7 of them have a recent master baseline. |
…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.
`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
Closes: #112242
Requested by @ nihalzp in #112242 (comment) (reported by @ zlareb1).
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed wrong results when a
WHEREclause contained aNULLexpression under aNOT, for exampleSELECT 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, andALTER TABLE ... DELETEwith that condition removed rows it should have kept.Description
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 isNULLforid38 and 39, so those two had to survive.Root cause.
cloneDAGWithInversionPushDownpushesNOTto the leaves. ForNOT (id >= 20 AND NULL), De Morgan turns theandinto anorand pushes the inversion into both children; the all-NULL leaf is not recognized, so the tail wraps it in a literalnot(), whichRPNBuildercomplements classically into "provably true for every row". Both steps hold only in two-valued logic:NOT NULLisNULL, whichWHEREmust reject.The change. Before the node dispatch, an all-NULL node absorbs the inversion instead of receiving a
not()wrapper, the same idiom the neighbouringmaterializeand trivial-cast branches use. It still folds to "never true" downstream, correct becauseNULLis notTRUE, and a non-negatedx AND NULLkeeps its exact fast path.Absorbing the inversion substitutes the operand's type for the
not()result type, so the guard is confined toboolean_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 typedNullable(Int64), whileif(id % 2, NULL, NULL)has no constant column.Validation
Debug build of the base commit vs the same build with the change.
count() WHERE NOT (id >= 20 AND NULL)toInt64OrNull('x')CAST(NULL, 'Nullable(UInt8)')if(id % 2, NULL, NULL)materialize(NULL)numbers(100) WHERE NOT (number = 5 AND NULL) LIMIT 10ALTER DELETE WHERE NOT (id >= 38 AND NULL), survivors[][38,39][38,39]count() WHERE id >= 20 AND NULLnumbers() WHERE number > 0 AND NULL LIMIT 10ifNull(NOT materialize(CAST(NULL, 'Nullable(Int64)')), 0), rowsNullable(Float64), rowsThe 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
toInt64OrNullandCAST, the type test coversif(id % 2, NULL, NULL), theboolean_contexttest covers the two value-position arms. The unboundednumbers()lines pin the positive direction, which an earlier attempt at this fix turned into a hang.The projection,
KeyConditionand 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 orKeyCondition.Workflow [PR]
Sync PR [sync-upstream/pr/115152]