Skip to content

Add notHas function - #109926

Merged
alexey-milovidov merged 29 commits into
ClickHouse:masterfrom
nihalzp:function-not-has
Aug 17, 2026
Merged

alexey-milovidov merged 29 commits into
ClickHouse:masterfrom
nihalzp:function-not-has

Conversation

@nihalzp

@nihalzp nihalzp commented Jul 9, 2026 •

Copy link
Copy Markdown
Member

This is needed to bridge the gap between NOT IN and NOT has() during index analysis. Currently, NOT IN becomes notIn (a single atom) but NOT has() becomes not(has()) (two atoms); as a result, relaxation propagation is weaker and we will prune less in some cases after #96225. This PR allows NOT IN and NOT has() to be later made symmetric to index analysis.

Adds the function notHas(haystack, needle) — the negation of has for arrays, maps, and JSON. It is computed as not(has(haystack, needle)).

SELECT notHas([1, 2, 3], 4);            -- 1
SELECT notHas([NULL, 1], NULL);         -- 0
SELECT notHas(map('a', 1), 'b');        -- 1
SELECT notHas('{"a" : 1}'::JSON, 'b');  -- 1

RewriteHasToInPass (optimize_rewrite_has_to_in, enabled by default) now also rewrites notHas(constant_array, x) to notIn(x, constant_array), under the same safety guards as the existing has to in rewrite (constant NULL-free array, no Nullable/LowCardinality needle, types that compare identically under has and IN).

CREATE TABLE t (x UInt64) ENGINE = MergeTree ORDER BY x SETTINGS index_granularity = 1;
INSERT INTO t SELECT intDiv(number, 4) FROM numbers(24);

EXPLAIN indexes = 1 SELECT count() FROM t WHERE notHas([1], x);
-- Condition: (x notIn 1-element set)
-- Granules: 21/24

During index analysis, NOT has(constant_array, key) is folded into the single notHas leaf, which is what makes it symmetric with notIn. NOT has(column, needle) is deliberately left as not(has(...)): KeyCondition cannot build a set atom out of that shape anyway, while the text index and the bloom filter index analyzers understand has but not notHas, so folding it would cost them the atom - and, for a text index, the direct read from the index.

When the rewrite does not apply, notHas executes as-is with full has semantics.

Changelog category (leave one):

  • New Feature

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

Add function notHas, the negation of has for arrays, maps, and JSON. When the haystack is a constant array, notHas(constant_array, x) is rewritten to x NOT IN constant_array by optimize_rewrite_has_to_in (enabled by default), so it executes via a set lookup and can prune by the primary key index like NOT IN.

Version info

  • Merged into: 26.8.1.1576 (included in 26.8 and later)

@clickhouse-gh

clickhouse-gh Bot commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8e936d3]

Summary: ✅


AI Review

Summary

This PR adds notHas, rewrites safe constant-array calls to notIn, and teaches KeyCondition / skip-index analysis about the new negative containment shape. Most of the earlier edge cases around NOT has, NaN, and nullable sets are covered now, but the negative key-condition fast path still accepts cross-type constant arrays whose raw Field semantics do not match set-style casting, so the PR can still prune matching granules incorrectly.

Findings

❌ Blockers

  • [src/Storages/MergeTree/KeyCondition.cpp:2791] tryPrepareSetIndexForHas only guards the new negative set-atom path against float/NaN mismatches, but has on constant arrays diverges from cast-based set membership for several non-float type pairs too. RewriteHasToInPass already rejects DateTime vs Date, String vs Enum, IPv4 vs UInt32, and similar cases for that reason. Here tryPrepareSetColumnsForIndex will still cast representable values into the key type and build FUNCTION_NOT_IN_SET, so notHas(..., key) / folded NOT has(..., key) can prune rows that actually satisfy the predicate; e.g. on an Enum8('a' = 1, 'b' = 2) primary key, notHas(['a'], x) should be true for every row, but the key condition can skip the x = 'a' granule as if the predicate were x NOT IN ('a'). Suggested fix: apply the same type-compatibility gate used in RewriteHasToInPass before constructing any set atom for has / notHas, and keep the negative path disabled when constant-array Field equality is not equivalent to key-type casting.
Tests
  • ⚠️ Add a focused MergeTree regression on a keyed Enum or Date column that exercises notHas(constant_array, key) and folded NOT has(constant_array, key) both with and without use_primary_key. The test should use a representable cross-type value (['a'] vs Enum8('a' = 1) or DateTime vs Date) so the failure is wrong-result pruning, not a type error.
Final Verdict

❌ Changes requested: the new negative has set-atom path still lacks the cross-type safety gate that the analyzer rewrite already relies on, so it can produce wrong results on keyed tables.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.80% 86.80% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.20% 79.20% +0.00%

Changed lines: Changed C/C++ lines covered: 97/109 (88.99%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Jul 9, 2026
Comment thread src/Analyzer/Passes/HasToInPass.cpp Resolved
@EmeraldShift

Copy link
Copy Markdown
Contributor

I'm curious to lean more about how the relaxation propagation is different between having one atom and having two, as I would have naively guessed they'd be the same. Is this something that fixing or reworking relaxedness can fix?

@nihalzp

nihalzp commented Jul 10, 2026

Copy link
Copy Markdown
Member Author

I'm curious to lean more about how the relaxation propagation is different between having one atom and having two, as I would have naively guessed they'd be the same. Is this something that fixing or reworking relaxedness can fix?

Currently, if the ORDER BY key is wrapped in non-injective function, we can never prune not IN and not has() safely (so ideally we should not create the atom at all); but we do:

CREATE TABLE t (x UInt64) ENGINE = MergeTree ORDER BY intDiv(x, 2) SETTINGS index_granularity = 1;

INSERT INTO t SELECT intDiv(number, 4) FROM numbers(24);
SELECT trimLeft(explain) FROM (EXPLAIN indexes = 1 SELECT count() FROM t WHERE x NOT IN (1)) WHERE explain LIKE '%Condition%' OR explain LIKE '%Granules:%/%';

-- Condition: (intDiv(x, 2) notIn 1-element set)
-- Granules: 24/24

SET optimize_rewrite_has_to_in = 0;

SELECT trimLeft(explain) FROM (EXPLAIN indexes = 1 SELECT count() FROM t WHERE NOT has([1], x)) WHERE explain LIKE '%Condition%' OR explain LIKE '%Granules:%/%';

-- Condition: not((intDiv(x, 2) in 1-element set))
-- Granules: 24/24

But there is no need to. We can just skip creating atom in such cases because it does not help at all. In that PR #96225, I will add this optimization and that's why need to be able to detect NOT has() similar to NOT IN.

@clickhouse-gh

clickhouse-gh Bot commented Jul 10, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.80% 85.80% +0.00%
Functions 92.70% 92.70% +0.00%
Branches 77.90% 77.90% +0.00%

Changed lines: Changed C/C++ lines covered: 76/82 (92.68%) · Uncovered code

Full report · Diff report

@ahmadov ahmadov self-assigned this Jul 27, 2026
@alexey-milovidov alexey-milovidov self-assigned this Aug 14, 2026
robot-clickhouse added 5 commits August 14, 2026 22:12
`KeyCondition` can only build a set atom out of `has(constant_array, key)` - `tryPrepareSetIndexForHas`
bails on anything else - so that is the only shape where folding `NOT has(...)` into the single `notHas`
leaf buys anything.

Folding it unconditionally cost the text index its direct read. The text index condition is built from the
canonicalized DAG, so the `notHas` leaf made it `FUNCTION_UNKNOWN`; `alwaysUnknownOrTrue` then kept the
index out of `skip_indexes.useful_indices`, and `collectTextIndexReadInfos` builds `text_index_read_infos`
from exactly that list, so `optimizeDirectReadFromTextIndex` had nothing left to rewrite. Measured against
a master binary, `SELECT max(id) FROM t WHERE NOT has(arr, 'w3')` stopped reading the index through
`__text_index_idx_has_...` entirely.

Granule counts were never affected: a negated containment atom can never prune a bloom filter or a text
index. `has` pushes `BoolMask(may_be_present, /* can_be_false */ true)`, so `not(has(...))` pushes
`BoolMask(true, may_be_present)` - `can_be_true` is unconditionally true, exactly like an unrecognized
atom - and `can_be_true` of `and`/`or` never reads `can_be_false`.
Covers the secondary index paths outside the primary key one: `bloom_filter`, `tokenbf_v1` and `text`
with the array tokenizer, with the direct read from the text index both off and on. Asserts that `has`,
`NOT has` and `notHas` agree with each other and with `use_skip_indexes = 0`, that the granule counts
are unchanged, that a positive sibling in the same conjunction still prunes next to the negated atom,
and that `NOT has` still reaches the text index through its virtual column.
Master is `v26.8.1.1-new` and `26.7` is already branched, so the version this function first appears
in is 26.8, not 26.7.
`notHas` takes the same arguments as `has`, so it belongs in the containment group the fuzzer swaps
function names within.
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 The major finding is real, and it is now fixed. I measured it instead of reasoning about it: I ran the same skip-index queries against a master binary (cb85adde17, 26.8.1) and against this branch, and NOT has(arr, 'w3') lost the direct read from the text index:

master: FUNCTION not(__text_index_idx_has_aadacba4a6351756469755b95f388b12 :: 0) -> not(has(__table1.arr, 'w3'_String))
branch: (nothing - the virtual column is gone)

The chain is a bit longer than "the analyzers only whitelist has". MergeTreeIndexConditionText is built from the canonicalized DAG, so the notHas leaf makes it FUNCTION_UNKNOWN; alwaysUnknownOrTrue then keeps the index out of skip_indexes.useful_indices (ReadFromMergeTree.cpp), and collectTextIndexReadInfos builds text_index_read_infos from exactly that list - so optimizeDirectReadFromTextIndex has nothing to work with. replaceToVirtualColumn would fail anyway, because it looks the search query hash up in all_search_queries, which is also populated from that canonicalized RPN.

Granule counts are a different story: a negated containment atom can never prune a bloom filter or a text index. has pushes BoolMask(may_be_present, /* can_be_false */ true), so not(has(...)) pushes BoolMask(true, may_be_present) - can_be_true is unconditionally true, exactly like FUNCTION_UNKNOWN. In the canonicalized DAG not only ever wraps a leaf (and/or are turned around by De Morgan), and can_be_true of and/or never reads can_be_false, so that substitution cannot change a granule count. Master and this branch both select 16/16 granules for NOT has(arr, 3) on bloom_filter, tokenbf_v1 and text, and 8/16 for NOT has(arr, 3) AND has(arr, 5).

So the fix is scoped to where the fold actually buys something: canFoldToInverseRelation in KeyCondition.cpp now applies the has/notHas inverse relation only when the haystack is constant. KeyCondition can only build a set atom out of has(constant_array, key) - tryPrepareSetIndexForHas bails on anything else - so NOT has(column, needle) stays not(has(...)) and every secondary-index consumer sees exactly what it saw before. The NOT IN / NOT has symmetry this PR is about is unaffected: it is about the constant-array shape, and so is the follow-up in #96225.

Added 04903_not_has_secondary_index for the requested regression coverage outside the primary key path: bloom_filter, tokenbf_v1 and text (with the direct read both off and on), asserting identical results for has / NOT has / notHas with and without use_skip_indexes, identical granule counts, that a positive sibling in the same conjunction still prunes, and that NOT has still reaches the text index through the virtual column.

One thing I did not fold in: a user-written notHas(column, needle) gets no text index usage at all, while NOT has(column, needle) gets the direct read. That is a gap in the new function rather than a regression, and closing it needs care - a hint-mode virtual column is an over-approximation, so negating it is unsound and only exact mode would be safe - so it is better as its own change.

Also merged master into the branch - it was five weeks behind - which takes care of both failures on the old run. test_replicated_database/test.py::test_replicated_table_structure_alter was a master-wide breakage between 2026-07-10 and 2026-07-24 (up to 176 failures a day across ~120 pull requests, tracked and closed in #110036), and the Upgrade-check Replicated-database UUID collision in clickhouse-server.log was a master flake spread over single unrelated pull requests that stopped after 2026-07-25. Neither is reachable from adding a function.

Two small follow-ups in the same push: IntroducedIn moved from 26.7 to 26.8, since master is v26.8.1.1-new and 26.7 is already branched, and notHas was added to the QueryFuzzer group of same-signature containment functions so the fuzzer exercises it.

Locally: the 5 reference tests this PR updates, 04509_not_has_function, 04510_not_has_function_explain, the pre-existing 01078_bloom_filter_operator_not_has and 01771_bloom_filter_not_has, and the new test all pass, and the 179-test text_index suite is clean except 02346_text_index_direct_read, which fails identically on a master binary here because its system.text_log section needs the CI server config.

@clickhouse-gh

clickhouse-gh Bot commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 8e936d389 with master 0fc2db323 (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 694.63 MiB 691.63 MiB -2.99 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.

Object file sizes

6 object files changed (+177.61 KiB total), 1 added.

Object file Master PR Δ
src/Functions/array/CMakeFiles/clickhouse_functions_array.dir/notHas.cpp.o new 165.42 KiB +165.42 KiB

737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

11 translation units recompiled, 41 s compile time in total, 10 of them have a recent master baseline.

Job report

Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
Preserve `NULL` set members for nullable primary keys in `tryPrepareSetColumnsForIndex` and cover `notHas` and `NOT IN` pruning.\n\nhttps://github.com/ClickHouse/pull/109926
Construct the nullable set column with mutable columns and use the data type nullability predicate. This resolves the `KeyCondition.cpp` build failures reported by CI.\n\nhttps://github.com/ClickHouse/pull/109926
Treat `Nothing` array elements as source NULLs when preparing a set index for a nullable primary key. This keeps the `notIn` atom for `notHas([NULL], key)` instead of mistaking the values for failed casts.

ClickHouse#109926

const DataTypePtr & array_nested_type = array_data_type->getNestedType();

/// `has` uses accurate equality for array elements, while MergeTreeSetIndex compares floating-point

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.

This new notHas / folded NOT has fast path still treats float/NaN as the only semantic mismatch, but constant-array has diverges from set-style casting for several non-float type pairs too. RewriteHasToInPass already has that broader guard (DateTime vs Date, String vs Enum, IPv4 vs UInt32, and similar), because has on a constant array compares raw Fields rather than the casted key type.

Here we go straight into tryPrepareSetColumnsForIndex, which will retain representable values and then expose notHas(..., key) as FUNCTION_NOT_IN_SET. On a keyed Enum8('a' = 1, 'b' = 2) column, for example, notHas(['a'], x) should be true for every row (the same constant-array semantics already covered by 03916_has_to_in), but this path casts 'a' to the enum value and prunes the x = 'a' granule as if the predicate were x NOT IN ('a').

I think tryPrepareSetIndexForHas needs the same type-compatibility gate as RewriteHasToInPass before it builds any set atom: exact same non-float type after stripping LowCardinality, or both native integers.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This can be addressed separately.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🕵 Fixed in #115233. KeyCondition now uses a set atom only when the constant-array element and primary-key types share raw Field equality semantics; the regression covers String elements against an Enum8 key.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 17, 2026
Merged via the queue into ClickHouse:master with commit f264deb Aug 17, 2026
181 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 17, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Aug 18, 2026
Master's notHas work (PR ClickHouse#109926) changed two behaviours this suite pinned, and both
changes are master's own, measured identical on an A/B where the only difference is this
branch's KeyCondition.cpp:

- 947f172 / 495d342 refuse a set atom for any array with a floating-point element,
  because has() uses accurate equality while MergeTreeSetIndex compares with compareAt.
  The `Point` cell was written when the outer custom name decided the outcome; the float
  ban now decides it first, so the cell asserts the decline instead of the atom.
- 6f549ee / 1418e54 preserve NULL set members for a nullable key, so the two
  `lossy ... NOT has` oracle columns agree with the Memory oracle where they previously
  diverged.

No source change. Both cells were re-verified as live oracles by mutating them and
confirming the file reddens, and the suite's arm discipline is unchanged: 7 of the 10
family files still fail on a pristine-master binary, and the 3 that pass hold only
agreement controls, each proven live by the same mutation check.
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Aug 18, 2026
…-explain-tests

Resolve the KeyCondition.cpp conflict in tryPrepareSetColumnsForIndex.

Master's ClickHouse#109926 rewrote the Nullable-source block and now handles the
non-Nullable-key case this branch had addressed on its own, in a strictly
more general form: it also preserves a NULL set member for a Nullable key
and treats a Nothing element as a source NULL. Master's version of that
block is taken whole, and the branch's own source-NULL filtering, which
master subsumes, is dropped.

What this branch still contributes is the equality-preservation of the set
conversion, which master does not cover: keyToSetConversionMayCollapse
declines an atom whose runtime key-to-set cast can map two distinct keys
onto one set value, and set_is_approximate relaxes an atom whose forward
set-to-key cast is not equality-preserving. Both are kept, rebased onto
master's variable names, and the approximate flag is now raised outside the
per-row loop next to master's source_null_map handling.

Master independently updated 03733_has_function_key_condition_explain to
the same expected set sizes this branch had produced, so that reference no
longer differs.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-feature Pull request with new product feature 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.

5 participants