Skip to content

Use bloom_filter skip index for IN with transform_null_in=1 and NULL-free set - #111329

Merged
shankar-iyer merged 9 commits into
ClickHouse:masterfrom
groeneai:fix-bloom-filter-transform-null-in
Aug 25, 2026
Merged

shankar-iyer merged 9 commits into
ClickHouse:masterfrom
groeneai:fix-bloom-filter-transform-null-in

Conversation

@groeneai

@groeneai groeneai commented Jul 22, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Improvement

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

Use the bloom_filter skip index for IN predicates on a directly indexed column when transform_null_in = 1 and the IN-set contains no NULL value. Previously the index was skipped for such queries, forcing a full scan.

Description

Closes: #111311

With transform_null_in = 1 the analyzer rewrites x IN (...) to nullIn(x, ...) (and globalIn to globalNullIn). The bloom_filter skip index condition built the predicate hashes for these but never assigned an RPN function, so the atom stayed FUNCTION_UNKNOWN and the index was unused, forcing a full scan.

When the IN-set has no NULL, nullIn selects exactly the same rows as in, so the index can prune. The fix maps nullIn/globalNullIn to FUNCTION_IN when the set is single-column, NULL-free and type-compatible with the index, and the column is not an Array. With a NULL in the set, nullIn also matches NULL rows, so the atom is left FUNCTION_UNKNOWN (unchanged behavior). x = 'abc' already worked: transform_null_in does not rewrite equals.

Scope: scalar left-hand side on a directly indexed column, which is the scope of the issue. Tuple lhs, JSONAllPaths and map subcolumns still recognize only in/globalIn and continue to full-scan.

Those are deliberately not extended, because the checks this fix relies on cannot be evaluated there: the recursive tuple(...) branch matches each element against its own index and is called with prepared_set = nullptr, and Set::hasNull() returns false whenever data_types.size() != 1, so reusing the single-column guard on a tuple set is vacuous rather than merely wider. Measured with that extension applied, a 180-query parity sweep against use_skip_indexes = 0 returned fewer rows than the truth arm for 17 queries; the sweep is clean on this PR. A test arm pins the contract, so extending the tuple branch on the single-column guard fails the test.

Verified with EXPLAIN indexes = 1 that the index prunes for String, Nullable, LowCardinality and LowCardinality(Nullable) with a NULL-free set, and does not prune for a set containing NULL, an Array column, a type-incompatible set or a tuple lhs. Results match use_skip_indexes = 0 in each case.


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

Version info

  • Merged into: 26.9.1.65 (included in 26.9 and later)
  • Backported to: 26.8.1.2003, 26.7.6.15, 26.6.4.22, 26.5.8.21

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. EXPLAIN indexes=1 on x IN (...) flips deterministically with transform_null_in: 250/250 granules (index unused) before, 14/250 after. No randomness.
b Root cause explained? Yes. transform_null_in=1 rewrites in->nullIn (resolveFunction.cpp). functionIsInOrGlobalInOperator already accepts nullIn, so traverseTreeIn builds the hashes but only set FUNCTION_IN for in/globalIn; nullIn stayed FUNCTION_UNKNOWN -> alwaysUnknownOrTrue() true -> index unused.
c Fix matches root cause? Yes. Assigns FUNCTION_IN for nullIn/globalNullIn at that exact site, gated by !prepared_set->hasNull(). Not a band-aid.
d Test intent preserved / new tests added? New test 04545 added: asserts the optimization FIRES (EXPLAIN indexes=1 subquery-filter form) AND results are correct, across the type matrix and both NULL-free / NULL-containing sets. No existing test weakened.
e Both directions demonstrated? Yes. Without fix: test FAILS (nullIn "prunes" rows 1->0). With fix: 50/50 randomized PASS. Build-ID verified for each binary.
f Fix is general across code paths? Scoped to the plain single-column scalar IN (the issue). notNullIn/globalNotNullIn intentionally untouched (FUNCTION_NOT_IN never prunes here, and NOT semantics differ). Map-element / JSON-subcolumn IN paths left FUNCTION_UNKNOWN under nullIn (unchanged; separate follow-up).
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Tested String, Nullable, LowCardinality, LowCardinality(Nullable): all prune for a NULL-free set and return correct results. Set containing NULL: not pruned + correct rows (incl. NULLs). Array columns explicitly excluded (whole-array equality hashing is unsound for granules mixing empty/non-empty arrays; regression test added).
h Backward compatible? Yes. Pure optimization enablement. No setting default / format / validation change. transform_null_in=0 unchanged; transform_null_in=1 results unchanged (only fewer granules read). No SettingsChangesHistory entry needed.
i Invariants and contracts preserved? Yes. Bloom filter is false-positive-only (never false-negative); FUNCTION_IN evaluation is any_of over set-element hashes, correct for a NULL-free set exactly as for in. Safety invariant "only prune when the set has no NULL" enforced by Set::hasNull(). No concurrency/lifetime/data-structure contract touched.

Session id: cron:clickhouse-author-slot-0:20260722-064300

@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review — adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 2 findings; bounded: 1 full pass + 1 fix round + 1 delta recheck).

# Sev Finding Verdict Evidence / action
1 ❌ New nullIn classification could incorrectly prune matching rows for Array bloom-filter columns AGREE — fixed Reproduced: Array(UInt32) col, x IN ([]) with transform_null_in=1 returned 0 with the skip index vs correct 1 without (Granules 0/2). The same mis-prune pre-exists in the in path (transform_null_in=0 also 0/2) — a pre-existing array-equality hashing limitation my change newly exposed. Excluded Array-typed index columns from the new classification (!typeid_cast<const DataTypeArray*>); re-verified x IN ([]) no longer prunes and returns 1; added an Array regression case.
2 ❌ NULL-free nullIn remains unoptimized for the Map-element and JSON-subcolumn IN paths DISAGREE Targets the Map (FUNCTION_IN at the map branch) and JSON (FUNCTION_EQUALS/IN at the JSON branch) assignments — both unchanged hunks in this diff (the change is confined to the single-column direct-header branch), so auto-dropped by the delta protocol. Substantively scoped out: this issue is specifically the plain x IN (...) case; Map/JSON are distinct sub-features with their own default-value/key-absence NULL semantics (one-concern-per-PR). The Array blocker just showed a plausible sibling extension can hide a real regression, so extending to Map/JSON needs per-path NULL-semantics verification — tracked as a focused follow-up, not bundled here.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding. Findings on hunks unchanged by the fix round are auto-dropped.

Session id: cron:clickhouse-author-slot-0:20260722-064300

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @al13n321 @CurtizJ — could you review this? With transform_null_in=1 the analyzer rewrites IN to nullIn, and the bloom_filter skip index condition never classified nullIn/globalNullIn as FUNCTION_IN, so the index was silently dropped and the query full-scanned. This maps them to FUNCTION_IN when the set has no NULL (Set::hasNull()), excluding Array columns where whole-array equality hashing is unsound.

@clickhouse-gh

clickhouse-gh Bot commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [79a7a40]

Summary: ✅


AI Review

Summary

This PR teaches MergeTreeIndexBloomFilter to reuse FUNCTION_IN for nullIn / globalNullIn only on the direct-column, single-column, NULL-free, non-Array, same-underlying-type cases that are actually safe, and the new stateless test file covers both the intended pruning paths and the known unsound exclusions. I re-read the current diff, the surrounding MergeTreeIndexBloomFilter and Set code, and every existing review thread on the PR; on the current head I did not find a remaining correctness, safety, or coverage issue worth reopening or blocking on.

Missing context / blind spots
  • ⚠️ I did not run 04545_bloom_filter_index_transform_null_in locally in this workspace because there is no build_* directory in the checkout, so the review relied on code inspection plus the added regression coverage and the PR discussion history.
Final Verdict

✅ No new findings on the current head.

LLVM Coverage Report

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

Changed lines: Changed C/C++ lines covered: 12/13 (92.31%) · Uncovered code

Full report · Diff report

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

Copy link
Copy Markdown
Collaborator Author

Fixed the Fast test regression on 01681_bloom_filter_nullable_column introduced by the first commit (65c5fe9).

Root cause. NUMBER_OF_COLUMNS_DOESNT_MATCH is a per-row runtime check inside the IN executor, downstream of skip-index analysis (confirmed: with use_skip_indexes=0 both transform_null_in=0 and =1 throw it). When the bloom filter prunes all granules, no rows execute and the error is never reached. The in/transform_null_in=0 path has always pruned the malformed multi-column query str IN (SELECT '1048576', str ...) to empty (the test's .reference documents that). My nullIn -> FUNCTION_IN mapping made transform_null_in=1 do the same, so the query returned empty instead of raising the error the test asserts.

Fix (commit 6cabd5a). Restrict the nullIn/globalNullIn mapping to single-column sets (getDataTypes().size() == 1). This matches the issue #111311 scope exactly (x IN ('a','b','c')), keeps Set::hasNull() reliable (it only reports NULL content for single-column sets), and keeps the multi-column-vs-single-index-column mismatch raising the error at execution. No existing test is weakened; 01681's { serverError NUMBER_OF_COLUMNS_DOESNT_MATCH } assertions are preserved.

Second commit (f3ebce6) adds a type-compatibility guard areTypesEqual(0, index_type) to the same mapping. With transform_null_in=1 the set casts the key strictly (not accurate_or_null), so a type-incompatible single-column set, e.g. a String index against IN (SELECT toUInt8(1)), throws CANNOT_PARSE_TEXT at execution; without the guard the index pruned that granule and swallowed the error. areTypesEqual compares modulo Nullable/LowCardinality, so the Nullable/LowCardinality/LowCardinality(Nullable) cases still prune. Regression case added to 04545.

Verified both directions on debug builds: 01681 fails before / passes after; 04545 (including the new type-mismatch case) passes; the Nullable/LowCardinality/LC(Nullable) matrix still uses the index; the set-with-NULL case still does not prune and returns the NULL rows.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (Gate B, delta) — 1 finding, adjudicated (click to expand)

Scoped delta review of the CI-fix commits (base 65c5fe9), engine codex.

id severity verdict resolution
nullin-type-guard blocker AGREE Verified real: String bloom index vs IN (SELECT toUInt8(1)) under transform_null_in=1 threw CANNOT_PARSE_TEXT with the index off but returned empty with it on (the strict set cast used only when transform_null_in=1; the in/transform_null_in=0 path uses accurate_or_null and never had this). Fixed in f3ebce6 by adding areTypesEqual(0, index_type) (compares modulo Nullable/LowCardinality). Re-verified both directions; wrapper matrix still prunes; regression case added to 04545.

…free set

With transform_null_in=1 the analyzer rewrites `x IN (...)` to `nullIn(x, ...)`
(and `globalIn` to `globalNullIn`). The bloom_filter index condition built the
predicate hashes for these forms but never assigned an RPN function, leaving the
atom FUNCTION_UNKNOWN so the index was not used and the query did a full scan.

When the IN-set has no NULL element, nullIn selects exactly the same rows as in,
so the index can prune. Map nullIn/globalNullIn to FUNCTION_IN for a directly
indexed column when the set is single-column, NULL-free (Set::hasNull()), and
type-compatible with the index (Set::areTypesEqual, modulo Nullable/
LowCardinality). When the set contains a NULL, nullIn also matches NULL rows, so
the atom is left FUNCTION_UNKNOWN (no pruning).

Guards:
- Array columns are excluded: whole-array equality hashing is not sound for
  granules that mix empty and non-empty arrays (a pre-existing limitation shared
  by the `in` path), so nullIn must not start pruning them.
- Only single-column sets: Set::hasNull() reports NULL content only for
  single-column sets, and a multi-column set against a single index column must
  keep raising NUMBER_OF_COLUMNS_DOESNT_MATCH rather than being pruned away.
- Type must match: with transform_null_in=1 the set casts the key strictly (not
  accurate_or_null), so a type-incompatible set (e.g. a String index against
  IN (SELECT toUInt8(1))) throws at execution; pruning would swallow that error.

The JSONAllPaths and map-subcolumn IN fast paths still recognize only in/globalIn,
so they continue to full-scan under transform_null_in=1 (out of scope for this
issue; extending them needs per-path NULL-semantics checks). `x = 'abc'` was
already handled: transform_null_in does not rewrite `equals`.

Closes: ClickHouse#111311

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai
groeneai force-pushed the fix-bloom-filter-transform-null-in branch from e2b2e4d to 4050d17 Compare July 22, 2026 15:46
@groeneai

Copy link
Copy Markdown
Collaborator Author

Force-pushed a strengthened version (squashed to one commit). The nullIn pruning is now gated to a directly indexed column with a set that is single-column, NULL-free, type-compatible with the index (Set::areTypesEqual, modulo Nullable/LowCardinality), and non-Array. Added regression cases for the Array and type-mismatch guards, and the "prunes" assertions now check actual granule reduction (read < total), not merely that the index was analyzed. JSON/map-subcolumn IN paths are left out of scope (they still full-scan under transform_null_in=1; extending them needs per-path NULL-semantics checks).

@clickhouse-gh

clickhouse-gh Bot commented Jul 22, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 48.00% 86.20% +38.20%
Functions 60.60% 92.00% +31.40%
Branches 36.90% 78.20% +41.30%

Changed lines: Changed C/C++ lines covered: 11/13 (84.62%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 4050d17

Every failure below is owned by a fixing PR or a full-effort fix task. None is caused by this PR (the change gates the bloom_filter skip index for direct-column IN under transform_null_in=1; it cannot cause the coverage-suite stateless flakies, an integration check-table failure, or a stress-build failure). The earlier Fast test 01681_bloom_filter_nullable_column regression was PR-caused and has been fixed in this PR; Fast test is green on this commit.

Check / test Reason Owner
Integration (amd_asan_ubsan, db disk, old analyzer, 5/6) / test_check_table::test_check_all_tables flaky (60 PRs/30d) a fix task is in pending (full-effort)
Stateless (amd_llvm_coverage, old analyzer, s3, DBReplicated, WasmEdge, 2/3) / Logical error incorrect data types (STID 2735-47bf) trunk fuzzer-class (24 PRs) a fix task is in pending (full-effort)
Stateless (amd_llvm_coverage, old analyzer, ...) / 03915_exchange_tables_race flaky (83 PRs/9 master) a fix task owns it (full-effort)
Stateless (amd_llvm_coverage, ...) / 03595_parallel_replicas_join_remote, 02311_system_zookeeper_insert, 01338_uuid_without_separator, 01600_quota_by_forwarded_ip, 03202_sz3_codec, 04055_rand_distribution_parameter_limits, 04291_91525_iceberg_position_deletes_multi_file flaky coverage-suite cluster (each 2-6 unrelated PRs/14d) a fix task is in pending (full-effort, coverage-suite flaky cluster)
Stress test (amd_tsan) / Test script failed flaky stress (chronic) a fix task owns it (full-effort)
Sync — CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260723-010000

@shankar-iyer shankar-iyer self-assigned this Jul 23, 2026
@rschu1ze

Copy link
Copy Markdown
Member

Please also double check for the text index.

@groeneai

Copy link
Copy Markdown
Collaborator Author

I checked. The text index has the same gap, and so do the two legacy text bloom filters. set, minmax and the primary key do not.

Measured on a debug build of master, Granules: read/total from EXPLAIN indexes = 1 for x IN ('word5', 'word500') over 1000 rows with index_granularity = 4:

index transform_null_in=0 transform_null_in=1
text 2/250 250/250, Skip section absent
tokenbf_v1 prunes no pruning
ngrambf_v1 prunes no pruning
set prunes prunes
minmax prunes prunes
primary key prunes prunes

Result rows are identical in every case, so this is lost pruning only, not wrong results.

Sites:

  • text: MergeTreeIndexConditionText.cpp:644 gates on function_name == "in" || function_name == "globalIn", so nullIn/globalNullIn never reach tryPrepareSetForTextSearch and the atom stays unknown.
  • tokenbf_v1/ngrambf_v1: MergeTreeIndexBloomFilterText.cpp:384 gates on functionIsInOrGlobalInOperator, which does include nullIn, but the body at :388-397 only assigns an RPN function for notIn and in. The set is prepared and then discarded.
  • set/minmax/primary key are unaffected because they build a KeyCondition, which already maps nullIn to FUNCTION_IN_SET at KeyCondition.cpp:479-486.

One soundness finding, since the text path is not structurally safe the way I first expected. tryPrepareSetForTextSearch does not reject a set containing NULL: on a Nullable(String) column, x IN ('word5', NULL) still prunes to 2/250 with transform_null_in=0. That is correct for in, where a NULL element cannot match anything, but it means adding the two function names at :644 on their own would prune away the NULL rows nullIn has to return. On a table with 10 NULLs that predicate returns 1 row with transform_null_in=0 and 11 with transform_null_in=1, so the rows at stake are real. The text and tokenbf_v1/ngrambf_v1 fixes therefore need the same null-free set guard this PR applies to bloom_filter, not just the extra names.

I would prefer to do those in a follow-up PR rather than here: three separate condition classes, and the text one has its own tokenizer and pre/postprocessor semantics that need their own test matrix. Tell me if you would rather have it all in this PR and I will fold it in.

@groeneai

Copy link
Copy Markdown
Collaborator Author

The follow-up is open: #112785

It covers the three text-family conditions I measured above, plus sparse_grams, which I had missed: it shares the same condition class as tokenbf_v1 and ngrambf_v1, so one hunk fixes all three. text is the second hunk.

Two things worth flagging, both in the description there. The extra function names alone would give wrong results, because at transform_null_in = 1 a Nullable key keeps the wrapper on its set elements even for a NULL-free set, so each site refuses per row at the tokenized position instead. And globalIn never pruned on the token bloom filter family even at transform_null_in = 0; the same branch fixes that, so unlike this PR the follow-up is not confined to transform_null_in = 1.

@shankar-iyer

Copy link
Copy Markdown
Member

@groeneai Code changes are good. Please condense your comments to 1 line or so in MergeTreeIndexBloomFilter.cpp

Keep only the local invariant at each site; the reasoning behind the guards is
in the parent commit message.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Done in c16a360: the guard now carries one two-line comment, and the JSON and map notes are one line each. The reasoning behind each guard condition lives in the commit message of 4050d17, so nothing was lost.

The type check in the nullIn mapping was documented as preventing a swallowed
conversion error. That reason is wrong: the CANNOT_PARSE_TEXT error fires whether
or not the index prunes, so the existing error-code assertion passes even with the
check removed and does not pin it.

The real reason is that the two casts involved are not inverse. Index analysis
hashes the set value cast to the index type (toUInt8(1) -> String '1'), while
execution casts each column value to the set type ('01' -> UInt8 1, which matches).
A granule holding '01' therefore stores hash('01') while the index searches for
hash('1'), so pruning it silently drops a matching row.

Add an arm whose values all parse cleanly, so nothing throws, and where '01' and
'+1' are lossy under the round trip. It asserts result parity against
use_skip_indexes = 0 and the exact row count. Removing the type check turns both
assertions red, which the previous error-code assertion did not do. Also correct
the misleading comment above the existing case.

Test only, no behavior change.

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 79a7a40c4 with master 4399d6c6a (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 708.92 MiB 705.88 MiB -3.04 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.

Compile time of recompiled translation units

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

Job report

groeneai and others added 2 commits August 10, 2026 10:14
globalNullIn is classified separately from nullIn in traverseTreeIn, but every
positive pruning assertion used a local IN, so dropping globalNullIn from the
classifier left the whole test green while GLOBAL IN silently stopped pruning
(11/250 granules read, then 250/250).

Assert reduced granules and the exact row count for GLOBAL IN as well.

Test only, no behavior change.

Co-Authored-By: Claude Fable 5 <[email protected]>
The pruning assertions filtered EXPLAIN rows with

    explain LIKE '%Granules: %/%' AND toUInt64(extract(...)) < toUInt64(extract(...))

which assumes the LIKE is evaluated before the conversions. With
enable_analyzer = 0 that ordering does not hold, so the conversions also run
on rows that carry no "Granules: N/M" text. There extract returns an empty
string and toUInt64('') throws ATTEMPT_TO_READ_AFTER_EOF, which failed the
test 3 out of 3 reruns in the old-analyzer job and aborted the file at its
first assertion, leaving the remaining arms unexercised in that
configuration.

Use toUInt64OrZero so the conversions are total. All nine assertions are
affected, not only the first, so all nine are changed.

The assertion is unchanged in strength: it still requires read < total
granules. Rows without a granule line compare 0 < 0, which is false, so they
do not contribute, and the negative arms produce no granule line at all and
still yield 0. Verified by re-running the file under enable_analyzer 1 and 0
and by three mutations of the classifier, each of which still reddens the
test: dropping the nullIn wiring, dropping the areTypesEqual guard, and
dropping globalNullIn.
@shankar-iyer

Copy link
Copy Markdown
Member

@groeneai Refresh to master

@groeneai

Copy link
Copy Markdown
Collaborator Author

@shankar-iyer Refreshed: merged master (4faa046) in, head is now 79a7a40. Clean merge, and the diff against master is still exactly the 3 files / +233 lines you approved -- I checked the added hunks are byte-identical to the pre-merge ones, so nothing was re-authored.

Master had touched MergeTreeIndexBloomFilter.cpp since my base (+126 lines), so I rebuilt and re-ran 04545_bloom_filter_index_transform_null_in: it passes with both enable_analyzer=1 and enable_analyzer=0, and the pruning assertions are still live on the merged tree (disabling the new guard locally flips 12 of them from 1 to 0).

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 79a7a40

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 (amd_msan) / Logical error 'Equal values are not contiguous within the range assumed to be sorted' (STID 2508-3319) pre-existing trunk defect, surfaced by the server-side AST fuzzer mutating another test's fixture #115839 (ours, open)

Not caused by this PR. The aborting query is
SELECT count() FROM (SELECT s FROM merge_distinct__fuzz_4 ORDER BY s DESC LIMIT 1 BY s LIMIT 100)
under log_comment = '04870_distinct_merge_over_distributed.sql-...'. The stress profile's
ast_fuzzer_runs = 5 / ast_fuzzer_any_query = true retypes that test's Merge parent into a
__fuzz_4 clone whose column type differs from its child's, which breaks the sort order its
LIMIT 1 BY arm assumes. This PR's diff is MergeTreeIndexBloomFilter.cpp plus its own test, and
that test contains no LIMIT BY and no DISTINCT, so it cannot reach the aborting code path.

Session id: cron:our-pr-ci-monitor:20260824-140000

@shankar-iyer

Copy link
Copy Markdown
Member

Let me try 1 rerun to get a green CI.

@shankar-iyer
shankar-iyer added this pull request to the merge queue Aug 25, 2026
Merged via the queue into ClickHouse:master with commit 773aa57 Aug 25, 2026
351 of 352 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 25, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Aug 25, 2026
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Aug 25, 2026
clickhouse-gh Bot added a commit that referenced this pull request Aug 25, 2026
Backport #111329 to 26.8: Use bloom_filter skip index for IN with transform_null_in=1 and NULL-free set
rschu1ze added a commit that referenced this pull request Aug 25, 2026
Backport #111329 to 26.7: Use bloom_filter skip index for IN with transform_null_in=1 and NULL-free set
rschu1ze added a commit that referenced this pull request Aug 25, 2026
Backport #111329 to 26.6: Use bloom_filter skip index for IN with transform_null_in=1 and NULL-free set
rschu1ze added a commit that referenced this pull request Aug 25, 2026
Backport #111329 to 26.5: Use bloom_filter skip index for IN with transform_null_in=1 and NULL-free set
@clickgapai

Copy link
Copy Markdown
Contributor

@groeneai @shankar-iyer — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Confirmed, with two corrections.

The bug is real and reproduces at default settings. On master 887b93e1, compared against use_skip_indexes = 0, x IN ([]) returns 0 instead of 1 and x IN ([], [2]) returns 1 instead of 2. It also reaches a subquery set, Array(String), Array(LowCardinality(String)), and a tuple IN with an array component. It is not new: the official 25.8.33.6 and 26.3.23.7 builds return the same wrong counts.

The provenance reading is right, so it is pre-existing rather than introduced here. This PR's entire net change to that file is the nullIn/globalNullIn block plus two comments; the in/globalIn mapping at MergeTreeIndexBloomFilter.cpp:569-570 is untouched by it, and had no guard before it either.

The blanket Array bail-out proposed in the issue is broader than the defect. The unsound condition is that the set contains an empty array, because a non-empty set array always contributes at least one element hash. Over 200k rows in 24 granules, x IN ([999999999, 999999998]) still prunes to Granules: 0/24, and across 40 random fixtures a set with no empty array matched the unindexed answer 40 times out of 40. Bailing out for every Array index throws that away.

Withholding only the FUNCTION_IN assignment is also not sufficient. traverseTreeIn accumulates every tuple component into one RPNElement, so when one index covers both components, the array component still appends its predicate and a scalar sibling then sets FUNCTION_IN:

CREATE TABLE t (x Array(UInt32), y UInt32,
  INDEX idx_xy (x, y) TYPE bloom_filter GRANULARITY 1)
ENGINE = MergeTree ORDER BY tuple() SETTINGS index_granularity = 2;
INSERT INTO t VALUES ([], 1), ([1], 2), ([2], 3), ([3], 4);
SELECT count() FROM t WHERE (x, y) IN (([], 1), ([2], 3)); -- 1, expected 2

One index per column hides this, because the array index then never sees the sibling.

The map subcolumn branch is unaffected structurally, not merely untriggered: an Array-valued map cannot carry that index at all, since Map(String, Array(UInt32)) with a mapValues bloom_filter index is rejected at DDL with Code: 36 ... Unexpected type Array(Array(UInt32)) of bloom filter index.

Fix: #116449. Leaving #116431 open for that PR to close on merge.

kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 28, 2026
…N with transform_null_in=1 and NULL-free set
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 28, 2026
…N with transform_null_in=1 and NULL-free set
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 28, 2026
…N with transform_null_in=1 and NULL-free set
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 28, 2026
…N with transform_null_in=1 and NULL-free set
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.4-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Use BloomFilter skip index if transform_null_in=1 and predicate does not include a NULL value

8 participants