Skip to content

Use bloom filter skip index for arrayJoin(col) IN (set) and arrayJoin(col) = const - #109536

Merged
yariks5s merged 8 commits into
ClickHouse:masterfrom
groeneai:fix-bloom-filter-arrayjoin-in-109516
Aug 26, 2026
Merged

yariks5s merged 8 commits into
ClickHouse:masterfrom
groeneai:fix-bloom-filter-arrayjoin-in-109516

Conversation

@groeneai

@groeneai groeneai commented Jul 6, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #109516
Closes: #109844

Changelog category (leave one):

  • Improvement

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

A bloom_filter skip index on an Array column is now used for arrayJoin(column) IN (set), arrayJoin(column) GLOBAL IN (set) and arrayJoin(column) = const, the same way it was already used for hasAny(column, set) and has(column, const). Previously these arrayJoin ... forms fell back to a full scan.

Description

MergeTreeIndexConditionBloomFilter only accepted the argument of IN / = as an indexed column directly or one of a few wrappers (tuple, map subcolumns, JSON paths). arrayJoin(tags) matched none, so the atom became FUNCTION_UNKNOWN and nothing was pruned, while hasAny(tags, ...) / has(tags, ...) already pruned.

This PR recognizes arrayJoin(indexed_array_column) on the left side and maps:

  • arrayJoin(arr) IN (set) (and GLOBAL IN) to the same granule test as hasAny(arr, set_elements) (traverseTreeIn);
  • arrayJoin(arr) = const to the same granule test as has(arr, const) (traverseTreeEquals).

arrayJoin only multiplies rows, so a granule matches only if one of its array elements belongs to the set / equals the constant, which is what the bloom filter evaluates for hasAny / has. NOT IN / != are intentionally not handled: a granule containing a set element / the constant can still yield rows whose value is outside the set / differs.

Both derivations hash the constant after converting it towards the indexed element type, and SQL comparison coerces more widely than that conversion does. Where the two disagree the index was probed with bytes the predicate never compares, or the conversion threw during index analysis. Both are now gated on a proven-matching hash domain: an identical element and constant type, or integer against integer. Everything else is declined, leaving a full scan and keeping a conversion error reachable at execution rather than turning it into pruned granules. Integer widening and a LowCardinality wrapper stay admitted, so the pruning this PR adds is unchanged.

Verified with EXPLAIN indexes = 1 that the arrayJoin ... forms prune like hasAny / has, that NOT IN / != do not prune, and that results are identical with the skip index on and off for every declined domain and for the LEFT ARRAY JOIN case. Test: 04365_bloom_filter_arrayJoin_in.


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

Version info

  • Merged into: 26.9.1.161 (included in 26.9 and later)
  • Backported to: 26.8.1.2015, 26.7.6.18, 26.6.4.27

@groeneai

groeneai commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. EXPLAIN indexes = 1 on arrayJoin(tags) IN ('tag_42') deterministically shows Granules: N/N (full scan) on HEAD and Granules: 2/13 (pruned) with the fix, over a table of 100k rows / 13 granules with unique tags.
b Root cause explained? traverseTreeIn only accepted an IN left-hand side that was an indexed column or a known wrapper (tuple / map subcolumn / JSON path). arrayJoin(col) matched none, so the atom became FUNCTION_UNKNOWN and no granule was skipped, whereas hasAny(col, ...) dispatched to FUNCTION_HAS_ANY and pruned.
c Fix matches root cause? Yes. traverseTreeIn now recognizes arrayJoin(indexed_array_column) IN (set) / GLOBAL IN via a new RPNBuilderTreeNode::getArrayJoinArgument() (handles both the DAG ARRAY_JOIN node and the AST arrayJoin function) and maps it to the exact FUNCTION_HAS_ANY set-hashing path hasAny uses.
d Test intent preserved / new tests added? New test 04365_bloom_filter_arrayJoin_in asserts, via EXPLAIN indexes = 1 granule counts, that the index prunes for IN / subquery IN / GLOBAL IN, widens for a multi-element set, does NOT prune for NOT IN, and that results are unchanged. No existing test weakened.
e Demonstrated both directions? Yes. Built the baseline binary (fix reverted): arrayJoin ... IN forms read 12/12 granules while hasAny prunes to 2/12. With the fix: all arrayJoin ... IN forms prune to 2/12 identically.
f Fix is general, not a narrow patch? Covers const set, subquery set, and GLOBAL IN; the getArrayJoinArgument() helper handles both the analyzer (DAG) and old (AST) paths, both verified. NOT IN is deliberately excluded because a granule with a set element can still yield arrayJoined rows outside the set (unsafe to skip).
g Generalizes across inputs / datatypes? The set is cast to the array's nested type before hashing (same as the existing mapValues IN path), so it follows the established conversion for the element type. Single- and multi-element sets both verified.
h Backward compatible? Yes. Pure query-planning enhancement: it only enables additional granule skipping for a predicate that previously full-scanned. No setting, format, or default changes; results are identical.
i Invariants and contracts preserved? Yes. Reuses the existing FUNCTION_HAS_ANY bloom-filter contract and BloomFilterHash::hashWithColumn path. arrayJoin-argument extraction is null-safe (single-argument check) and returns std::nullopt for anything else, falling through to the prior behavior.

Session id: cron:clickhouse-worker-slot-2:20260706-155000

@groeneai

groeneai commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator Author

cc @rschu1ze @CurtizJ for review (skip index / bloom filter component) — extends traverseTreeIn to prune granules for arrayJoin(col) IN (set) via the existing hasAny bloom filter path.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jul 7, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ea22ef2]

Summary: ✅


AI Review

Summary

This PR extends the bloom-filter skip index so arrayJoin(col) IN (...) / GLOBAL IN (...) and arrayJoin(col) = const can prune marks through the existing hasAny / has logic, and the added regression coverage around coercion domains is materially better than earlier revisions. I did not find a remaining correctness issue in the current implementation, but one previously-discussed contract gap is still present: the advertised IN optimization disappears entirely under transform_null_in = 1.

Findings

⚠️ Majors

  • [dismissed by author -- https://github.com/Use bloom filter skip index for arrayJoin(col) IN (set) and arrayJoin(col) = const #109536#issuecomment-5359620663] [src/Storages/MergeTree/MergeTreeIndexBloomFilter.cpp:709] This branch only accepts raw in / globalIn, but TreeRewriter rewrites every ordinary IN / GLOBAL IN to nullIn / globalNullIn when transform_null_in = 1 (src/Interpreters/TreeRewriter.cpp:1669-1681). So the PR still does not cover the supported setting where users write the same SQL surface the title/body promise. Either handle the null-aware function names here with the same safety gate, or narrow the PR text/changelog and add a focused regression test that makes the unsupported setting explicit.
Final Verdict

⚠️ Request changes: the current implementation is sound for the raw in / globalIn cases it handles, but the promised arrayJoin(... ) IN optimization is still missing under transform_null_in = 1.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.00% 87.00% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.30% 79.30% +0.00%

Changed lines: Changed C/C++ lines covered: 52/60 (86.67%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jul 7, 2026
@groeneai

groeneai commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator Author

Fixed in 887a2f0. Thanks for catching the LEFT ARRAY JOIN hazard.

I took the second option you suggested (restrict the rewrite by the set contents) rather than propagating is_left through the DAG, because it is local and provably safe:

traverseTreeIn now falls back to no pruning whenever the IN set contains the element type's default value (Array nested type's getDefault(), e.g. '' / 0). Rationale: a LEFT ARRAY JOIN expands an empty array into one row holding that default, so col IN (default) can match a row produced from an all-empty-array granule that the bloom filter (hasAny semantics) never sees. Excluding default-containing sets makes an all-empty-arrays granule impossible to skip. Non-default sets still prune unchanged.

Verified against your case with a table of whole empty-array granules followed by unique-tag granules:

  • arrayJoin(tags) IN ('') and IN ('tag_x', '') now read 13/13 (no prune); IN ('tag_x') still prunes to 2/13.
  • Same for a numeric column: IN (0) no prune, IN (42) prunes.
  • SELECT count() FROM t LEFT ARRAY JOIN tags WHERE tags IN ('') returns the same result with use_skip_indexes=1 and =0 (20000 rows from the default-expanded empties).
  • Full use_skip_indexes on/off sweep across the INNER arrayJoin(...) IN, GLOBAL IN, subquery, and LEFT ARRAY JOIN forms shows identical results under both the analyzer (DAG) and old (AST) paths.

Regression added to 04365_bloom_filter_arrayJoin_in (empty-array table asserting 13/13 for default-containing sets, 2/13 for non-default, plus a LEFT ARRAY JOIN correctness check).

Note for context: the LEFT ARRAY JOIN clause with a bare column does not currently route an ARRAY_JOIN node into the skip-index filter (only the explicit INNER arrayJoin() function does), so I could not construct a wrong-result repro on HEAD without the guard. The guard is nonetheless correct-by-construction and removes the reliance on that invariant, so the branch stays safe if a future is_left ARRAY_JOIN ever reaches this code.

@groeneai

groeneai commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 887a2f0

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug, targeted) / STID 1941-26fa Inconsistent AST formatting trunk AST-fuzzer bug (84 hits / 72 PRs / 6 master, 14d; not this PR's diff) #106522 (external, open)
AST fuzzer (amd_debug, targeted) / STID 4419-44a9 KeyCondition uses PREWHERE output trunk AST-fuzzer bug (6 unrelated PRs / 0 master, 14d; Parquet-v3 key-condition root cause) #109267 (ours, open)
Stress test (amd_msan) / STID 0250-41a5 Not-ready Set is passed as the second argument trunk bug (85 hits / 75 PRs / 5 master, 14d) #107924 (external, open)
Performance Comparison (arm_release, master_head, 5/6) arm-perf report-build noise (all query rows success, no regression) #109397 (ours, open)
Stateless tests (amd_tsan, s3 storage, parallel, 2/2) / exit 125 docker daemon died during post-run chown teardown; all 5658 tests OK (signature A, NOT fixed by merged #109096 which fixes the 9000s watchdog signature B) a fix task is created (investigating at full effort — fixing-PR link to follow here)
CH Inc sync - CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260707-143000

A bloom filter skip index on an Array column was used for hasAny(col, set)
but not for the semantically equivalent arrayJoin(col) IN (set) / GLOBAL IN,
which fell back to a full scan.

Recognize arrayJoin(indexed_array_column) IN (set) (and GLOBAL IN) in
MergeTreeIndexConditionBloomFilter::traverseTreeIn and map it to the same
granule test as hasAny(indexed_array_column, set_elements). arrayJoin only
multiplies rows, so a granule can produce a matching row only if at least one
array element in the granule is in the set, which is exactly what the bloom
filter evaluates for hasAny. NOT IN is intentionally not handled: a granule
containing a set element can still yield rows whose arrayJoined value is
outside the set, so no granule can be skipped.

The rewrite fires only for the inner arrayJoin() function inside WHERE, which
has inner-array-join semantics: empty arrays produce no rows, so hasAny is
exact even when the set contains the element type's default value (a granule
of all-empty arrays yields no matching row; a granule that actually stores the
default value as an element is kept and returned). A LEFT ARRAY JOIN clause,
which expands empty arrays to a default-value row, keeps its predicate above
the ARRAY JOIN pipeline step and is never pushed into the skip index condition
(getConjunctionNodes rejects ARRAY_JOIN nodes from filter push-down), so it
cannot reach this branch and results stay correct. The test covers both the
default-value inner case (pruning still fires, correct result) and a LEFT
ARRAY JOIN over empty arrays (identical result with the skip index on and off).

Closes: ClickHouse#109516

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai
groeneai force-pushed the fix-bloom-filter-arrayjoin-in-109516 branch from 887a2f0 to d9af984 Compare July 7, 2026 15:34
@groeneai

groeneai commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator Author

Update on d9af984: I reverted the default-value guard I had added in 887a2f0. After investigating I could not construct any query where this branch produces a wrong result for a LEFT ARRAY JOIN, and the guard disabled a correct, useful optimization, so keeping it would have been a speculative change I can't back with a repro.

Reachability analysis:

  • This branch fires only for the inner arrayJoin(col) function inside WHERE — matched AST-side in RPNBuilderTreeNode::getArrayJoinArgument() via ast_function->name == "arrayJoin". That form has inner-array-join semantics: empty arrays produce no rows, so hasAny is exact even when the set contains the default value.
  • A genuine LEFT ARRAY JOIN <col> clause never reaches here. Its predicate stays above the ArrayJoinStep and is not pushed into the MergeTree index condition: getConjunctionNodes (ActionsDAG.cpp) rejects ARRAY_JOIN nodes from filter push-down, and filterPushDown.cpp restricts pushable inputs to non-array-joined columns. So the DAG ARRAY_JOIN path (where is_left is indeed dropped by addArrayJoin) is never consulted for skip-index analysis.

Verified against a table with a whole granule of empty arrays: LEFT ARRAY JOIN tags WHERE tags IN ('') returns the same result with use_skip_indexes on and off (no Skip line in EXPLAIN indexes = 1), and EXPLAIN shows no idx_tags usage for the left-array-join form in any of the plan variants I tried (analyzer on/off, filter push-down on/off).

The guard was also actively harmful: for the reachable inner form it stopped pruning whenever the set contained a default value, e.g. arrayJoin(tags) IN ('') where '' is a real element went from Granules: 2/13 to a full scan.

The test now covers both: a default-value inner case (pruning still fires and the result is correct) and a LEFT ARRAY JOIN over empty arrays (identical result with the skip index on and off). If you know a construction that does route a left-array-join predicate into this branch, I'm happy to take a closer look.

@groeneai

groeneai commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the s3-storage exit-125 signature-A (docker daemon death at post-run chown/teardown, all tests OK): #109673

@groeneai

groeneai commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — d9af984

Every failure below has an owner. None is caused by this PR (the diff is bloom-filter-only: MergeTreeIndexBloomFilter.cpp / RPNBuilder.* / the 04365 test).

Check / test Reason Owner / fixing PR
Stateless tests (amd_debug, parallel) / 04061_spilling_hash_join_overflow_limits flaky (66 PRs / 11 master, 30d) #109334 (ours, open)
Stress test (arm_debug) / Block structure mismatch in JoinStep (STID 0993-386d) trunk fuzzer bug (64 PRs / 2 master, 30d) #109114 (ours, open)
Stress test (amd_debug) / Got read request from replica 0 for unknown stream (STID 5217-505b) trunk logical-error, parallel-replicas coordinator #109202 (ours) — closed WONTFIX by @ nickitat: divergent reading modes for one table = a logical bug that should never happen on a real path; the guard intentionally keeps throwing, and it is only reachable via a failpoint under stress
Mergeable Check / PR aggregators — roll-up of the above; no independent failure
CH Inc sync — pass (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260707-200000

arrayJoin(arr) = x implies has(arr, x): a granule can produce a row
matching the equality only if some array element in the granule equals
the constant, which is exactly what the bloom filter evaluates for has.
Mapped in traverseTreeEquals via getArrayJoinArgument, mirroring the
existing arrayJoin(col) IN (set) -> hasAny handling. notEquals is not
derivable and is left as a full scan.

Closes: ClickHouse#109844

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai groeneai changed the title Use bloom filter skip index for arrayJoin(col) IN (set) Use bloom filter skip index for arrayJoin(col) IN (set) and arrayJoin(col) = const Jul 8, 2026
@groeneai

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate for the added arrayJoin(col) = const derivation (extends this PR beyond the IN form):

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. On the issue reproducer, EXPLAIN indexes=1 SELECT count() FROM t WHERE arrayJoin(tags) = 'tag_500000' reads 122/122 granules before, 1/122 after (deterministic, no randomization).
b Root cause explained? traverseTreeEquals only accepted an indexed column or known wrappers on the LHS of =. arrayJoin(col) matched none, so the atom became FUNCTION_UNKNOWN and no granule was skipped, while has(col, const) pruned via FUNCTION_HAS.
c Fix matches root cause? Yes. Recognize arrayJoin(indexed_array_col) on the LHS of equals and map it to the same FUNCTION_HAS granule test as has(col, const), reusing the existing getArrayJoinArgument helper added for the IN case.
d Test intent preserved / new tests added? New EXPLAIN-indexes assertions added to 04365_bloom_filter_arrayJoin_in for = (prune), != (no-prune), default-value/empty() fallback, and result-equality (skip index on vs off).
e Both directions demonstrated? Yes. Rebuilt without the change: = 'x' reads all granules; with the change: prunes to 1 granule (has-equivalent). Reference file matches byte-for-byte via clickhouse-local.
f Fix is general across code paths? Yes. = handled in traverseTreeEquals, IN/GLOBAL IN in traverseTreeIn, both via the shared getArrayJoinArgument. !=/NOT IN deliberately left as full scans (not derivable: a granule with the value can still yield arrayJoined rows outside the set).
g Fix generalizes across inputs? Element type conversion goes through BloomFilter::getPrimitiveType + convertFieldToType (same path as has), and returns false (safe full scan) when conversion is null. Works for the array element type; = '' is analyzer-rewritten to empty() and safely falls back to a full scan (documented + tested).
h Backward compatible? Yes. Pure query-planning optimization — only widens granule pruning for an existing predicate; no setting, format, or on-disk change. Original filter still applied after pruning, so results are unchanged.
i Invariants and contracts preserved? Yes. Pruning is a safe over-approximation: arrayJoin only multiplies rows, so a granule yields a matching row only if some element equals the constant — exactly the has bloom test. The original WHERE filter runs afterwards, so no rows are dropped or added.

Session id: cron:clickhouse-worker-slot-2:20260708-213900

@groeneai

groeneai commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 83a850f (superseded by master-merge 3f2c043)

Every failure below has an owner; none is PR-caused (our diff is MergeTreeIndexBloomFilter.cpp / RPNBuilder + the 04365 test, none of the failing areas).

Check / test Reason Owner / fixing PR
Unit tests (asan_ubsan / tsan / msan / amd_llvm_coverage) — ThreadPoolCallbackRunner.DroppedSynchronouslyWhileAttachedToAnotherGroup (+ AllTests) trunk (branch predated the revert) #109851 (merged) — merged master @ 3f2c043 to pick it up
Stateless tests (amd_tsan, s3 storage, parallel, 2/2) transient job-level ERROR (0 test failures in report) a fix task owns it (transient amd_tsan s3 wrapper ERROR, under investigation)
CH Inc sync - CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260709-033000

@groeneai

groeneai commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 3f2c043

Every failure below has an owner (a fixing PR). None is PR-caused (this PR's diff is MergeTreeIndexBloomFilter.cpp / RPNBuilder + the 04365 test; it touches neither KeyCondition/PREWHERE nor JoinStep planning). Both are chronic trunk fuzzer LOGICAL_ERRORs (debug/sanitizer aborts; handled exceptions in release) with 0 master hits, spread across many unrelated PRs.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug, targeted) / KeyCondition uses PREWHERE output (STID 4419-44a9) trunk logical error #109267 (ours, open)
Stress test (arm_msan) / Block structure mismatch in JoinStep duplicate column (STID 0993-386d) trunk logical error #109114 (ours, open)
Mergeable Check / PR rollup of the above owned via #109267 / #109114
CH Inc sync — CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260709-080000

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 24cdd05

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stress test (arm_msan) / STID 0993-3a3c — Block structure mismatch in joined block stream: different number of columns: __join_result_dummy UInt8 logical error, trunk — fuzzed 02564_analyzer_cross_to_inner query where both join children emit only __join_result_dummy #112205 (ours, open)
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 01666_merge_tree_max_query_limit flaky, trunk — under parallel replicas one statement becomes several reads of the same table on this server with different query ids, so the holder query competes against itself for the single max_concurrent_queries slot #112385 (ours, open)

Session id: cron:our-pr-ci-monitor:20260729-103000

@clickhouse-gh

clickhouse-gh Bot commented Aug 10, 2026

Copy link
Copy Markdown
Contributor

Dear @rschu1ze, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@rschu1ze

Copy link
Copy Markdown
Member

@yariks5s If that's in your area, would you like to check this PR?

@yariks5s

Copy link
Copy Markdown
Member

🕵 @groeneai please check

  1. [P3] The negative-condition no-pruning assertions are vacuous

    The NOT IN and != tests at 04365_bloom_filter_arrayJoin_in.sql:37 (https://github.com/ClickHouse/ClickHouse/blob/d304ce67873a56cf46086689f62ee478309263c2/tests/queries/0_stateless/04365_bloom_filter_arrayJoin_in.sql#L37-L44) search the entire EXPLAIN output for Granules: 13/13.
    
    The PrimaryKey section already contains that line, so both assertions succeed even if idx_tags appears later and incorrectly prunes granules. Assert that Name: idx_tags is absent, as the LEFT ARRAY JOIN test does, or scope the granule check specifically to the skip-index block.
    
  2. [P3] The integer-widening test uses the same type on both sides

    The compatibility gate has a distinct cross-integer arm at MergeTreeIndexBloomFilter.cpp:566
    (https://github.com/ClickHouse/ClickHouse/blob/d304ce67873a56cf46086689f62ee478309263c2/src/Storages/MergeTree/MergeTreeIndexBloomFilter.cpp#L566-L569), but the claimed widening test uses arrayJoin(u) = 5 where u is UInt8 at 04365_bloom_filter_arrayJoin_in.sql:183 (https://github.com/ClickHouse/ClickHouse/blob/d304ce67873a56cf46086689f62ee478309263c2/tests/queries/0_stateless/04365_bloom_filter_arrayJoin_in.sql#L183-L191). ClickHouse infers 5 as UInt8, so this exercises only the identical-type path.
    
    Use an explicitly wider constant such as toUInt64(5), and preferably a UInt64 subquery set as well, so both equality and IN exercise successful cross-integer pruning.
    
  3. [P3] The Enum test does not verify the pruning it claims

    The exact-type Enum8 case at 04365_bloom_filter_arrayJoin_in.sql:213 (https://github.com/ClickHouse/ClickHouse/blob/d304ce67873a56cf46086689f62ee478309263c2/tests/queries/0_stateless/04365_bloom_filter_arrayJoin_in.sql#L213-L230) contains one row and only compares results with use_skip_indexes enabled and disabled. It passes if idx_e is never selected, despite the comment saying the case “still prunes.”
    
    Add a nonmatching second granule and an EXPLAIN indexes = 1 assertion showing idx_e pruning to 1/2 granules.
    

@yariks5s

Copy link
Copy Markdown
Member

@groeneai also a things that can be shorter:

MergeTreeIndexBloomFilter.cpp:558-569: shrink: four locals to express two predicates. isFloat/isInteger free overloads for const DataTypePtr & already exist (IDataType.h:469,493,499) — drop both WhichDataType locals and both_integers:

auto value = removeLowCardinalityAndNullable(value_type);
auto element = removeLowCardinalityAndNullable(nested_type);
if (isFloat(value) || isFloat(element))
    return false;
return (isInteger(value) && isInteger(element)) || value->equals(*element);

MergeTreeIndexBloomFilter.cpp:714-736: shrink: four nesting levels, but the block is the last thing before return false; — invert to guards, kills 4 closing braces.

MergeTreeIndexBloomFilter.cpp:722, :951: shrink: index_type is a one-use local. Inline into the typeid_cast.

MergeTreeIndexBloomFilter.cpp:726: shrink: row_size used once. Inline column->size().

04365_bloom_filter_arrayJoin_in.sql:188-191: shrink: = 100000 and = -5 both assert "out-of-range constant declines, count 0 either way". One case covers it.

04365_bloom_filter_arrayJoin_in.sql:80-81: delete: the optimize_empty_string_comparisons = 1 pair tests the empty(s) rewrite, which this PR doesn't touch. The = 0 pair at 82-83 is the one that exercises the new equals derivation.

Considered and rejected:

  • Factoring the ~13-line duplicated preamble shared by :716-724 and :945-953 into a helper. Wrote both versions out: 48 lines becomes 48 lines. A wash, so the copy-paste stays — that's a correctness-review argument, not a length one.
  • Folding RPNBuilder.cpp:513-520 into toFunctionNodeOrNull(). Doesn't work: isFunction() requires DAG ActionType::FUNCTION, and ARRAY_JOIN is its own type (RPNBuilder.cpp:293), so the DAG half needs the explicit check anyway. The AST half alone comes out the same length.

Review round 2 on ClickHouse#109536 (@yariks5s). Three test assertions did not check what
they claimed, and the domain gate is expressed more directly.

The NOT IN and != safety assertions searched the whole EXPLAIN output for
"Granules: 13/13". The PrimaryKey section always emits that line, so they
succeeded whether or not idx_tags was selected and pruning. Measured on the PR
head: the skip-index block is absent from both plans, yet the same oracle also
returns 1 for a predicate that does prune 2/13. They now assert that
"Name: idx_tags" is absent, matching the LEFT ARRAY JOIN case in the same file.

The cross-integer arm of bloomFilterHashDomainMatches was covered by
arrayJoin(u) = 5 over an Array(UInt8) column. ClickHouse infers 5 as UInt8
(EXPLAIN QUERY TREE: constant_value_type UInt8), so it only exercised the
identical-type path. It now uses toUInt64(5) for both the equality and the IN
form.

The exact-type Enum8 case had a single row, so no granule could ever be pruned
and the case passed even when the index was never selected. It now has a
second, non-matching label and an EXPLAIN indexes = 1 assertion on 1/2.

Both new oracles were validated by mutation: with the cross-integer arm dropped
and Enum declined, the three new assertions redden while the ones they replace
stay green.

Also: express the gate with the isFloat/isInteger free overloads for
DataTypePtr, invert the traverseTreeIn arrayJoin block to early returns, inline
two single-use locals, drop the duplicate out-of-range constant case, drop the
optimize_empty_string_comparisons = 1 result pair, and shorten the test
comments to one or two lines.
@groeneai

Copy link
Copy Markdown
Collaborator Author

All three reproduce. Fixed in ea22ef2, with the shortening list applied.

1. Confirmed: neither plan contains a skip-index block, and the only Granules: 13/13 line is the PrimaryKey one. The same oracle also returns 1 for arrayJoin(tags) IN ('tag_42'), which prunes 2/13. Both now assert Name: idx_tags is absent; NOT IN and != do not go through the empty(s) rewrite, so this is analyzer-independent (checked both).

2. Confirmed: EXPLAIN QUERY TREE gives constant_value_type: UInt8 for = 5. Now toUInt64(5), plus a UInt64 subquery set for the IN form.

3. Confirmed: one row cannot prune. Second non-matching label added, with an EXPLAIN indexes = 1 assertion on 1/2.

2 and 3 are validated by mutation, not by passing: with the cross-integer arm removed and Enum declined, the new assertions go 1 -> 0 while the ones they replace stay green.

Shortening: all six adopted. isFloat/isInteger do have const DataTypePtr & overloads (IDataType.h:493,499), so the gate is your four lines.

On :80-81 - that pair was a live control, not dead weight: at the default = 1 the predicate becomes empty(arrayJoin(tags)), idx_tags leaves the plan, and the count stays 5000. The = 0 pair plus the index-on/off pair already cover it, so I dropped the redundant lines and kept the pin. Tell me if you want an explicit default-setting arm back.

Validation: Build ID 6c892c8eea5e123341aadacab048b9e821ac609c (server buildId asserted equal), all 13 pruning paths still fire, 50/50 randomized runs green, sweep over allow_experimental_analyzer=0, optimize_empty_string_comparisons 0/1, and both prewhere settings.

Separately, the second-model review flagged three declines as missed optimizations: nullIn under transform_null_in=1, an explicit ARRAY JOIN clause, and equals at the default optimize_empty_string_comparisons=1. All three reproduce identically on d304ce6 and give correct results index-on and index-off, so I did not widen scope here. Happy to take any of them as a follow-up.

@yariks5s
yariks5s added this pull request to the merge queue Aug 26, 2026
Merged via the queue into ClickHouse:master with commit ab19f74 Aug 26, 2026
178 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 26, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Aug 26, 2026
@robot-ch-test-poll robot-ch-test-poll added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Aug 26, 2026
yariks5s added a commit that referenced this pull request Aug 26, 2026
Backport #109536 to 26.8: Use bloom filter skip index for arrayJoin(col) IN (set) and arrayJoin(col) = const
yariks5s added a commit that referenced this pull request Aug 26, 2026
Backport #109536 to 26.6: Use bloom filter skip index for arrayJoin(col) IN (set) and arrayJoin(col) = const
yariks5s added a commit that referenced this pull request Aug 26, 2026
Backport #109536 to 26.7: Use bloom filter skip index for arrayJoin(col) IN (set) and arrayJoin(col) = const
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 28, 2026
…rrayJoin(col) IN (set) and arrayJoin(col) = const
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 28, 2026
…rrayJoin(col) IN (set) and arrayJoin(col) = const
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 28, 2026
…rrayJoin(col) IN (set) and arrayJoin(col) = const
subkanthi pushed a commit to subkanthi/ClickHouse that referenced this pull request Nov 10, 2026
…(set)

The bloom_filter index has used these forms since ClickHouse#109536, but the text index
reads every granule for them. The test checks the granule counts for =, IN,
GLOBAL IN and IN with transform_null_in = 1, the forms that must not use the
index, and the rows. It fails on master: the index checks print 0.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors groeneai-origin-unknown PR origin: unclassified (legacy task) pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-improvement Pull request with some product improvements pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.6-must-backport

Projects

None yet

8 participants