Skip to content

Do not cancel a pair of not in a value position during index analysis - #116381

Merged
alexey-milovidov merged 7 commits into
masterfrom
fix-not-in-value-position-key-condition
Sep 6, 2026
Merged

alexey-milovidov merged 7 commits into
masterfrom
fix-not-in-value-position-key-condition

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 25, 2026 •

Copy link
Copy Markdown
Member

cloneDAGWithInversionPushDown pushes an inversion through every not, so a pair of them cancels
out and the argument replaces the result. 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 before, 1001 after
SELECT sum((NOT (NOT c0)) > -0.5) FROM t;            -- 1001, the predicate really is always true

The same shape reached primary-key pruning, partition pruning, minmax skip indexes and
statistics-based part pruning; it reproduces on 26.7. Only the cancellation is unsound: a not
that receives an inversion in a value position now stays an ordinary function, so the atom is
opaque to index analysis. A not that merely sends an inversion into its child is still pushed
down in any position - the child either absorbs it into an equivalent two-valued complement
(NOT notHas(...) still becomes has(...) and matches the text index, asserted by
04903_not_has_secondary_index) or gets an explicit not() wrapper, both value-preserving. A
truth-tested NOT is also pushed down as before, so WHERE NOT (c0 = 0) still uses the primary
key (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++'s NoREC and QUERY_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):

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

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 two NOTs and compared the column itself
with the constant, pruning parts, granules and partitions that do match.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

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

Version info

  • Merged into: 26.9.1.822 (included in 26.9 and later)

`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.
@clickhouse-gh

clickhouse-gh Bot commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c43d84c]

Summary: ✅


AI Review

Summary

This PR makes KeyCondition stop cancelling NOT NOT x in value position during inversion pushdown, so index analysis no longer rewrites not(not(x)) into x where that changes the value and can prune matching data. The C++ change looks narrowly correct, but the new stateless test still does not prove the Statistics and minmax skip-index entrypoints it claims to cover.

Findings

⚠️ Majors

[tests/queries/0_stateless/05043_not_in_value_position_key_condition.sql:16] The statistics block only checks result counts on t_not_stats. Those queries still return the same answers when statistics-based part pruning never runs at all, so this does not actually pin the entrypoint the PR description says was affected. Suggested fix: materialize statistics and assert a Statistics section in EXPLAIN indexes = 1 for this predicate shape (for example with materialize_statistics_on_insert = 1, use_statistics = 0, and use_statistics_for_part_pruning = 1).

[tests/queries/0_stateless/05043_not_in_value_position_key_condition.sql:57] The skip index block has the same evidence gap: a full scan returns the same row counts, so the test stays green even if idx_c0 stops participating in index analysis entirely. Suggested fix: either force idx_c0 with force_data_skipping_indices = 'idx_c0' or assert its presence in EXPLAIN indexes = 1, so this really covers the minmax path mentioned in the PR description.

Final Verdict

Changes requested. The core fix looks sound, but the new regression test still leaves two claimed pruning entrypoints effectively unproven.

LLVM Coverage Report

Measured on commit c43d84c.

Metric Baseline Current Δ
Lines 88.70% 88.70% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 81.00% 81.00% +0.00%

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

Full report · Diff report

alexey-milovidov and others added 2 commits August 27, 2026 19:29
…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]>
@qoega qoega added the sqlancer Issue found by SQLancer tool label Aug 27, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing c43d84c58 with master 6113efbf0 (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

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

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

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

Job report

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @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 — Logical error: Part A doesn't exist (info: B) in the Upgrade check (amd_release). It is unrelated to this PR (which only changes KeyCondition index analysis), and I could not find an existing issue for it. Please provide a fix in a separate PR, or link the fix here if it is already in progress.

@groeneai

Copy link
Copy Markdown
Collaborator

Not this PR, and it is already fixed.

The abort is on the previous release binary, not on this PR's build. job.log resolved previous_release_tag=v26.7.5.10-stable, and the fault banner reads (version 26.7.5.10 (official build), ..., git hash: c7d5ecce0dd9ac4a24ab6111d7cf66876eb59793), which is the v26.7.5.10-stable commit. All 3863 version banners in clickhouse-server.err.log are 26.7.5.10, and clickhouse-server.upgrade.log (Starting ClickHouse 26.9.1.1, this PR's build) has no <Fatal> line.

Logical error: 'Part patch-4811bd937f1be8e9d5ec5374e149fefa-all_0_0_0_1 doesn't exist'
query: UPDATE t_lwu_block_number SET c2 = 'xx' WHERE id = 1;
ReplicatedMergeTreeSinkPatch::finishDelayed -> ReplicatedMergeTreeSink::commitPart
  -> MergeTreeData::Transaction::commit -> MergeTreeData::modifyPartState

That query is line 37 of tests/queries/0_stateless/03100_lwu_drop_update_race.sh in the 26.7.5.10 test tree: one thread loops DROP TABLE ... SYNC while another loops a lightweight UPDATE. In 26.7.5.10 the share lock in InterpreterUpdateQuery::execute is function-local, so it is released before the patch part is committed, and the concurrent DROP clears the data parts index under the sink.

Fix: #114826, merged to master on 2026-08-21. Backported by #116463 (26.3), #116465 (26.6) and #116466 (26.7, merged yesterday); 26.8 was branched after the fix and carries it natively. No separate PR is needed.

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 get_previous_release_tag.py resolves carries the fix, so until the next 26.7 patch release or a 26.8 stable release.


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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 4, 2026

@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.

LGTM

@alexey-milovidov alexey-milovidov self-assigned this Sep 5, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 5, 2026
Merged via the queue into master with commit 8696d4f Sep 6, 2026
174 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-not-in-value-position-key-condition branch September 6, 2026 00:29
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 6, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 9, 2026
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.
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 9, 2026
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.
pull Bot pushed a commit to SINHASantos/ClickHouse that referenced this pull request Sep 19, 2026
`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]>
@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

Labels

comp-key-condition Analysis of a filter against a key. KeyCondition turns a WHERE condition into ranges over the pri... pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo sqlancer Issue found by SQLancer tool

Projects

None yet

4 participants