Skip to content

Use a dense bitset instead of a Bloom filter for JOIN runtime filters on 8 and 16 bit integer keys - #129186

Merged
cv4g merged 16 commits into
ClickHouse:masterfrom
groeneai:dense-bitset-runtime-filter-129092
Nov 18, 2026
Merged

cv4g merged 16 commits into
ClickHouse:masterfrom
groeneai:dense-bitset-runtime-filter-129092

Conversation

@groeneai

@groeneai groeneai commented Nov 4, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #129092
Related: #96779

Changelog category (leave one):

  • Performance Improvement

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

JOIN runtime filters on Int8, UInt8, Int16 and UInt16 keys use an exact bitset over all values of the key type instead of a Bloom filter when there are too many keys for the exact set. This removes hashing and false positives from the probe.

Description

When the exact set of a JOIN runtime filter overflows join_runtime_filter_exact_values_limit and the key is Int8, UInt8, Int16 or UInt16, the filter now switches to one bit per value of the key type (32 bytes or 8 KiB) instead of a Bloom filter. A probe is one load per row and passes only build keys, and the filter needs no size setting. Other key types, NOT IN filters and partial filters sent between plan stages are unchanged. An 8 bit key has at most 256 values, so it reaches the bitset only when that limit is below 256. 32 and 64 bit keys are left for a follow-up.

With a single 8 or 16 bit key, join_runtime_filter_from_fixed_hash_table (on by default) replaces this filter with the join's FixedHashMap after the build, so there the bitset only replaces the Bloom filter that was built before. The bitset is the filter that runs for such keys in joins on several keys, and when that setting is off.

Measured locally (release, no LTO, 64 pinned cores, 7 paired runs, fix/master): 100M probe rows joined on a UInt16 and a UInt8 key with 12000 or 30000 build keys 0.42 / 0.46 at 8 threads and 0.49 / 0.50 at 32 threads; the same join on the UInt16 key alone, where the FixedHashMap filter takes over, 1.00 / 0.98. The UInt16 query added to join_runtime_filter.xml about 0.55. No TPC-H or TPC-DS key is (U)Int8 or (U)Int16, so those benchmarks are unchanged.

A gtest compares the filter with the build keys for every value of each of the four types, and 05497 checks the new RuntimeFilterDenseBitsetsBuilt event for a 16 and an 8 bit key.


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

Version info

  • Merged into: 26.11.1.2674-master (included in 26.11 and later)

groeneai and others added 9 commits November 3, 2026 21:18
… a narrow range

This applies the patch in ClickHouse#129092 as posted: when the exact set of a JOIN
runtime filter overflows `join_runtime_filter_exact_values_limit` and the
key is a native integer, the build keys go to a bitset over [min, max]
instead of a Bloom filter, as long as the range fits the allowance. The
bitset is exact and costs one load per probe row.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Changes on top of the patch from ClickHouse#129092:

- The allowance of the bitset is raised only by the distinct-key count of
  the hash table statistics, not by the build rows inserted so far. Rows
  count duplicate keys, so a build of 20M rows with 100K distinct keys over
  a wide range could get a 33 MB bitset where a 512 KiB Bloom filter has a
  low false positive rate.
- Keys leave a bitset in batches of `DEFAULT_BLOCK_SIZE` instead of one
  column of all keys, and the size and predicted saturation of the Bloom
  filter are decided before any key is read. A bitset of 8 MiB can hold
  67M keys, 536 MB as `UInt64`.
- Before moving its keys to a Bloom filter, a bitset counts its distinct
  keys exactly and drops the key set if they alone would saturate the
  filter, so a first execution does not hash keys into a filter that is
  then discarded.
- The pass-all branches of `DenseBitsetRuntimeFilter::find` and the
  conversion in `serialize` are unreachable and now throw `LOGICAL_ERROR`.
  A transported partial never builds a bitset, also when it merges one.
- The new test gets a free number and pins the block size of the query that
  checks the bitset is built before the far keys arrive. One serialization
  gtest spreads its keys wider than the bitset covers, to keep testing the
  local Bloom filter path.
- Descriptions of `join_runtime_filter_exact_values_limit`,
  `join_runtime_bloom_filter_bytes` and `RuntimeFilterBloomFilterBuildsSkipped`
  mention the bitset.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
200000 integer keys over a range of 60 million values: a dense bitset
on the patched binary, a Bloom filter on master.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`bugprone-use-after-move` rejects `emplace` on a moved-from variant, and the
variant cannot be move-assigned (`DenseBitsetRuntimeFilter` has a const
member). The keys are now read into a local Bloom filter, which is then
moved into the variant: the same batches and the same peak memory.

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

`ApproximateRuntimeFilterQueriesBloomFilter` used keys {1, 3}, {5}, which now fit a
dense bitset, so the test named for the Bloom lookup checked the bitset. Its first
overflowing insert is now wider than the bitset allowance, and the test asserts that
no bitset was built.

`RuntimeFilterDenseBitsetsBuilt` counts the switch to a bitset, before any later move
to a Bloom filter, and every result row of 05497 is filter-independent, so the test
could not fail if the bitset fell back. The new `dense stays` query uses a 1 KiB Bloom
filter, which these keys would saturate, and checks that rows are still filtered:
`RuntimeFilterRowsChecked > 0` and no predicted-saturated build was skipped. Master
drops the saturated Bloom filter (RowsChecked 0); a bitset that falls back after its
first block also fails it.

`wide small allowance` runs on one stream with 8192-row blocks: with 32 streams and
small granules, one stream's short run of keys overflows the 64 KiB exact-bytes limit
inside the 1 MiB allowance and briefly becomes a bitset, which flipped the row that
expects none.

The class comment of `DenseBitsetRuntimeFilter` states the per-stream bound as the
bytes of the keys the stream received.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…53 Q3 on the Bloom filter

`DenseBitsetMergesPartialFiltersInAnyRepresentation` never merged two bitsets: with a 1 KiB geometry
the wide part needed more words than the allowance and became a Bloom filter, the empty part became an
empty Bloom filter, and every source was finished before the merge, so no source carried pending keys.
It now uses a 64 KiB geometry with a 1e-6 saturation bound (a Bloom filter would be dropped and pass
every row), four parts that become bitsets (two with sparse keys left pending, two dense ones at
different words), and merges the sources both unfinished, as `RuntimeFilterLookup::add` does, and
finished. It asserts the bitset count, the exact mask and the row counters in every merge order.

03753 Q3, the Bloom filter case, had keys {5, 6, 7} that now fit one bitset word. One far key keeps the
range wider than a bitset covers, and the check also requires `RuntimeFilterDenseBitsetsBuilt = 0`.
The reference is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The pair arm of 05077 and the whole of 05289 guard that statistics of distinct
(a, b) pairs never skip the per-column filter on `a`. Their `a` keys were in a
narrow range, so the runtime filter became a dense bitset and the check in
switchToApproximateFilter was never reached. Spread `a` by 1e6 (counts are
unchanged) and check that no dense bitset is built for those queries. The 05077
check matches only the pair queries: the `k` queries may build transient
per-stream bitsets before the predicted-saturated Bloom filter is skipped.

Also fix the key count in the 03753 Q3 heading.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Add the gtest DenseBitsetAllowanceGrowsOnlyWithStatisticsOfTheFilterKey. It pins
the three parts of AdaptiveSetRuntimeFilter::denseBitsetMaxBytes that no test
reached: distinct keys of the hash table statistics raise the allowance above
16 x join_runtime_bloom_filter_bytes (keys up to 1e6 become a bitset with a
1 KiB Bloom filter size), statistics of another key do not raise it (the
ClickHouse#122167 class of pair statistics), and the allowance never exceeds 32 MiB.
Removing any one of the three fails only its own arm.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Shorten the DenseBitsetRuntimeFilter comments to their invariants and drop the motivation and narration of the new code.

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

This comment was marked as resolved.

@groeneai

This comment was marked as resolved.

@groeneai

This comment was marked as resolved.

@clickhouse-gh

clickhouse-gh Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0edd19b]

Summary: ✅


AI Review

Summary

Reviewed #129186 at 0edd19b5e3181d9fd2e3fece61e75841f186c3a4, including all prior discussion. Overflowing local JOIN runtime filters on Int8, UInt8, Int16, and UInt16 keys now use exact bitsets; transported partials retain the existing format. No actionable findings remain. The earlier serialization-test lifetime issue is fixed. Exhaustive lookup coverage, the transport regression test, the current-head stateless test, and the supplied paired performance measurements support approval.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements can be tested Allows running workflows for external contributors comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... labels Nov 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 0edd19b5e with master e8cb3beb9 (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

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

12 object files changed (+37.68 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/QueryPlan/RuntimeFilterLookup.cpp.o 761.96 KiB 794.90 KiB +32.94 KiB (+4.32%)

711 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.79 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 6.8 s 14.6 s +9.3 s (+174%)
Compile time of recompiled translation units

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

Job report

…de the lookup lock

With unordered build keys every per-stream dense bitset partial keeps its keys as values
(fewer bytes than the bits of its range), and `RuntimeFilterLookup::add` merged each of
them into the registered filter under the lookup mutex, so the bits of all streams were
set serially on one thread. Such a partial now waits for the next one; the two are merged
outside the lock and the registered filter takes their union in one merge. At most one
partial per key waits, and a partial waits only while more expected partials remain, so
none is left behind. `DenseBitsetRuntimeFilter::mergeFrom` sets the source keys straight
into the bits when the merged keys become bits, instead of copying them first.

Release build, 64 cores pinned, 20M unordered keys over 60M values, two runs of 7 pairs,
`max_threads_min_free_memory_per_thread = 0`: time vs the previous head 0.447 / 0.358 at
32 / 64 threads (vs master 0.699 / 0.752, the previous head was 1.56 / 2.10); MergeTree
random-order build side at 64 threads 0.367; 4 / 16 threads, sorted build side, 200K keys,
Bloom-only shapes and TPC-H q21 / q04 / q22 at 32 / 64 threads unchanged within noise;
peak memory unchanged.

Patch by snelheidai (ClickHouse#129092 (comment)).

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

This comment was marked as resolved.

@groeneai

This comment was marked as resolved.

@cv4g cv4g self-assigned this Nov 5, 2026
The bitset words were a `std::vector`, which `operator new` counts but never refuses
(`min_allocation_size_to_throw_on_memory_limit` is 0 by default), so up to 32 MiB of bits
went over the memory limit where the Bloom filter they replace is refused. They are now a
`VectorWithMemoryTracking`, like `BloomFilter::Container`.

`BuildRuntimeFilterTransform` is an `ISimpleTransform`: after `insert` throws it passes the
exception downstream, keeps inserting the next blocks into the same filter and publishes it
in `finish`. A refused append to the pending keys left `pending_keys` null, so the next
insert dereferenced it and the server crashed (reproduced with
`memory_tracker_fault_probability`, at run 2 and run 13 of the posted query). The column is
now put back by a scope guard in `insert` and `mergeFrom`. A refused switch away from a full
exact set left the set full, so the next block threw `LOGICAL_ERROR` "Unexpected state of
AdaptiveSetRuntimeFilter"; the full set still holds every key, so the switch is retried.

Four gtests, one per change: each fails with its own change reverted and passes with any
other one reverted; the first three also fail on the previous head. The posted
fault-injection query: 1200 runs, no crash, no `LOGICAL_ERROR`, every successful count
correct. Release build, 64 cores pinned, two runs of 7 pairs (15 more for TPC-H): the
synthetic shapes and TPC-H q21 / q04 / q22 at 32 / 64 threads are unchanged in time and peak
memory within noise.

Patch by snelheidai (ClickHouse#129092 (comment)),
plus the test of the `mergeFrom` guard.

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

This comment was marked as resolved.

@groeneai

This comment was marked as resolved.

opensource-fork-sync Bot pushed a commit to cla7aye15I4nd/opensource-ClickHouse__ClickHouse that referenced this pull request Nov 7, 2026
…ing DROP DATABASE

`DROP DATABASE` and `DETACH DATABASE` build a local dependency graph from the
union of each table's loading and referential dependencies (ClickHouse#114952). The two
global graphs can disagree on the UUID of the same name: the referential node
of a view gets its UUID from `ALTER`, and it survives `DROP TABLE` + `CREATE TABLE`
of that name while a dictionary still depends on it. A dictionary reading that
name then has the dependencies `[db.x, db.x (stale uuid)]`. In the local graph
the first entry resolves to the node of the real table, and the second one
takes the name-conflict branch of `addOrUpdateNode`, which removes that node.
The vector overload of `addDependencies` had already stored its raw pointer,
and then inserted into the freed node's `dependents`.

Keep every node collected by `addDependencies` alive until the end of the
call, replace `table_node` by the node that took its name (the rule the
single-dependency overload already uses since ClickHouse#126292), and drop the removed
nodes from the new dependency set: each of them gave its name to the node of a
later dependency, which is in the set. When no node is removed, the resulting
graph is the same as before.

Found by La Casa Del Dolor (arm_asan_ubsan), STID 4010-5179, on PR ClickHouse#129186.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Core/Settings.cpp Resolved
As asked in review, keep the first step simple: only (U)Int8 and (U)Int16
keys switch from the exact set to a bitset, which then covers every value of
the key type (32 bytes or 8 KiB). That removes the size allowance and its
statistics heuristic, the key range tracking and the keys kept as values,
the merging of partials in pairs outside the lookup lock, and the memory
limit handling of the large bitset. 32 and 64 bit keys keep the Bloom filter
and are left for a follow-up.

The tests 03753, 04357, 05077 and 05289 and the serialization gtest use 32
and 64 bit keys again as on master, and 05497 becomes a minimal check of
RuntimeFilterDenseBitsetsBuilt. The narrow-range Int32 query of the
performance test is replaced by a join on a UInt16 and an Int32 key, where
the bitset is the filter that runs: with a single 8 or 16 bit key the join's
FixedHashMap replaces the runtime filter after the build.

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

@rschu1ze rschu1ze left a comment

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.

@cv4g This PR lgtm, wdyt?

@rschu1ze

Copy link
Copy Markdown
Member
image

`switchToDenseBitset` now holds the four lines that build the bitset
from the exact set, so `switchFromExactFilter` only picks the target
representation.

A UInt8 key has at most 256 values, so it leaves the exact set only
when `join_runtime_filter_exact_values_limit` is below 256. Both new
cases lower it: 05497 checks that the switch builds a bitset for UInt8
keys, and the performance test gets a UInt8 pair next to the UInt16 one.

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

cv4g commented Nov 17, 2026

Copy link
Copy Markdown
Contributor

@cv4g This PR lgtm, wdyt?

Same. Looks very good to me now. The scope that is implemented now is much better than before.

When expanding it to larger integer types we should rethink the modeling of pending_keys (which was representing the non-merged intermediate state) as it increased the code complexity quite a bit.

During review I also noticed the intermediate column built in DenseBitsetRuntimeFilter::getValuesColumn() but as far as I can see that replaced a forEachValue-like member function as a simplification under the guarantee that UInt8, UInt16 only have a small value range and it does not occur often.

Comment thread src/Common/ProfileEvents.cpp Resolved
@snelheidai

Copy link
Copy Markdown

On whether to keep RuntimeFilterDenseBitsetsBuilt, from the source at bd5f26e:

  • A plain EXPLAIN cannot show it: the bitset is chosen during execution, when the build side's exact set overflows join_runtime_filter_exact_values_limit.
  • EXPLAIN ANALYZE has per-step reports (getAnalysisReport) only for join and aggregation steps. None of the runtime filter's run-time events (Bloom build skipped, filter disabled, rows passed) appears there; they are all ProfileEvents. Showing the bitset there would first need a runtime filter report.
  • 05497 checks the bitset only through this counter in system.query_log; its join counts are the same with a Bloom filter. Without the counter, it would no longer show that the bitset is used. The perf test does not read the counter.
  • If it stays, its description should say that it counts bitset builds, not filters. It is incremented in each build stream whose exact set overflows, again when merging the per-stream filters overflows the exact set, and also for a single key with join_runtime_filter_from_fixed_hash_table on (the default), where the join's FixedHashMap then replaces the bitset.

@cv4g
cv4g added this pull request to the merge queue Nov 17, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Nov 18, 2026
master enabled the `modernize-use-nodiscard` clang-tidy check in ClickHouse#126158,
after this PR's last CI run. The merge queue's `Clang-tidy (changed files)`
job then flagged the new declaration (RuntimeFilterLookup.h:251 in the
merge commit) and removed the PR from the queue. This matches master's
`ExactSetRuntimeFilter::getValuesColumn`, which the same check annotated.

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

Copy link
Copy Markdown
Collaborator Author

The merge queue removed this PR because master's new modernize-use-nodiscard clang-tidy check (#126158) flagged the DenseBitsetRuntimeFilter::getValuesColumn declaration this PR adds. Fixed in 0edd19b (one [[nodiscard]], no other change), so it can go back to the queue.

cv4g added a commit that referenced this pull request Nov 18, 2026
What a JOIN runtime filter becomes is decided while the query runs: the exact set may overflow into a
Bloom filter, the Bloom filter may be dropped for too many set bits, and `HashJoin` may replace the
filter with its `FixedHashMap`. So far only ProfileEvents showed any of it, summed over the query.

`BuildRuntimeFilterStep` now has an analyzer that reports, per filter, what it was built as and what
its probe did:

    Runtime filter: type fixed hash map · replaced bloom filter
    Probe: checked … · passed … · pass rate …% · skipped … · before ready …

- `RuntimeFilter::describe` gives the kind of the final merged filter, its keys and size, the set bits
  of a Bloom filter, and why a filter passes every row. `AdaptiveSetRuntimeFilter` keeps the reason it
  dropped its key set, also across merges, and `KeySetDropped` cannot be created without a reason.
- When `RuntimeFilterLookup::replace` installs a filter under an existing key, `RuntimeFilter::supersede`
  makes it record the kind of the filter it replaced and count into the usage statistics of that filter,
  which may have probed blocks already. The statistics are shared, so probes that still run on the
  replaced filter are counted too.
- A `FixedHashMap` filter does not report its keys: the `Hash table` line of the join shows them.
- A lookup of a filter that is not ready yet is counted in its statistics as well as in
  `RuntimeFilterLookupsBeforeBuildFinished`.
- `BuildRuntimeFilterTransform` exposes the filter it registered. All build streams merge into it, so
  the first transform of the step reports for the whole step.
- The text and the JSON plan renderers know the new metrics.
- `04510_explain_analyze_join_stats` and `04758_explain_analyze_join_stats_merge_algorithms` match
  `unique keys` on the `Hash table` line only: a runtime filter that the join does not replace reports its
  keys too, on its own step.

Related: #129186 (comment)
@cv4g
cv4g enabled auto-merge November 18, 2026 01:00
@cv4g
cv4g added this pull request to the merge queue Nov 18, 2026
Merged via the queue into ClickHouse:master with commit 5b561b4 Nov 18, 2026
193 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 Nov 18, 2026
@rschu1ze

Copy link
Copy Markdown
Member

@groeneai Investigate how the dense bitset for runtime filters differs from the shared hash map introduced in #105640. In which situations are both representations triggered, is there overlap? Is one representation more efficient than the other (and in which cases)?

@groeneai

Copy link
Copy Markdown
Collaborator Author

Measured on the official release build of the merge commit 5b561b4 (100M probe rows, uniform UInt16 keys, 24 pinned cores), plus the code on master.

When each one is used

  • Shared FixedHashMap (Optimize some joins by reusing the hash join's FixedHashMap as runtime filter #105640, join_runtime_filter_from_fixed_hash_table): after the build, HashJoin publishes its own table and replaces whatever filter BuildRuntimeFilter registered (exact set, bitset or Bloom filter). Only for a hash join with the serial layout (estimated build below parallel_hash_join_threshold = 100000 rows), one disjunct, one key column, not an anti join, more than one build row, and a key8/key16 map or a 32/64 bit key that enable_join_fixed_hash_table_conversion turned into a range map (range up to 2^16, or up to 2^18 when at least 25% of it is filled). Nullable keys work.
  • Dense bitset (Use a dense bitset instead of a Bloom filter for JOIN runtime filters on 8 and 16 bit integer keys #129186): BuildRuntimeFilter switches to it when the exact set overflows join_runtime_filter_exact_values_limit (10000) on a non-Nullable (U)Int8/(U)Int16 filter type (an 8 bit key only with a limit below 256). Any layout, one filter per key column, not for transported partials.

Observed (RuntimeFilterDenseBitsetsBuilt and the Published shared fixed-hash-table runtime filter trace line):

Join Bitset Shared map Probing filter
one UInt16 key, 12000-row build (serial layout) built published shared map
one UInt16 key, 300000-row build with 12000 distinct keys (parallel layout) built not published bitset
same, hash_join_layout = 'serial' built published shared map
keys UInt16 + Int32 built not published bitset on the UInt16 key
one Int32 key, 12000 keys in a 60000 range no published (range16_key32) shared map
same Int32 key, 300000-row build (parallel layout) no not published Bloom filter
one Nullable(UInt16) build key no published shared map

So both are triggered only for one 16 bit key, serial layout, more than 10000 distinct build keys. There the bitset is built and then replaced (8 KiB per build stream). Outside that case each covers joins the other does not (parallel layout and several keys for the bitset; 32/64 bit, Nullable and below-limit keys for the shared map), so neither makes the other redundant.

Efficiency in the overlap (same binary, A/B by join_runtime_filter_from_fixed_hash_table, median of 21 runs, ms, 8 / 24 threads):

Build keys (rows passed) Query Shared map Bitset No filter
12000 (18%) sum(v) 80 / 46 74 / 41 104 / 54
30000 (46%) sum(v) 88 / 50 82 / 47 154 / 74
12000 (18%) count() 33 / 20 30 / 19 58 / 31
30000 (46%) count() 41 / 25 39 / 24 106 / 52

The bitset is 4-11% faster in every row. Its probe is one shift and mask per row on 8 KiB that stays in L1, and it counts the passed rows in the same loop. The shared map probe reads a cell of the join's table (65536 cells, 1.02 MiB for this join) after a range check, and the passed rows are counted in a second pass over the mask. This host has 2 MiB of L2 per core, so the table stays in L2; I did not measure a host with a smaller L2. Memory goes the other way: the shared map costs nothing extra, the bitset 8 KiB per build stream.

If you want, I can make publishSharedRuntimeFilters leave a filter that already switched to a bitset in place, which would give the overlap the numbers above. Otherwise there is nothing to change.

@snelheidai

Copy link
Copy Markdown

With less L2 than in groeneai's run, and with the exact set as a third case, the shared map is the slowest of the three for 8 and 16 bit keys, and the exact set is the fastest:

One key, build keys Shared map Bitset Exact set
UInt16, 12000 149 / 132 126 / 97 98 / 85
UInt16, 30000 187 / 166 167 / 128 143 / 114
UInt16, 5000 130 / 123 84 / 75
UInt8, 100 117 / 94 125 / – 92 / 84

Milliseconds on a Xeon 8375C (1.25 MiB L2 per core) / Graviton3 (1 MiB L2 per core): official builds of master 4e68e80, one binary per host with the filter chosen by settings, 100M probe rows with uniform keys, serial layout, count(), 4 threads, server time, median of 20 paired runs. The bitset is join_runtime_filter_from_fixed_hash_table = 0 (with join_runtime_filter_exact_values_limit = 10 for UInt8); the exact set for 12000 and 30000 keys also sets join_runtime_filter_exact_values_limit = 100000. The paired 95% intervals are within ±4.5%, and the same two settings give 1.00 in the parallel layout, where no map is published. Without a runtime filter, the 12000-key join takes 188 ms on the Xeon.

  • In the overlap, the bitset gains more as L2 shrinks: it takes 0.85-0.89 of the shared map's time on the Xeon and 0.72-0.77 on Graviton3, against 0.89-0.96 in groeneai's run with 2 MiB.
  • Below the limit, the shared map replaces an exact set and loses there too: 0.64 / 0.62 with 5000 keys, 0.79 / 0.90 for UInt8. So in the change you offered, @groeneai, publishSharedRuntimeFilters should replace only a Bloom filter for key8/key16 maps, leaving an exact set in place as well as a bitset. The gains in Optimize some joins by reusing the hash join's FixedHashMap as runtime filter #105640 were measured with Int64 keys, where the exact set hashes.
  • The exact set also beats the bitset: 0.79 / 0.86 with 12000 keys and 0.85 / 0.88 with 30000 (on the Xeon, 0.74 for UInt8 and 0.82 in the parallel layout). For an 8 or 16 bit key it is a FixedHashSet with one byte per value (64 KiB for UInt16), probed with 4 instructions per row. In perf, the bitset probe costs about 2.3 times as much: release builds bounds-check words[...] (_LIBCPP_HARDENING_MODE_FAST), and every row reloads words.data() and the result pointer, because the UInt8 store may alias them. So as written, the bitset from our JOIN runtime filters: an exact dense bitset instead of a Bloom filter for integer keys in a narrow range makes TPC-H q21, q04 and q22 1.3-2.3x faster #129092 is slower than keeping the exact set past the limit. Either keep the exact set for (U)Int8/(U)Int16 keys, whose size is bounded anyway, or probe the bitset through raw pointers. I measured only the first.
  • A query that reads more dilutes all of this: with sum(p.v), which also reads an 800 MB column, the exact set takes 0.96 of the bitset's time and the bitset equals the shared map (Xeon).

@groeneai

Copy link
Copy Markdown
Collaborator Author

I re-ran this with the exact set as a third case (official build of 5b561b4, 100M probe rows, count(), 4 threads, 40 paired runs, 2 MiB L2), and the order holds here too: the exact set takes 0.87 / 0.89 of the bitset's time with 12000 / 30000 UInt16 keys and 0.83 for UInt8, and 0.72 of the shared map's time with 5000 keys.

Probing the bitset through raw pointers does not close the gap. In a standalone loop of the same shape, the merged probe costs 0.66 ns per row, the same loop without the bounds check and the reloads 0.57, and a lookup in a one-byte-per-value table (what the exact set's FixedHashSet does), counting the passed rows afterwards, 0.35. So my "nothing to change" above was wrong. Two changes would help:

  1. Keep the exact set for (U)Int8/(U)Int16 keys past join_runtime_filter_exact_values_limit (its table is a fixed 256 B / 64 KiB array) and remove the bitset, together with RuntimeFilterDenseBitsetsBuilt and 05497.
  2. Make publishSharedRuntimeFilters leave an exact set in place for key8/key16 maps.

Should I open a PR with 1, 2, both, or neither?

@snelheidai

Copy link
Copy Markdown

Both. Your raw-pointer result shows the bitset can't catch up with the byte table, so for these keys (1) supersedes the bitset from our #129092, and (2) keeps the exact set where the shared map replaces it today.

For (1), I'd decide by the set rather than by the bitset's four types: keep the exact set past the limit whenever Set stores it as key8/key16. That also fixes two cases the bitset never covered. A Nullable(UInt16) key gets an exact-only filter with no Bloom fallback, so past the limit the filter is dropped. A Date key switches to a Bloom filter, which makes the join below 2.9 times slower than with runtime filters disabled.

12000 build keys, parallel layout Today Exact set kept
Nullable(UInt16) 236 ms, no filter 120 ms
Date 562 ms, Bloom filter 106 ms

Official build of 4e68e80, Xeon 8375C, 100M probe rows with uniform keys (18% match), count(), 4 threads, server time, medians of 15 paired runs (12 for the other figures here), 95% intervals within ±3%. "Exact set kept" is join_runtime_filter_exact_values_limit = 100000. The shared map replaces these filters only for a single key in the serial layout, and there it is slower than the exact set as well (Date: 146 against 98 ms).

Two details for (1):

  • Keep the limit for transported partials (boundExactSetByKeyBytes). AdaptiveSetRuntimeFilter::deserialize rejects an exact state with more than join_runtime_filter_exact_values_limit values, and a server without the change would too.
  • Past the limit, getRecordedKeyValues would give index analysis an IN set of up to 65536 values instead of the min/max range. If that should stay as it is, return nothing there.

Memory stays small: besides the 64 KiB table, a UInt16 set stores its values at 2 bytes each, so a filter keeps a few hundred KiB at most instead of 8 KiB, and every build stream already allocates the table today before it switches to the bitset.

opensource-fork-sync Bot pushed a commit to cla7aye15I4nd/opensource-ClickHouse__ClickHouse that referenced this pull request Nov 21, 2026
… hits the memory limit

`AdaptiveSetRuntimeFilter::switchToApproximateFilter` emplaced the Bloom
filter into the variant directly. `std::variant::emplace` destroys the exact
set first and then runs the constructor, which allocates the Bloom filter's
buffer through the memory tracker. When the memory limit refuses it, the
variant is left valueless. `BuildRuntimeFilterTransform` is an
`ISimpleTransform`, which passes the exception downstream and keeps pulling
blocks into the same filter, so the next block threw LOGICAL_ERROR
"Unexpected state of AdaptiveSetRuntimeFilter" and aborted debug and
sanitizer builds. The merge path (`mergeFrom` with a Bloom filter source)
went through the same function.

Build and fill the Bloom filter in a local and only then move it into the
variant, as `switchToDenseBitset` already does; the move is nothrow
(static_assert), so a refused allocation now leaves the exact set in place.
A full exact set on the next insert then means the previous switch threw;
it still holds every key (`ExactSetRuntimeFilter::insert` inserts the block
before setting `is_full`), so retry the switch instead of throwing.

The exception still reaches the user unchanged; only the state the filter is
left in changes. The transient peak during the switch grows by the exact
set's own buffers, bounded by `exact_bytes_limit`.

ClickHouse#129186 had this fix (9a9df77 + 9583f6a); the scope cut af3c523 dropped it
together with the dense-bitset memory handling.

Related: ClickHouse#129092
Related: ClickHouse#129186

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants