Skip to content

Add experimental cuckoo_filter and binary_fuse_filter skip indexes - #101796

Open
zex-hyd wants to merge 73 commits into
ClickHouse:masterfrom
zex-hyd:feature/cuckoo-filter-skip-index
Open

zex-hyd wants to merge 73 commits into
ClickHouse:masterfrom
zex-hyd:feature/cuckoo-filter-skip-index

Conversation

@zex-hyd

@zex-hyd zex-hyd commented Apr 4, 2026 •

Copy link
Copy Markdown

Changelog category (leave one):

  • Experimental Feature

Related Issue:

#101795 (Cuckoo Filter)
#104466 (Binary Fuse Filter)

Changelog entry:

Added experimental cuckoo_filter and binary_fuse_filter skip index types for MergeTree tables. Both are gated by experimental settings and documented as workload-dependent alternatives to bloom_filter, with stateless size-benchmark coverage; the binary-fuse CI benchmark also includes a tiny pruning sanity check.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Summary

This PR implements and benchmarks two experimental probabilistic filter structures for MergeTree skip indexes: cuckoo_filter and binary_fuse_filter.

Both structures are based on published research on compact approximate membership filters for large static sets. Benchmark results in the stateless tests show that they are not general replacements for bloom_filter in ClickHouse's current skip-index model. In particular, at skip-index GRANULARITY = 1 and a common target FPR such as 0.025, both filters are often larger than bloom_filter because of fixed structural overhead on small per-index-granule key sets.

The feature remains experimental and gated. bloom_filter remains the recommended default skip index unless workload-specific benchmarks show an advantage for one of these filters.

Implemented Index Types

1. cuckoo_filter

Based on Fan et al., "Cuckoo Filter: Practically Better Than Bloom" (ACM CoNEXT 2014), with secondary-index motivation from Kipf et al., "Cuckoo Index" (PVLDB 2020).

Parameters: Single argument — target false positive rate, for example 0.01.

Experimental setting: Requires allow_experimental_cuckoo_filter_index = 1.

2. binary_fuse_filter

Based on Graf & Lemire, "Binary Fuse Filters: Fast and Smaller Than Xor Filters" (arXiv:2201.01174, 2022).

Parameters: Single argument — target false positive rate, for example 0.025.

Experimental setting: Requires allow_experimental_binary_fuse_filter_index = 1.

Benchmark Results

Both filters were evaluated against bloom_filter in 04104_cuckoo_filter_benchmark.sql and 04204_binary_fuse_filter_benchmark.sql.

Methodology: 10,000 rows per table, table index_granularity = 8192, skip-index GRANULARITY = 1, OPTIMIZE FINAL, then sum(secondary_indices_uncompressed_bytes) from system.parts. Each file covers 18 core scenarios: 6 cardinality regimes × 3 FPR values. 04204 adds representative CI-friendly extensions (lower FPR snapshot, skip-index GRANULARITY sensitivity, distribution-sensitive cases, and a tiny pruning sanity check).

Cuckoo Filter vs Bloom

At skip-index GRANULARITY = 1 and fpr = 0.025, cuckoo_filter was larger than bloom_filter in all six tested cardinality regimes (04104 reference).

Scenario FPR Bloom Cuckoo Ratio
single value 0.025 2 B 15 B 7.5x
1% distinct 0.025 101 B 139 B 1.4x
10% distinct 0.025 1,002 B 2,061 B 2.1x
50% distinct 0.025 5,002 B 8,205 B 1.6x
90% distinct 0.025 9,002 B 16,397 B 1.8x
all distinct 0.025 10,002 B 16,397 B 1.6x

Observed range at fpr = 0.025: 1.4x–7.5x larger than Bloom.

At the lower fpr = 0.001 (where the requested FPR is rounded up to the nearest supported fingerprint width), cuckoo_filter remains larger than bloom_filter in every tested cardinality regime as well (04104 reference):

Scenario FPR Bloom Cuckoo Ratio
1% distinct 0.001 189 B 267 B 1.4x
10% distinct 0.001 1,877 B 4,109 B 2.2x
50% distinct 0.001 9,377 B 16,397 B 1.7x
90% distinct 0.001 16,877 B 32,781 B 1.9x
all distinct 0.001 18,752 B 32,781 B 1.7x

Binary Fuse Filter vs Bloom

At skip-index GRANULARITY = 1 and fpr = 0.025, binary_fuse_filter was also larger than bloom_filter in all six core cardinality regimes (04204 reference).

Scenario FPR Bloom Binary Fuse Ratio
single value 0.025 2 B 12 B 6.0x
1% distinct 0.025 101 B 187 B 1.9x
10% distinct 0.025 1,002 B 1,396 B 1.4x
50% distinct 0.025 5,002 B 6,293 B 1.3x
90% distinct 0.025 9,002 B 11,029 B 1.2x
all distinct 0.025 10,002 B 12,309 B 1.2x

Observed range at fpr = 0.025: 1.2x–6.0x larger than Bloom.

However, binary_fuse_filter can be smaller in specific FPR regimes where its fingerprint width is favorable. For example, at fpr = 0.001:

Scenario FPR Bloom Binary Fuse Ratio
1% distinct 0.001 189 B 187 B 0.99x
10% distinct 0.001 1,877 B 1,396 B 0.74x
50% distinct 0.001 9,377 B 6,293 B 0.67x
90% distinct 0.001 16,877 B 11,029 B 0.65x
all distinct 0.001 18,752 B 12,309 B 0.66x

Additional representative CI-friendly coverage in 04204_binary_fuse_filter_benchmark.sql: lower-FPR snapshot (fpr = 0.005), skip-index GRANULARITY = 1 / 8 / 64, distribution-sensitive scenarios, and a tiny hit/miss pruning sanity check. 04104 covers the full 18-scenario size matrix for cuckoo but does not include those extensions.

Root Cause Analysis

The common issue is structural overhead in small-set regimes:

  • cuckoo_filter: per-index-granule bucket count rounds up to a power of two; fixed overhead from slot structure, load-factor requirements, and fingerprint-width choices cannot amortize well for small distinct-key counts.
  • binary_fuse_filter: whole-byte fingerprints and power-of-two segment alignment introduce step changes in size. This can be favorable in some FPR regimes, but unfavorable at common settings such as fpr = 0.025.

Both structures are designed for larger static sets where structural overhead is easier to amortize. ClickHouse skip indexes often operate on much smaller per-index-granule key sets, so the benefit is workload- and parameter-dependent.

Why keep this experimental implementation?

Although the MergeTree skip-index results are workload-dependent, these implementations provide reusable probabilistic filter structures that may be useful beyond the current skip-index model, for example for runtime filters or future index layouts with larger key sets.

The user-facing skip-index integrations remain experimental and gated, and the documentation describes the measured limitations instead of presenting these filters as general bloom_filter replacements.

Test Files

  • 04077_cuckoo_filter_skip_index.sql — focused cuckoo predicate coverage vs bloom_filter: scalar equality/!=/NOT IN, scalar IN (including a forced miss set), hasAny/hasAll, tuple expression indexes, and map key paths; EXPLAIN sanity for scalar equality
  • 04299_binary_fuse_filter_skip_index.sql — same focused predicate coverage for binary_fuse_filter
  • 04319_experimental_skip_index_json_isnotnull_nested.sql — JSON path-presence correctness: bare isNotNull(json.path) uses the index; nested forms such as isNotNull(json.path) = 0 do not
  • 04078_cuckoo_filter_skip_index_bad_args.sql — cuckoo bad-argument validation, experimental-setting gates, and unchanged-index ALTER behavior
  • 04205_binary_fuse_filter_bad_args.sql — same for binary_fuse_filter
  • 04104_cuckoo_filter_benchmark.sql — full 18-scenario Cuckoo vs Bloom size benchmark (04104 reference)
  • 04204_binary_fuse_filter_benchmark.sql — 18 core scenarios plus representative CI-friendly extensions for Binary Fuse vs Bloom
  • 04103_cuckoo_filter_vs_bloom_filter_equivalence.sql — PREWHERE scalar-equality count equivalence vs bloom_filter
  • 04203_binary_fuse_filter_vs_bloom_filter_equivalence.sql — same for binary_fuse_filter

Both benchmark files use the same core methodology: same schema/data pattern, OPTIMIZE FINAL, then reading secondary_indices_uncompressed_bytes from system.parts.

Predicates Covered

The implemented index-condition paths follow existing bloom_filter skip-index semantics where applicable, while unsafe or unsupported forms fall back conservatively to avoid false negatives.

Covered paths exercised by the stateless tests include:

  • scalar equality (=)
  • scalar IN (including a forced miss set in 04077 / 04299)
  • array predicates hasAny and hasAll
  • tuple expression indexes (x = … AND y = … on a tuple index)
  • map key access paths (m['key'] = … with a mapKeys(m) index)
  • bare JSON path-presence checks such as isNotNull(json.path) (04319)

Not claimed as index-backed in tests:

  • nested boolean forms such as isNotNull(json.path) = 0
  • negation / inversion paths such as !=, NOT IN — compared against bloom_filter for result parity, but not forced through the skip index

More complex boolean forms should fall back to normal scanning rather than being forced through the skip index.

Example Usage

SET allow_experimental_cuckoo_filter_index = 1;
SET allow_experimental_binary_fuse_filter_index = 1;

CREATE TABLE t
(
    k UInt64,
    INDEX idx_cuckoo k TYPE cuckoo_filter(0.01) GRANULARITY 1,
    INDEX idx_bfuse k TYPE binary_fuse_filter(0.025) GRANULARITY 1
)
ENGINE = MergeTree
ORDER BY k;

<!-- CI automatic block start :ci_links: -->

---
Workflow [[PR](https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=101796&sha=latest&name_0=PR)]
Sync PR [[sync-upstream/pr/101796](https://github.com/search?q=head%3Async-upstream%2Fpr%2F101796+org%3AClickHouse+type%3Apr&type=pullrequests)]
<!-- CI automatic block end :ci_links: -->

@zex-hyd

zex-hyd commented Apr 4, 2026

Copy link
Copy Markdown
Author

Hi @alexey-milovidov @rschu1ze,

This PR is related to my feature request #101795 (from Intern Tasks 2025/2026).

Would appreciate feedback on the approach! Happy to adjust based on your suggestions.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Apr 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented Apr 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [eb724f5]

Summary: ❌

job_name test_name status info comment
Style check FAIL
settings_changes_history FAIL cidb
Fast test FAIL
05871_experimental_skip_index_expression_identity FAIL cidb
Build (arm_tidy, 1/4) FAIL
Build ClickHouse FAIL cidb
Build (arm_tidy, 2/4) FAIL
Build ClickHouse FAIL cidb
Build (arm_tidy, 3/4) FAIL
Build ClickHouse FAIL cidb
Build (arm_tidy, 4/4) FAIL
Build ClickHouse FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL
Code Review DROPPED
Build (amd_asan_ubsan) DROPPED
Build (arm_asan_ubsan) DROPPED

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Apr 5, 2026
@zex-hyd
zex-hyd marked this pull request as draft April 5, 2026 17:09
Comment thread src/Interpreters/CuckooFilter.cpp Resolved
Comment thread src/Interpreters/CuckooFilter.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member

The Stress test (arm_msan) failure is fixed by #101239, which should be merged first. After it is merged, please update the branch to include the fix.

Comment thread src/Interpreters/CuckooFilter.cpp Resolved
@zex-hyd
zex-hyd force-pushed the feature/cuckoo-filter-skip-index branch from 79e4994 to a513b9c Compare April 8, 2026 22:51
@zex-hyd
zex-hyd marked this pull request as ready for review April 8, 2026 22:51
@zex-hyd

zex-hyd commented Apr 9, 2026 •

Copy link
Copy Markdown
Author

The Stress test (arm_msan) failure is fixed by #101239, which should be merged first. After it is merged, please update the branch to include the fix.

@alexey-milovidov The stress test is failing again, I have verified that this PR is up to date with master!

So it looks like a separate MSan issue (or flake) uncovered by stress, unrelated to the cuckoo_filter changes on our side!

@alexey-milovidov

Copy link
Copy Markdown
Member

The MSan stress test failure (MemorySanitizer: use-of-uninitialized-value, STID 4179-5154 or 4148-3044) is a known pre-existing issue unrelated to this PR. Fix: #102158

@zex-hyd

zex-hyd commented Apr 9, 2026 •

Copy link
Copy Markdown
Author

The MSan stress test failure (MemorySanitizer: use-of-uninitialized-value, STID 4179-5154 or 4148-3044) is a known pre-existing issue unrelated to this PR. Fix: #102158

@alexey-milovidov Thanks again for the clarafication! This PR is also ready for review!

@alexey-milovidov

Copy link
Copy Markdown
Member

The Hung check failure is fixed by #102008 and #102010, let's update the branch

@zex-hyd

zex-hyd commented Apr 10, 2026

Copy link
Copy Markdown
Author

The Hung check failure is fixed by #102008 and #102010, let's update the branch

Thanks for the help! I also make some fix on the comments with previous typo.

Comment thread src/Core/Settings.cpp Resolved
@zex-hyd

zex-hyd commented Apr 18, 2026

Copy link
Copy Markdown
Author

@alexey-milovidov @rschu1ze This PR has passed all the checks and is ready to be review! Please feel free to add comments on the PR! Thank you!

@rschu1ze

rschu1ze commented Apr 20, 2026 •

Copy link
Copy Markdown
Member

@zex-hyd We must only introduce new index types to ClickHouse if they are strictly better than the current ones in terms of performance and storage space. Please evaluate the Cuckoo filter indexes vs. Bloom filter indexes (ideally as systematically as possible) along these dimensions, you can use functional tests (tests/queries/0_stateless), SQL performance tests (tests/performance) or C++ Google Benchmark tests for this.

@zex-hyd

zex-hyd commented May 1, 2026

Copy link
Copy Markdown
Author

Hi @alexey-milovidov @rschu1ze! Could you add the pr-performance label to this PR?

Without the pr-performance label we don’t get the amd performance report / all-query-metrics.tsv. We need that to compare our new cuckoo_filter_.xml runs against the existing bloom_filter_.xml and to document the time + secondary index size follow-up to the earlier review!

@zex-hyd

zex-hyd commented May 2, 2026

Copy link
Copy Markdown
Author

@zex-hyd We must only introduce new index types to ClickHouse if they are strictly better than the current ones in terms of performance and storage space. Please evaluate the Cuckoo filter indexes vs. Bloom filter indexes (ideally as systematically as possible) along these dimensions, you can use functional tests (tests/queries/0_stateless), SQL performance tests (tests/performance) or C++ Google Benchmark tests for this.

@alexey-milovidov @rschu1ze Could you add the pr-performance label to this PR? Without the pr-performance label we don’t get the amd performance report / all-query-metrics.tsv.

@rschu1ze rschu1ze added the pr-performance Pull request with some performance improvements label May 3, 2026
alexey-milovidov and others added 4 commits October 11, 2026 06:57
…er-skip-index

Conflict in the skip-index function support table: master added rows for
`multiSearchAnyCaseInsensitive` and `multiSearchAnyCaseInsensitiveUTF8`;
kept the PR's `cuckoo_filter` / `binary_fuse_filter` columns (unsupported for both).
…ilter`

`cuckoo_filter` and `binary_fuse_filter` now decline the index for a set
containing NULL over a non-nullable key (instead of throwing from
`castColumn`), and fold `equals` against an unknown enum name to
`ALWAYS_FALSE` when `validate_enum_literals_in_operators = 0` (instead of
throwing `UNKNOWN_ELEMENT_OF_ENUM`), like `bloom_filter` and `KeyCondition`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…mental filters

Unlike `bloom_filter`, `cuckoo_filter` and `binary_fuse_filter` are not used
through lossless type conversions of the key or for `arrayJoin` conditions.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`04077_cuckoo_filter_skip_index` ran over 180 s in the debug flaky check
(~33 s on average there). Move the `Map`, `Array`, `Tuple` and default-argument
cases into separate tests, and do the same for the `binary_fuse_filter` twin.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=101796&sha=f70aea3da881fe111d47bc7a1a958348df326ccc&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20flaky%20check%29
PR: ClickHouse#101796

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 2 commits October 19, 2026 20:24
…er-skip-index

Conflict in `tests/performance/scripts/perf.py`: master reworked the setup,
teardown and reference-failure handling and added the `do_not_check_in_pr`
opt-out for setup queries that fail on the reference server. Take master's
`perf.py` and drop the PR's `new_server_only` mechanism; the four
`cuckoo_filter` / `binary_fuse_filter` performance tests now mark their
`CREATE TABLE` with `do_not_check_in_pr="101796"` and pass the experimental
setting in the `CREATE` `SETTINGS` clause instead of `<settings>` (which would
fail on the reference server that does not know the setting).
…the experimental filters

`cuckoo_filter` and `binary_fuse_filter` now match current `bloom_filter`:

- convert the map key constant strictly to the key type of the map, and
  decline the predicate when it is not representable, so the index cannot
  hide `UNKNOWN_ELEMENT_OF_ENUM` from `arrayElement`;
- compare a `String` / `FixedString` constant with `Enum` elements by the
  name of the enum value (`tryConvertEnumNameConstant`), in `has`, `indexOf`,
  `hasAny`, `hasAll` and the map functions, instead of throwing while the
  index is prepared;
- over `Enum` map values, account for the zero of the underlying integer
  that `arrayElement` returns for a missing key, in both the `IN` and the
  `equals` branches, and hash the converted enum value;
- `0.0` and `-0.0` are equal but `BloomFilterHash` hashes them apart: probe
  the hash of the other zero as well, otherwise a granule was pruned for a
  predicate on the other zero.

The new test fails on the previous code with wrong results for `-0.0`,
`UNKNOWN_ELEMENT_OF_ENUM` and `BAD_GET`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=101796&sha=c31809925cce70e794157b9262f7db55b82bb0c6&name_0=PR&name_1=Upgrade%20check%20%28amd_release%29 (Logical error: Part all_1_2_3 intersects previous part all_1_1_3, seen in the upgrade check of many unrelated PRs since 2026-10-11) and https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=101796&sha=c31809925cce70e794157b9262f7db55b82bb0c6&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20ParallelReplicas%2C%20s3%20storage%2C%20parallel%29 (05210_lightweight_update_materialized_cte_in_ignore, UNKNOWN_TABLE for _materialized_cte_c_* with parallel replicas, also failing in many PRs), and provide a fix in a separate PR. If the fix is already in progress, link it here.

@groeneai

Copy link
Copy Markdown
Collaborator

Both are already fixed on master, so no new PR is needed.

Upgrade check (amd_release): the stress phase ran the previous release, v26.9.15.5. There, TRUNCATE TABLE t (01443_merge_truncate_long.sh) hit an injected MEMORY_LIMIT_EXCEEDED in MetadataOperationsHolder::commit under StorageMergeTree::renameAndCommitEmptyParts, and the rollback left its empty part all_1_1_3 on disk. 40 ms later a merge of all_1_1_2 and all_2_2_0 wrote all_1_2_3, and the upgraded server aborts while loading test_1.t. This is the rolled-back empty part leak that #122375 fixes (merged 2026-10-09). The check upgrades from the newest older release, so it keeps failing in PRs until that release has the fix: v26.9.22.3 (released today) and the 26.9 branch still lack it, the 26.10 branch has it. It stops with the first 26.10 release, or earlier with a 26.9 backport of #122375.

05210_lightweight_update_materialized_cte_in_ignore: fixed by #123121 (mine, merged 2026-10-13, closes #112642). This run tested the merge commit 7b81038b from 2026-10-11, which predates it. In all 30 PRs where the test failed after that merge, the tested tree did not contain it. It has failed twice since 2026-10-15, the last time on 2026-10-18, both times on a merge commit that lacked the fix (692 and 1652 commits behind it).

alexey-milovidov and others added 2 commits October 27, 2026 06:23
# Conflicts:
#	src/Interpreters/InterpreterCreateQuery.cpp
#	src/Storages/MergeTree/registerStorageMergeTree.cpp
The `settings_changes_history` style check requires new settings to carry a
record for the current version after `master` moved to `26.11`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master (9a348d8c) and pushed 330c505f..bcdf6cfe. That merge brings in #122375 and #123121, which @groeneai pointed to above as the fixes for the upgrade-check and 05210 failures.

  • Conflicts: in registerStorageMergeTree.cpp, master moved the getIndexFromAST call below the reserved implicit-minmax-name check. The cuckoo_filter / binary_fuse_filter experimental gates now sit on that call. In InterpreterCreateQuery.cpp the conflict was only in the extern settings list.
  • Fixed the settings_changes_history style failure: both gating settings now have a 26.11 record instead of the 26.10 one.
  • Local build passes. 04077, 04078, 04299 and 05411 match their references.

`04104_cuckoo_filter_benchmark` and `04204_binary_fuse_filter_benchmark` failed
in Fast test because `secondary_indices_compressed_bytes` of the `bloom_filter`
tables differed by a few bytes from the reference (e.g. 28 vs 27). Compressed
sizes depend on the compression codec and library in the environment, so they
are not a stable thing to pin. The size comparisons in these tests are based
on `secondary_indices_uncompressed_bytes`, which stay deterministic; drop the
`*_compressed` output lines.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=101796&sha=bcdf6cfe408af6aaa8ccebe413dff345bad5daf4&name_0=PR&name_1=Fast%20test
ClickHouse#101796

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Fast test failed on 04104_cuckoo_filter_benchmark and 04204_binary_fuse_filter_benchmark: the bloom_compressed values were a few bytes off the reference (for example 28 vs 27). Compressed sizes depend on the codec and compression library in the test environment, so they shouldn't be pinned. I removed the *_compressed output lines from both tests (c53a101f). The size comparisons already use secondary_indices_uncompressed_bytes, which matched the reference. Pushed bcdf6cfe..c53a101f.

@maxknv maxknv added the external Author is not a member of the ClickHouse organization label Nov 2, 2026
alexey-milovidov and others added 5 commits November 5, 2026 07:10
# Conflicts:
#	src/Storages/AlterCommands.cpp
…umn shadowing check

Master replaced the per-condition `NameSet` of columns shadowing Map key subcolumns
with an `IsShadowingColumn` callback returned by `getMapSubcolumnShadowingCheck`
(a3d7b0c). Mirror the change made to `bloom_filter` in both experimental
index conditions so the branch builds after merging master.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… type in experimental skip indexes

In `cuckoo_filter` and `binary_fuse_filter`, the `arrayElement(map, key) = value` path hashed
the raw constant for a `mapValues` index and checked only the default of the constant's own
type to decide whether a missing key could satisfy the predicate:

* over `Map(String, FixedString(2))`, `m['k'] = 'a'` hashed `a` instead of the stored `a\0`,
  so the matching granule was pruned (the reverse, a `FixedString` constant against `String`
  values, was unsafe as well);
* over `Map(String, UInt64)` with a keys-only index, `m['missing'] = '0'` is true for a row
  without the key, but `'0'` is not the `String` default, so the row could be skipped.

Convert the constant the way `equals` does to the type of the map values, with the same
zero-padding guards as the scalar equality path, decline the index when the converted value
is the default of the map values (unless they are `Nullable`), and hash the converted value
for a `mapValues` index.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ent `mapContains*` support

The gating settings now live in the `26.11` history, so both index types declare
`.introduced_in = {26, 11}`. The function support table in the registered `MergeTree`
documentation marked `mapContains`/`mapContainsKey` and `mapContainsValue` as unsupported for
`bloom_filter`, `cuckoo_filter` and `binary_fuse_filter`, although all three condition builders
use them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 The previous CI run on ef123583 was cancelled in the middle of the build (The operation was canceled in Fast test and the arm_tidy builds), so it reported no real failures. I merged master (4088c421) without conflicts and pushed ef123583..5f0d9a77 to get a fresh run. Locally, after the merge, the release build succeeds and all 18 stateless tests of this PR pass.

alexey-milovidov and others added 2 commits November 14, 2026 17:58
…omain of the index

`Set::execute` casts the key column to the type of the set, while `cuckoo_filter` and
`binary_fuse_filter` cast the set to the key type and hash the result. This only agrees when the
conversion from the key type to the set type is injective: a `String` key holding `'01'` matches the
`UInt64` set element `1`, but the index looked up the hash of `'1'` and pruned the granule. A set of
`Array(Nullable(UInt64))` holding `[NULL]` could not even be cast to an `Array(UInt64)` key and threw.

Accept a set only when its type equals the key type up to a top-level `Nullable` or `LowCardinality`,
or when both are integers. The same check applies to `m['k'] IN (subquery)` over `mapValues(m)`.

Also add a correctness test for the persisted 16-bit fingerprints (`false_positive_rate = 0.0001`)
of both index types, with enough distinct values per granule for `binary_fuse_filter` to build a fuse
filter rather than an exact list.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
{
auto key_column_name = key_node.getColumnName();

if (header.has(key_column_name))

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.

[Blocker] Verify expression identity before matching an index by name

header.has(key_column_name) also succeeds when the index contains an unrelated physical column whose literal name looks like the query expression. For example, with the experimental setting enabled:

CREATE TABLE t_expr
(
    s String,
    `lower(s)` String,
    INDEX idx `lower(s)` TYPE binary_fuse_filter GRANULARITY 1
)
ENGINE = MergeTree ORDER BY tuple();
INSERT INTO t_expr VALUES ('ABC', 'x');
SELECT count() FROM t_expr WHERE lower(s) = 'abc';

The predicate matches the row, but this branch hashes 'abc' against the index of the physical value 'x', so the single-hash filter rejects its granule. The same name-only match occurs in traverseTreeIn, and the map/JSON special cases likewise infer expressions from header names. Both experimental implementations are affected.

Please carry the index expression nodes into both conditions and verify structural identity, as the current bloom_filter does with ExpressionMatcher, findIndexPosition, and its specialized map/JSON matching. Adapt the focused cases in 05620_bloom_filter_index_map_keys_column_name.sql for both filters; fixing only this equality branch leaves the other entrypoints unsound.

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.

🕵 Addressed in eb724f5 for both binary_fuse_filter and cuckoo_filter. Both conditions now carry the outputs of the index expression and match structurally: findIndexPosition in traverseTreeEquals and traverseTreeIn, findMapIndexPosition for mapContains* / has over a map and for the m[key] / m.key_<k> paths, and collectJSONIndexColumns for the JSON matchers. These three helpers are shared with bloom_filter (declared in MergeTreeIndexBloomFilter.h) rather than copied. The test adapts the cases of 05620_bloom_filter_index_map_keys_column_name.sql for both filters.

Not run locally: the build machine was too loaded to link a binary in this pass, so only the changed translation units were compiled against merged master. The new test 05871_experimental_skip_index_expression_identity is verified by CI on eb724f5; leaving this thread open until it passes.

/// Try to match the column name to a JSONAllPaths index for JSON subcolumn filtering.
/// tryMatchNodeToJSONIndex handles both plain subcolumns and CAST-wrapped expressions
/// like `json.some.path = value`, `json.some.path.:Type = value`, or `json.path::Type = value`.
if (auto json_info = tryMatchNodeToJSONIndex(key_node, header, "JSONAllPaths", json_argument_types))

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.

[Blocker] Preserve the JSON subcolumn shadowing check

All three calls to tryMatchNodeToJSONIndex omit the shadowing callback, so a real column or regular subcolumn named like a JSON path is treated as a path inside the indexed JSON column. For example:

SET allow_experimental_binary_fuse_filter_index = 1;
CREATE TABLE t_json_shadow
(
    j JSON,
    `j.a` Nullable(String),
    INDEX idx JSONAllPaths(j) TYPE binary_fuse_filter GRANULARITY 1
)
ENGINE = MergeTree ORDER BY tuple();
INSERT INTO t_json_shadow VALUES ('{"b":1}', 'v');
SELECT count() FROM t_json_shadow WHERE `j.a` = 'v';

The query reads the physical column and should return 1. The index instead probes path 'a' in JSONAllPaths(j), which contains only 'b', and rejects the matching granule. IN and bare isNotNull have the same problem, as does the copied cuckoo_filter condition.

Please pass getJSONSubcolumnShadowingCheck into both conditions and every JSON matcher, as MergeTreeIndexBloomFilter::createIndexCondition already does. Add coverage for a physical dotted column and a regular tuple subcolumn (the existing 05620_bloom_filter_index_map_keys_column_name.sql has both). This is separate from validating the identity of the index expression: here the index really is JSONAllPaths(j), but the query reads a different object.

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.

🕵 Addressed in eb724f5: both indexes pass getJSONSubcolumnShadowingCheck into the condition, and all three tryMatchNodeToJSONIndex calls (equals, IN, bare isNotNull) receive it. The test covers a physical dotted column j.a and a regular tuple subcolumn j.t.c next to a JSON column j, for both filters.

Not run locally: the build machine was too loaded to link a binary in this pass, so only the changed translation units were compiled against merged master. The new test 05871_experimental_skip_index_expression_identity is verified by CI on eb724f5; leaving this thread open until it passes.

if (!prepared_set)
return false;

auto default_column_to_check = type->createColumnConstWithDefaultValue(1)->convertToFullColumnIfConst();

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.

[Blocker] Test the map lookup's default in its actual result type

Here type is the prepared set's type, which can differ from the result type of m[key]. Its default therefore does not establish whether a missing map key can satisfy IN. For example:

SET allow_experimental_binary_fuse_filter_index = 1;
SET optimize_functions_to_subcolumns = 0;
CREATE TABLE t_map_default
(
    m Map(String, UInt64),
    INDEX idx mapKeys(m) TYPE binary_fuse_filter GRANULARITY 1
)
ENGINE = MergeTree ORDER BY tuple();
INSERT INTO t_map_default VALUES (map('present', 1));
SELECT count() FROM t_map_default WHERE m['missing'] IN (SELECT '0');

The lookup returns UInt64(0) and Set::execute casts it to the set's String type, yielding '0', so the row matches. This check instead tests String(''), permits the key-presence predicate, and the index rejects the granule because 'missing' is absent. The new hash-compatibility guard only runs in the values-index branch and does not protect this keys-index path. Both experimental conditions have this bug.

Construct the default probe from the actual lookup result type and let prepared_set->execute perform the runtime conversion, following the nearby JSON branch, while retaining the separate enum-zero check. Add a keys-only regression for both filters against use_skip_indexes = 0.

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.

🕵 Addressed in eb724f5 for both filters: the default probe is built from the result type of the lookup (key_node.getDAGNode()->result_type) and prepared_set->execute does the conversion, as in the JSON branch; the separate enum-zero check is kept. The test has the keys-only regression against use_skip_indexes = 0, with optimize_functions_to_subcolumns both 0 and 1.

Note that bloom_filter on master has the same defect: your reproduction with TYPE bloom_filter returns 0 instead of 1 on a recent master binary, since MergeTreeIndexConditionBloomFilter::traverseTreeIn also probes with the default of the set type. That is outside this PR and needs a separate fix.

Not run locally: the build machine was too loaded to link a binary in this pass, so only the changed translation units were compiled against merged master. The new test 05871_experimental_skip_index_expression_identity is verified by CI on eb724f5; leaving this thread open until it passes.

alexey-milovidov and others added 3 commits November 23, 2026 16:45
… name

The conditions of `cuckoo_filter` and `binary_fuse_filter` looked the index column up by the name
of the query expression, so an index on a column literally named `lower(s)`, `mapKeys(m)` or
`JSONAllPaths(j)` was probed for the expression of the same name and could reject a matching granule.

- Carry the outputs of the index expression into both conditions and verify structural identity with
  `findIndexPosition`, `findMapIndexPosition` and `collectJSONIndexColumns`, which are now shared
  with `bloom_filter` instead of being private to `MergeTreeIndexBloomFilter.cpp`.
- Pass `getJSONSubcolumnShadowingCheck` to every `tryMatchNodeToJSONIndex` call, so that a column or
  a subcolumn named like a path of the indexed `JSON` column is not taken for that path.
- For `m[key] IN (set)`, probe the set with the default of the result type of the lookup rather than
  the default of the set type: `m['missing'] IN (SELECT '0')` over `Map(String, UInt64)` matches.

Co-Authored-By: Claude Fable 5.2 <[email protected]>

This branch has not been deployed

No deployments
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 comp-skip-index Skipping indexes (minmax, set, bloom) and their evaluation. external Author is not a member of the ClickHouse organization manual approve Manual approve required to run CI pr-experimental Experimental Feature pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants