Repository navigation
Do not cancel a pair of not in a value position during index analysis - #116381
Conversation
`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 #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: #115152
A declared skip index builds its own `KeyCondition` from the same inverted DAG, so it over-pruned the same way. With one row per granule the index prunes down to individual rows, which makes the finding visible in a five-row table.
|
Workflow [PR], commit [c43d84c] Summary: ✅
AI ReviewSummaryThis PR makes Findings
Final VerdictChanges requested. The core fix looks sound, but the new regression test still leaves two claimed pruning entrypoints effectively unproven. LLVM Coverage ReportMeasured on commit c43d84c.
Changed lines: Changed C/C++ lines covered: 5/5 (100.00%) · Uncovered code |
…sition-key-condition
…sh-through Gating every `not` on `boolean_context` also disabled the value-preserving case: a `not` that merely sends an inversion into its child, which absorbs it into an equivalent two-valued complement (`not(notHas(...))` becomes `has(...)`, De Morgan on `and`/`or`) or gets an explicit `not()` wrapper. The text index canonicalizes candidate nodes with `boolean_context = false`, so `WHERE NOT notHas(arr, 'w3')` stopped matching the index, caught by `04903_not_has_secondary_index` in the Fast test: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=116381&sha=209c05a2f300e2436ff5d2ed37d0a830b62bba68&name_0=PR&name_1=Fast%20test Only the cancellation is unsound in a value position: a `not` that receives an inversion (`need_inversion == true`) absorbs it by returning its bare argument, substituting `x` for `not(not(x))`. Keep exactly that case opaque outside a truth-tested context. Co-Authored-By: Claude Fable 5 <[email protected]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units7 translation units recompiled, 20 s compile time in total, 7 of them have a recent master baseline. |
…sition-key-condition
|
🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=116381&sha=6a2f3f01d8cd97559b26bac0cfea5638d9bb1b2b&name_0=PR&name_1=Upgrade%20check%20%28amd_release%29 — |
|
Not this PR, and it is already fixed. The abort is on the previous release binary, not on this PR's build. That query is line 37 of Fix: #114826, merged to The existing issue is #116394 (open, assigned to @ alesapin). It is titled after the literal part name rather than the STID, which is probably why it did not turn up. This will keep firing until the tag |
…sition-key-condition
|
|
||
| SELECT 'statistics'; | ||
| -- All five rows match: the comparisons are constant over the {0, 1} range of `NOT NOT c0`. | ||
| SELECT count() FROM t_not_stats WHERE (NOT (NOT c0)) > -0.5; |
There was a problem hiding this comment.
The statistics block still passes if statistics pruning never runs at all: t_not_stats has no primary key or skip index, so a full scan returns the same row counts. Since the PR description explicitly says this bug reproduced in statistics-based part pruning, please pin that entrypoint too, e.g. use_statistics = 0, use_statistics_for_part_pruning = 1, and an EXPLAIN indexes = 1 assertion that the Statistics section is present for this query shape.
| CREATE TABLE t_not_idx (c0 Int64, INDEX idx_c0 c0 TYPE minmax GRANULARITY 1) ENGINE = MergeTree | ||
| ORDER BY tuple() SETTINGS index_granularity = 1; | ||
| INSERT INTO t_not_idx VALUES (-2), (-1), (0), (1), (2); | ||
| SELECT count() FROM t_not_idx WHERE (NOT (NOT c0)) > -0.5; |
There was a problem hiding this comment.
The minmax subsection has the same coverage gap: these SELECT count() checks stay green both when idx_c0 is used safely and when it is not used at all. If this test is meant to cover the skip-index entrypoint called out in the commit message, please force the index with force_data_skipping_indices = 'idx_c0' or assert its presence in EXPLAIN indexes = 1, so a future change that stops building the index condition does not silently pass here.
Master landed its own `has`-path set-index exactness rule (ClickHouse#115294, ClickHouse#116381): `areTypesCompatibleForHasSetIndex` + `areSetAndKeyTypesCompatibleForHas`, called from `tryPrepareSetIndexForHas`, plus the `Variant`/`Dynamic` in-use-alternatives recovery `narrowVariantToOccupiedAlternatives`. That supersedes this branch's `has` half, which reached the same property through a `composite_field_identity_is_enough` flag inside `tryPrepareSetColumnsForIndex`. Keeping both would be their conjunction, so it would silently narrow decisions taken under review: master admits an `Enum8` element against an `Int8` key and prunes it exactly (its comment cites `00674_has_array_enum`), which this branch's rule declines. Taking "ours" in the conflicted region would delete `narrowVariantToOccupiedAlternatives` outright. So `src/` is reset to master's content verbatim here, together with the six existing test files this branch had re-recorded for the `has` rule. The `IN` half, which master has not fixed and which still drops rows, is re-applied on top in a later commit.
Index analysis builds an exact set atom out of constants it converted into the
key column's type, while runtime `IN` membership converts the key into the set
element's type. When those two conversions are not mutual, the atom names key
values the predicate does not match and misses ones it does, so single-point key
range pruning (partition pruning and minmax) drops the part holding a matching
row and the row silently disappears.
`tryPrepareSetColumnsForIndex` casts each element with `castColumnAccurateOrNull`
and drops only the elements whose cast produced NULL; whatever survives is
treated as exact. A conversion that succeeds without preserving equality was
never considered. Measured on master, against an `ENGINE = Memory` table holding
the same rows:
UInt64 key, k NOT IN (SELECT '01') -> [2] vs [1,2]
String key, s IN (SELECT 1) rows '01','1' -> ['1'] vs ['01','1']
String key, PARTITION BY length(s), s IN (SELECT 1) -> ['1'] vs ['01','1']
UInt8 key, k IN (SELECT CAST(5, 'Bool')) -> [1] vs [1,5]
String key, k NOT IN (a Variant(String, UInt8)) -> ['4'] vs ['3','4']
(String, UInt64) key, (a, b) IN (SELECT (1, 1)) -> [('1',1)] vs both rows
Marking the atom relaxed does not fix this: `relaxed` only forbids trusting
`can_be_false`, and four of the six cases prune through `can_be_true` instead -
the `PARTITION BY length(s)` case is an atom master already marks relaxed. So the
atom is declined outright, and the check is deliberately not gated on
`!out.relaxed` the way the `has` sibling is.
The rule mirrors the one master merged for `has` in ClickHouse#115294 and ClickHouse#116381: a
type-level gate at the caller, before the columns are prepared. It admits two
shapes, both sides first normalized with
`removeNullable(recursiveRemoveLowCardinality(...))`: `equals`-equal types that
also agree on custom names, and two plain integers. `equals` alone is not enough
because `Bool` is `equals`-equal to `UInt8` yet clamps every nonzero value to 1;
`getName()` equality is too strict in the other direction, since it would decline
a `DateTime('UTC')` element against a `DateTime('Europe/Moscow')` key, a pair that
prunes correctly today because a time zone is display metadata no `Field` carries.
It is narrower than `areTypesCompatibleForHasSetIndex` on purpose: that one also
admits `Enum`/native-integer, `Nothing` and container pairs, which are sound for a
raw `Field` comparison but not once `IN` casts the key into the set type, where a
narrowing conversion throws rather than nulling.
Rejected alternatives: gating on polarity (a pair can be unsound in either
direction, so it would need a directional injectivity analysis per type pair);
reusing the `has` predicate verbatim (strictly less safe here); a value-level
round-trip probe (catches the first case, but not the ones where the element
round-trips and a different key value collides with it).
The type-unpacking loop is extracted into `unpackSetTypesToKeyArity` and shared
with the `has` path; returning false where the arity is unreachable preserves that
caller's behaviour exactly.
`AST fuzzer (amd_release, oracle)` on ClickHouse#118321 reported an `Identity WHERE (NOT(NOT p))` mismatch seeded from `02346_text_index_partially_materialized.sql`: `hasPhrase(text, 'ello50 wor')` counted 30 rows while `NOT (NOT hasPhrase(text, 'ello50 wor'))` counted 0. `hasPhrase` with two arguments tokenizes with `splitByNonAlpha`, under which `'ello50 wor'` is not a phrase of `'hello50 world50'`; the index tokenizer reaches the row-level function only as a third argument injected by `processTextIndexFunction`. Because the index declares `support_phrase_search = 0`, `getDirectReadMode` returns `Hint`, the only mode that keeps the original predicate beside the index virtual column, so that injection is observable. Before ClickHouse#116381, index analysis cancelled a pair of `not` unconditionally, so `not(not(hasPhrase(...)))` canonicalised to the bare atom, the outer `not` node became the replacement key, and `replaceNodes` returned early on it without descending into its children, so the injected three-argument call never reached the executed predicate. `EXPLAIN actions = 1` shows both sides: before Filter column: __text_index_idx_hasPhrase_5d43... AND NOT NOT hasPhrase(text, 'ello50 wor') after Filter column: NOT NOT (__text_index_idx_hasPhrase_5d43... AND hasPhrase(text, 'ello50 wor', 'ngrams(3)')) ClickHouse#116381 fixed this on master by blocking only the unsound half of the cancellation, so this commit adds no source change. `05043_not_in_value_position_key_condition` pins the index-analysis consequence of that fix; the direct-read rewrite had no test of its own. `hasAnyTokens` and `hasAllTokens` take the same injected tokenizer argument, but over a plain text index `getDirectReadMode` gives them `Exact` mode, which drops the original predicate, so this seam is reachable only for a non-positional `hasPhrase` and no sibling arm is added. With the one line of ClickHouse#116381 reverted locally, `not not p` and `prewhere not not p` report 0 instead of 10 (20 of 20 randomized runs fail); on master 50 of 50 randomized runs pass. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118321&sha=518eff241122633d224affa709900640c1544c07&name_0=PR&name_1=AST%20fuzzer%20%28amd_release%2C%20oracle%29 Related: ClickHouse#118321 Related: ClickHouse#116381 Co-Authored-By: Claude Opus 5 <[email protected]>
cloneDAGWithInversionPushDownpushes an inversion through everynot, so a pair of them cancelsout and the argument replaces the result. That is only truthiness-preserving:
not(not(x))isx != 0, aUInt8in{0, 1}, notxitself. Where the value is merely truth-tested that isexactly 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 asc0 > -0.5, andpruning dropped every part, granule and partition whose values are negative:
The same shape reached primary-key pruning, partition pruning,
minmaxskip indexes andstatistics-based part pruning; it reproduces on 26.7. Only the cancellation is unsound: a
notthat receives an inversion in a value position now stays an ordinary function, so the atom is
opaque to index analysis. A
notthat merely sends an inversion into its child is still pusheddown in any position - the child either absorbs it into an equivalent two-valued complement
(
NOT notHas(...)still becomeshas(...)and matches the text index, asserted by04903_not_has_secondary_index) or gets an explicitnot()wrapper, both value-preserving. Atruth-tested
NOTis also pushed down as before, soWHERE NOT (c0 = 0)still uses the primarykey (asserted in the test with
force_primary_key = 1).This is the sibling of the all-NULL case fixed in #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, and SQLancer++'sNoRECandQUERY_PARTITIONING-hit this one predicate shape: 20 of the run's findings.
Verified by building the same commit with and without the change and running all 233
index/key-condition/pruning-related stateless tests under both: the only test whose result changes
is the new one.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix wrong results when a doubly negated expression is compared with a constant, such as
WHERE (NOT NOT c) > -0.5. Index analysis cancelled the twoNOTs and compared the column itselfwith the constant, pruning parts, granules and partitions that do match.
Documentation entry for user-facing changes
Workflow [PR]
Sync PR [sync-upstream/pr/116381]
Version info
26.9.1.822(included in26.9and later)