Repository navigation
Rewrite has(<constant array>, <expr>) to IN - #97341
Conversation
|
Workflow [PR], commit [6d64235] Summary: ✅ AI ReviewSummaryThis PR introduces an analyzer pass that rewrites Findings
Final VerdictStatus:
|
| 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 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Done, updated most tests to check with both has() and rewrite toIN and some to run with the new setting to 0.
|
When |
|
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. |
There was a problem hiding this comment.
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
RewriteHasToInPassto transformhas(const_array, x)intoin(x, const_array)underoptimize_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. |
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 | |||
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
|
clean CI run at 5b2aac7 |
|
Something bad with the sync PR, closed it and triggering a new sync PR. |
LLVM Coverage Report
Changed lines: 92.42% (61/66) · Uncovered code |
|
@groeneai do a comparison of |
|
@fm4v as of master (with PR #93813 "Add support for Where each form is recognized
Primary-key pruning - empirical checkTested on master (debug build, 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 granulesSame predicate via three forms:
5 granules out of 1221, same Why - in one sentence
When the rewrite does NOT fire
In every one of those cases, Historical noteBefore PR #93813 (merged 2025-11-27), |

Ref : internal ticket. A
has()call with a constant array containing 10s of elements is very slow compared to the same condition written usingIN. This PR just rewrites thehas()to ain()if a constant array is the argument. Thehasimplementation has to handle both const and non-const arrays.Example -
v/s
TODO - Some more tests with NULL, JOINs, CASE etc. Let me check the results with default setting to 1.
Changelog category
Changelog entry
has(<constant array>, <expr>), the analyzer will transform the node to use a fasterin()implementation if it is feasible to do so.Version info
26.6.1.209