Skip to content

Rewrite has(<constant array>, <expr>) to IN - #97341

Merged
shankar-iyer merged 37 commits into
ClickHouse:masterfrom
shankar-iyer:has_to_in
May 28, 2026
Merged

shankar-iyer merged 37 commits into
ClickHouse:masterfrom
shankar-iyer:has_to_in

Conversation

@shankar-iyer

@shankar-iyer shankar-iyer commented Feb 19, 2026 •

Copy link
Copy Markdown
Member

Ref : internal ticket. A has() call with a constant array containing 10s of elements is very slow compared to the same condition written using IN. This PR just rewrites the has() to a in() if a constant array is the argument. The has implementation has to handle both const and non-const arrays.

Example -

SELECT COUNT(*)
FROM hits
WHERE has([8870915600312787184, 8684171118223012123, 8574107276198705358, 6263646819421161387, 
  6206125822616017172, 6168830513084475205, 7356558383366006351, 5037751398894358551, 
  8727011889259436312, 4830510014642617077, 5133794716250984238, 6562561149933416515, 
  6656932073178464385, 8490346753223334783, 6991702910161899868, 6516417990354410952, 
  7743303383283164948, 5975683574520711341, 5848138144997547995, 7726962265612126939, 
  6216627901075210457, 9122077181398203511, 5624662116742960725, 5565372313553016751, 
  5380347431141317864, 6927569105072956735, 7967750689219088342, 7084825557630192816, 
  8977521527866504922, 4834088356461824902], WatchID)
SETTINGS use_query_condition_cache = 0, optimize_rewrite_has_to_in = 0

Query id: 6fd18803-fad0-4097-b409-b1bba5673e41

   ┌─COUNT()─┐
1. │      30 │
   └─────────┘

1 row in set. Elapsed: 4.224 sec. Processed 507.65 million rows, 4.06 GB (120.18 million rows/s., 961.43 MB/s.)
Peak memory usage: 1.20 MiB.

v/s

SELECT COUNT(*)
FROM hits
WHERE has([8870915600312787184, 8684171118223012123, 8574107276198705358, 6263646819421161387, 
  6206125822616017172, 6168830513084475205, 7356558383366006351, 5037751398894358551, 
  8727011889259436312, 4830510014642617077, 5133794716250984238, 6562561149933416515, 
  6656932073178464385, 8490346753223334783, 6991702910161899868, 6516417990354410952, 
  7743303383283164948, 5975683574520711341, 5848138144997547995, 7726962265612126939, 
  6216627901075210457, 9122077181398203511, 5624662116742960725, 5565372313553016751, 
  5380347431141317864, 6927569105072956735, 7967750689219088342, 7084825557630192816, 
  8977521527866504922, 4834088356461824902], WatchID)
SETTINGS use_query_condition_cache = 0, optimize_rewrite_has_to_in = 1

Query id: 2477e36a-8b35-48fe-a8a9-9ceda207fca8

   ┌─COUNT()─┐
1. │      30 │
   └─────────┘

1 row in set. Elapsed: 0.192 sec. Processed 507.65 million rows, 4.06 GB (2.65 billion rows/s., 21.20 GB/s.)
Peak memory usage: 1.26 MiB.

TODO - Some more tests with NULL, JOINs, CASE etc. Let me check the results with default setting to 1.

Changelog category

  • Performance Improvement

Changelog entry

  • If a query contains a has(<constant array>, <expr>), the analyzer will transform the node to use a faster in() implementation if it is feasible to do so.

Version info

  • Merged into: 26.6.1.209

@shankar-iyer
shankar-iyer marked this pull request as draft February 19, 2026 09:16
@clickhouse-gh

clickhouse-gh Bot commented Feb 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6d64235]

Summary: ✅


AI Review

Summary

This PR introduces an analyzer pass that rewrites has(<constant array>, <expr>) into in(<expr>, <constant array>) behind optimize_rewrite_has_to_in, with multiple correctness guards (nullable/low-cardinality, complex types, float handling, and type-compatibility) plus regression tests. The core rewrite logic and prior semantic issues discussed on the PR look addressed, but one test-coverage regression remains.

Findings

⚠️ Majors

  • [tests/queries/0_stateless/03778_deterministic_injective_functions_key_condition_rewrite_has.sql:1] The no-replicated-database and no-parallel-replicas tags are stale for this new test. The file no longer contains EXPLAIN-text assertions and only checks deterministic counts, so these tags unnecessarily suppress coverage in replicated/parallel-replica runs.
    Suggested fix: remove both no-* tags (and the stale explanatory comments), or add a reproducible reason specific to this test for keeping each tag.
Final Verdict

Status: ⚠️ Request changes
Minimum required actions:

  1. Remove stale no-replicated-database / no-parallel-replicas tags from 03778_deterministic_injective_functions_key_condition_rewrite_has.sql (or document a concrete reproducible need for each).

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Feb 19, 2026
@shankar-iyer shankar-iyer reopened this Feb 19, 2026
Comment on lines 56 to 66
MinMax
Keys:
dt
Condition: not((dt in 1-element set))
Condition: (dt notIn 1-element set)
Parts: 40/40
Granules: 960/960
Partition
Keys:
toDate(dt)
Condition: not((toDate(dt) in 1-element set))
Condition: true
Parts: 40/40
Granules: 960/960
Ranges: 40

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.

We should duplicate the tests here: once with optimize_rewrite_has_to_in = 0 and once with optimize_rewrite_has_to_in = 1; otherwise, we will lose coverage.

Additionally, I am worried there are other tests where we will stop exercising the has function paths in KeyCondition.cpp. As a result, future bugs in that area might not get caught. If possible, we can consider duplicating them as well if it's not too hard.

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.

Done, updated most tests to check with both has() and rewrite toIN and some to run with the new setting to 0.

@geldot

geldot commented Feb 24, 2026

Copy link
Copy Markdown
Contributor

When SETTINGS transform_null_in = 1 it would also be safe to transform has([1, NULL], i) into in(i, [1, NULL]) right? Would handling this case achieve a similar performance win? (Ref #77906)

@shankar-iyer

Copy link
Copy Markdown
Member Author

@geldot @nihalzp Busy with some other work, I will respond in a couple of days!

@clickhouse-gh

clickhouse-gh Bot commented Apr 28, 2026

Copy link
Copy Markdown
Contributor

Dear @shankar-iyer, this PR hasn't been updated for a while. Will you continue working on it? If not, please close it. Otherwise, ignore this message.

Copilot AI left a comment

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.

Pull request overview

This PR adds an analyzer optimization that rewrites has(<constant array>, <expr>) into the faster in(<expr>, <constant array>), controlled by a new setting optimize_rewrite_has_to_in (default enabled). It also adds stateless tests, extends an existing pruning test to cover the rewritten form, and includes a performance benchmark query.

Changes:

  • Add RewriteHasToInPass to transform has(const_array, x) into in(x, const_array) under optimize_rewrite_has_to_in.
  • Introduce and document the new setting (default true) and register it in compatibility history.
  • Add new stateless tests and a performance test covering the rewrite and its impact on index usage.

Reviewed changes

Copilot reviewed 11 out of 11 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
tests/queries/0_stateless/03916_has_to_in.sql New stateless test coverage for the rewrite (functional + EXPLAIN-based assertions).
tests/queries/0_stateless/03916_has_to_in.reference Expected output for the new stateless test.
tests/queries/0_stateless/03904_has_function_partition_pruning_key_condition.sql Extends partition-pruning test to run both with rewrite disabled and enabled.
tests/queries/0_stateless/03904_has_function_partition_pruning_key_condition.reference Updates expected output to include the additional rerun with rewrite enabled.
tests/queries/0_stateless/03762_has_in_function_key_condition_deterministic_function_chain_explain.sql Pins optimize_rewrite_has_to_in=0 to preserve existing expected EXPLAIN behavior.
tests/performance/has_to_in_hits.xml Adds a performance benchmark query reproducing the slow has([...], WatchID) case.
src/Core/SettingsChangesHistory.cpp Records the new setting in settings compatibility history.
src/Core/Settings.cpp Declares and documents optimize_rewrite_has_to_in.
src/Analyzer/QueryTreePassManager.cpp Registers the new analyzer pass in the pass pipeline.
src/Analyzer/Passes/HasToInPass.h Declares RewriteHasToInPass.
src/Analyzer/Passes/HasToInPass.cpp Implements the rewrite and safety checks for semantic compatibility.

Comment thread src/Analyzer/Passes/HasToInPass.cpp Resolved
Comment thread src/Analyzer/Passes/HasToInPass.cpp Resolved
Comment thread src/Analyzer/Passes/HasToInPass.cpp Resolved
@shankar-iyer
shankar-iyer marked this pull request as ready for review May 16, 2026 09:20
Comment thread src/Analyzer/Passes/HasToInPass.cpp Resolved
Review on PR ClickHouse#97341 surfaced three correctness issues:

1. LowCardinality(Nullable) needle was not rejected because
   DataTypeLowCardinality::isNullable returns false, so has(arr, lc_nullable)
   was still rewritten despite has and in differing on NULL.
   ClickHouse#97341 (comment)

2. has on a constant array compares raw Field values
   (FunctionArrayIndex::executeConst uses accurateEquals) while in converts
   the right-hand side to the left-hand side type via convertFieldToType.
   The two diverge for types whose Field representation has different
   semantic meaning: Date vs DateTime, Enum vs String, IPv4 vs UInt32, etc.
   The rewrite is now allowed only when types match exactly (after stripping
   LowCardinality) or when both sides are native numbers (Int/UInt/Float),
   where accurateEquals handles mixed widths and signs correctly.
   ClickHouse#97341 (comment)

3. has returns UInt8 but `lc_col IN (...)` returns LowCardinality(UInt8).
   Rewriting in place leaves parent nodes resolved against UInt8 (e.g.
   `NOT has(...)` becomes `NOT in(...)` whose argument is
   LowCardinality(UInt8)) and trips a logical error. Skip the rewrite when
   the needle is LowCardinality. Found by the fuzzer.

Also adds a defensive haystack guard for Array(LowCardinality(Nullable(T)))
and Array(Nullable(T)) element types, even though the value-level NULL
check would normally catch these — constant-folded inputs could otherwise
slip through.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@@ -0,0 +1,78 @@
-- Tags: no-replicated-database, no-parallel-replicas

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 test no longer has EXPLAIN-text assertions and only checks deterministic counts on a local MergeTree table, so the no-replicated-database and no-parallel-replicas tags look stale. Keeping them needlessly reduces coverage on replicated/parallel-replica runs.

Please remove these no-* tags unless there is a reproducible divergence without them.

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 is still live on current HEAD: tests/queries/0_stateless/03778_deterministic_injective_functions_key_condition_rewrite_has.sql has no EXPLAIN assertions, so no-replicated-database and no-parallel-replicas are no longer justified by this file.

Keeping these tags unnecessarily drops coverage in replicated/parallel-replica runs. Please remove both tags (and the stale explanatory comments) unless there is a reproducible divergence for this exact test without them.

Comment thread src/Analyzer/Passes/HasToInPass.cpp Resolved
@shankar-iyer

Copy link
Copy Markdown
Member Author

clean CI run at 5b2aac7

@shankar-iyer

Copy link
Copy Markdown
Member Author

For reference :
Screenshot 2026-05-21 at 2 30 12 PM

@shankar-iyer

Copy link
Copy Markdown
Member Author

Something bad with the sync PR, closed it and triggering a new sync PR.

@clickhouse-gh

clickhouse-gh Bot commented May 27, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 91.40% 91.40% +0.00%
Branches 76.60% 76.50% -0.10%

Changed lines: 92.42% (61/66) · Uncovered code

Full report · Diff report

@shankar-iyer
shankar-iyer added this pull request to the merge queue May 27, 2026
Merged via the queue into ClickHouse:master with commit 3f16d30 May 28, 2026
166 checks passed
@shankar-iyer
shankar-iyer deleted the has_to_in branch May 28, 2026 00:00
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label May 28, 2026
@fm4v

fm4v commented Jun 1, 2026

Copy link
Copy Markdown
Member

@groeneai do a comparison of has and IN regarding indexes support. Also primary key pruning with has and IN

@groeneai

groeneai commented Jun 1, 2026

Copy link
Copy Markdown
Collaborator

@fm4v as of master (with PR #93813 "Add support for has to skip granules" merged 2025-11-27 and this PR #97341 merged 2026-05-28), has(const_array, key_col) and key_col IN const_array produce identical index and primary-key pruning. The rewrite added here is a runtime evaluation speedup for the rows that survive pruning, not a pruning enabler.

Where each form is recognized

Surface has(const_array, x) x IN const_array Notes
Primary key (KeyCondition) yes - tryPrepareSetIndexForHas (src/Storages/MergeTree/KeyCondition.cpp:2429), atom_map["has"] -> FUNCTION_IN_SET (line 456) yes - tryPrepareSetIndexForIn, atom_map["in"/"globalIn"/...] -> FUNCTION_IN_SET Both lower to MergeTreeSetIndex and the same RPN atom FUNCTION_IN_SET. PK pruning happens via generic exclusion search on the same set.
minmax skip index yes yes Built on top of KeyCondition; inherits the same atoms (MergeTreeIndexMinMax.cpp:194).
set skip index yes yes MergeTreeIndexConditionSet::atomFromDAG replays any function whose arguments reduce to (index column, constants) verbatim against the indexed values - no function whitelist.
bloom_filter skip index yes - FUNCTION_HAS yes - FUNCTION_IN Explicit cases in MergeTreeIndexBloomFilter.cpp:484, 500, 519, 566.
bloom_filter text (tokenbf_v1, ngrambf_v1) yes - FUNCTION_HAS (used for has on Array(String) columns) yes - FUNCTION_IN MergeTreeIndexBloomFilterText.cpp:402, 384, 637.
Text / full-text index yes - FUNCTION_HAS_ANY_ELEMENTS yes - same FUNCTION_HAS_ANY_ELEMENTS for IN (MergeTreeIndexConditionText.cpp:490, 232) Both has and IN route into the tokenized lookup.
Vector similarity index n/a n/a Distance predicate only, not relevant here.

Primary-key pruning - empirical check

Tested on master (debug build, clickhouse local):

CREATE TABLE t_haskey (k UInt32, v String) ENGINE = MergeTree ORDER BY k SETTINGS index_granularity = 8192;
INSERT INTO t_haskey SELECT number, toString(number) FROM numbers(10_000_000);
OPTIMIZE TABLE t_haskey FINAL;
-- 1 part, 1222 granules

Same predicate via three forms:

A) WHERE has([7,42,100,1000,10000,100000,1000000,5000000], k)  SETTINGS optimize_rewrite_has_to_in = 0
B) WHERE has([7,42,100,1000,10000,100000,1000000,5000000], k)  SETTINGS optimize_rewrite_has_to_in = 1
C) WHERE k IN  (7,42,100,1000,10000,100000,1000000,5000000)

EXPLAIN indexes = 1 produces the byte-identical pruning plan for A, B, and C:

PrimaryKey
  Keys: k
  Condition: (k in 8-element set)
  Parts: 1/1
  Granules: 5/1221
  Search Algorithm: generic exclusion search
Ranges: 4

5 granules out of 1221, same generic exclusion search strategy in all three cases. Same result row count (8).

Why - in one sentence

KeyCondition::tryPrepareSetIndexForHas (added in PR #93813) builds the exact same MergeTreeSetIndex and RPNElement::FUNCTION_IN_SET atom that tryPrepareSetIndexForIn builds for IN, so downstream checkInRange and checkInHyperrectangle cannot tell them apart. The set is constructed from the constant array literal in both cases.

When the rewrite does NOT fire

HasToInPass.cpp skips the rewrite when:

  • optimize_rewrite_has_to_in = 0
  • first arg is not a constant array, or the array is empty / contains NULL
  • needle is Nullable / LowCardinality(Nullable) / Map / Array / Tuple / Object / Dynamic / Nothing
  • array element or needle is any float type (incl. BFloat16) - has uses accurateEquals (+0.0 == -0.0) while IN builds a Set keyed by raw bits
  • types differ and neither side is a native integer

In every one of those cases, has(...) is still recognized by KeyCondition and all skip indexes through the native has code path - pruning is still equivalent to IN, you just keep the slower row-level has execution. The rewrite is purely a performance optimization for the surviving rows, where for >~10-element arrays IN uses a hash set lookup and is much faster than FunctionArrayIndex::executeConst over Field values (the PR description shows ~50x).

Historical note

Before PR #93813 (merged 2025-11-27), has(const_array, key_col) was NOT recognized by KeyCondition and triggered a full scan even on a PK. Writing IN was the only way to get PK pruning. That gap was closed independently of this PR. Today the two forms are equivalent for pruning and the rewrite only matters for execution speed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-performance Pull request with some performance improvements 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.

8 participants