Repository navigation
Use a dense bitset instead of a Bloom filter for JOIN runtime filters on 8 and 16 bit integer keys - #129186
Conversation
… 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]>
This comment was marked as resolved.
This comment was marked as resolved.
This comment was marked as resolved.
This comment was marked as resolved.
This comment was marked as resolved.
This comment was marked as resolved.
|
Workflow [PR], commit [0edd19b] Summary: ✅
AI ReviewSummaryReviewed #129186 at Final VerdictStatus: ✅ Approve |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes12 object files changed (+37.68 KiB total), 0 added.
711 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Slowest function optimization changes (ThinLTO)Median per-function time ratio to the master baseline:
Compile time of recompiled translation units159 translation units recompiled, 2327 s compile time in total, 159 of them have a recent master baseline. |
…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]>
This comment was marked as resolved.
This comment was marked as resolved.
This comment was marked as resolved.
This comment was marked as resolved.
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]>
This comment was marked as resolved.
This comment was marked as resolved.
This comment was marked as resolved.
This comment was marked as resolved.
…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]>
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]>
`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]>
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 During review I also noticed the intermediate column built in |
|
On whether to keep
|
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]>
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)
|
Measured on the official release build of the merge commit 5b561b4 (100M probe rows, uniform When each one is used
Observed (
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
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 |
|
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:
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,
|
|
I re-ran this with the exact set as a third case (official build of 5b561b4, 100M probe rows, 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
Should I open a PR with 1, 2, both, or neither? |
|
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
Official build of 4e68e80, Xeon 8375C, 100M probe rows with uniform keys (18% match), Two details for (1):
Memory stays small: besides the 64 KiB table, a |
… 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]>

Related: #129092
Related: #96779
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
JOIN runtime filters on
Int8,UInt8,Int16andUInt16keys 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_limitand the key isInt8,UInt8,Int16orUInt16, 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 INfilters 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'sFixedHashMapafter 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
UInt16and aUInt8key 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 theUInt16key alone, where theFixedHashMapfilter takes over, 1.00 / 0.98. TheUInt16query added tojoin_runtime_filter.xmlabout 0.55. No TPC-H or TPC-DS key is(U)Int8or(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
RuntimeFilterDenseBitsetsBuiltevent for a 16 and an 8 bit key.Workflow [PR]
Sync PR [sync-upstream/pr/129186]
Version info
26.11.1.2674-master(included in26.11and later)