Skip to content

Skip the join runtime filter Bloom filter build that the key count predicts to saturate - #118336

Merged
rschu1ze merged 11 commits into
ClickHouse:masterfrom
raimannma:runtime-filter-skip-saturated-bloom-filter
Sep 9, 2026
Merged

rschu1ze merged 11 commits into
ClickHouse:masterfrom
raimannma:runtime-filter-skip-saturated-bloom-filter

Conversation

@raimannma

@raimannma raimannma commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Related: #118230

ApproximateRuntimeFilter sizes its Bloom filter from the build-side key count of the hash table statistics, but the size is capped at 4 MiB. With more distinct keys than fit at join_runtime_bloom_filter_max_ratio_of_set_bits, every build thread filled and merged its 4 MiB copy only for checkBloomFilterWorthiness to discard the result: on a 30M-key SEMI JOIN that was a third of all CPU time, and the query's profile events showed no row ever checked against the filter.

The same formula that sizes the filter predicts its fill rate at the capped size, 1 - exp(-keys * hashes / bits). When that exceeds the maximal ratio, the filter is disabled before the build instead of after it. The min/max envelope for index analysis is still tracked. New profile event RuntimeFilterBloomFilterBuildsSkipped.

Split out of #118230.

Changelog category (leave one):

  • Performance Improvement

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

The join runtime filter no longer builds a Bloom filter that the build-side key count predicts to be too dense to be useful.


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

Version info

  • Merged into: 26.9.1.1041 (included in 26.9 and later)

…edicts to saturate

`ApproximateRuntimeFilter` sizes its Bloom filter from the build-side key count of the
hash table statistics, but the size is capped at 4 MiB. With more distinct keys than fit
at `join_runtime_bloom_filter_max_ratio_of_set_bits`, every build thread filled and
merged its 4 MiB copy only for `checkBloomFilterWorthiness` to discard the result: on a
30M-key `SEMI JOIN` that was a third of all CPU time, and the query's profile events
showed no row ever checked against the filter.

The same formula that sizes the filter predicts its fill rate at the capped size,
`1 - exp(-keys * hashes / bits)`. When that exceeds the maximal ratio, the filter is
disabled before the build instead of after it. The min/max envelope for index analysis is
still tracked. New profile event `RuntimeFilterBloomFilterBuildsSkipped`.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SGvsqqytvRcokXN8TWn2Mr
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Sep 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7d51c7b]

Summary: ✅


AI Review

Summary

This PR makes ApproximateRuntimeFilter skip building a Bloom filter up front when cached hash-table statistics predict that the capped filter would already be too dense to help, and it adds a stateless test around that path. The multi-key false-disable issue from the first revision is fixed, but I do not think this is ready to merge yet: the new hard skip can still suppress a useful filter on the first run after the build side shrinks sharply, and the user-visible setting docs still describe join_runtime_filter_size_from_hash_table_stats as a sizing-only knob.

Findings

⚠️ Majors

  • src/Processors/QueryPlan/RuntimeFilterLookup.cpp:543-548, src/Processors/QueryPlan/Optimizations/joinRuntimeFilter.cpp:191-204, src/Interpreters/HashJoin/HashJoin.cpp:1458-1460, src/Interpreters/HashTablesStatistics.cpp:43-46 [dismissed by author -- https://github.com/Skip the join runtime filter Bloom filter build that the key count predicts to saturate #118336#discussion_r3951686318] The new fast path treats the cached ht_size hint as if the current execution must still be within HashJoinEntry::MAX_OVERESTIMATION_FACTOR, but the cache is only updated after the shrunken run finishes. A concrete trace is enough to show the gap: if one execution stores a 30M-key hint and the next execution of the same plan shape builds only 1M distinct keys, planning still sees 30M, derives least_distinct_keys = 15M, and drops the Bloom filter because that predicts ~73.8% fill of the 4 MiB cap, even though the actual 1M-key filter would only be ~8.6% full and remain useful. That turns a sizing hint into a one-run performance regression on variable-cardinality workloads.
    Suggested fix: keep the statistic sizing-only unless you have a freshness signal for the current run, or store explicit freshness/lower-bound information with the cached entry instead of inferring it from shouldBeUpdated.

  • src/Core/Settings.cpp:9217-9219 join_runtime_filter_size_from_hash_table_stats now changes whether a runtime filter is built at all, but its source-level docs still promise that it only sizes the filter and otherwise falls back to join_runtime_bloom_filter_bytes. Users enabling the setting will not see that it can suppress Bloom-filter construction when the cached key count predicts saturation.
    Suggested fix: extend the DECLARE text to mention the pre-build skip behavior and its interaction with join_runtime_bloom_filter_max_ratio_of_set_bits.

Final Verdict

Changes requested. The pre-build skip still has a real stale-hint regression on variable-sized workloads, and the new user-visible setting behavior is not documented.

LLVM Coverage Report

Measured on commit 7d51c7b.

Metric Baseline Current Δ
Lines 88.80% 88.80% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.20% 81.20% +0.00%

Changed lines: Changed C/C++ lines covered: 103/104 (99.04%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... labels Sep 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 7d51c7b48 with master 85439c0e4 (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.

Compile time of recompiled translation units

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

Job report

@clickhouse-gh

clickhouse-gh Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 40 queries analysed

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: f0689ad5-328c-4bc6-9aca-e45302022207
  • MIRAI run: ed8a5ab0-cb56-416c-9f04-902f4b6d8019
  • PR check IDs:
    • clickbench_69564_1788899322
    • clickbench_69570_1788899322
    • clickbench_69576_1788899322
    • tpch_adapted_1_official_69587_1788899322
    • tpch_adapted_1_official_69599_1788899322
    • tpch_adapted_1_official_69635_1788899322

@rschu1ze rschu1ze self-assigned this Sep 7, 2026
raimannma and others added 3 commits September 7, 2026 18:25
…er build

The hash table statistics are keyed by the join order optimization, which assigns no
key when `query_plan_optimize_join_order_limit` is 0. The test harness randomizes
that setting to 0 in about 5% of the runs, so the second run of the test found no
size hint and built the filter again instead of skipping it.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118336&sha=latest&name_0=PR
PR: ClickHouse#118336

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Pp8vKdfGBejMpYwu4EKgP8
…nd allow for a stale key count

The hash table statistics count distinct join keys. A per-column filter of a multi-key join gets
only an upper bound of its distinct values from them, so its build is sized by the count but never
skipped. The statistics also keep a measured size until a run finds less than half of it, so the
build is skipped only if half of the counted keys would saturate the filter.

Also explain in `disable` why it releases the exact values, link the fill rate formula, and reword
the comments from the review.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Pp8vKdfGBejMpYwu4EKgP8
/// (`HashJoinEntry::shouldBeUpdated`), so the build is skipped only if half of the hinted keys saturate the filter.
if (distinct_keys_hint_matches_filter_key)
{
const double least_distinct_keys = static_cast<double>(*distinct_keys_hint) / 2.0;

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.

Using *distinct_keys_hint / 2 here does not actually make the skip safe on the first execution after the build side shrinks. getBuildSideDistinctKeys reads the previous HashJoinEntry::ht_size, and HashTablesStatistics::update deliberately keeps the old maximum until a later run finishes with new_entry.ht_size < old / 2. So a query that previously saw, say, 8M build keys and now sees 1M will still plan with least_distinct_keys = 4M and can hit disable() even though the current Bloom filter would stay below the density threshold. Before this PR a stale hint only oversized the filter; now it changes behavior. Please keep the hint sizing-only, or gate this fast path on a freshness signal that proves the current run is within that 2x window.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The stale hint cannot be verified at planning time: the current run's size is unknown until the hash table is built, so no freshness signal can prove it is within the 2x window. The / 2 covers the case where the statistics deliberately keep the old maximum. For the remaining case, a build side that shrinks by more than 2x below a hint above ~27M keys (defaults), the cost is one run without the Bloom filter: it is never wrong, only absent, the min/max envelope is still tracked, and that same run updates the statistics (new_entry.ht_size < ht_size / 2), so the next run plans correctly. The old sizing-only behavior filled and merged a 4 MiB filter per thread that was then discarded, which the fast path avoids, so I keep it.

/*track_key_range_=*/optimization_settings.enable_join_runtime_filters_index_analysis,
distinct_keys_hint);
distinct_keys_hint,
/*distinct_keys_hint_matches_filter_key_=*/true);

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.

It's not clear to me why we set true in l. 479.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's true because this filter is built on the complete join key, so the hash table size counts exactly this filter's distinct keys

raimannma and others added 3 commits September 7, 2026 22:45
…he build side

`HashJoinEntry::shouldBeUpdated` and the Bloom filter build skip both relied on
the literal `2`, which must stay in sync. Expose it as
`HashJoinEntry::MAX_OVERESTIMATION_FACTOR` and use it in both places.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01JyZgVjwycGoE67Jf1wvve6
… filter test, add a performance test

`05077_join_runtime_filter_skip_saturated_bloom_filter` failed in the old analyzer and the parallel replicas CI configurations: the old analyzer builds no join runtime filters, and with parallel replicas the probe side is read on the replicas, so `RuntimeFilterRowsChecked` stays zero on the initiator. The test now sets `enable_analyzer = 1` and `enable_parallel_replicas = 0` like the other runtime filter tests.

The performance test joins a 1M row probe side with a 40M distinct key build side, which saturates the largest statistics-sized Bloom filter, so the build is skipped from the second run on. Interleaved runs of the CI-built master (55c2563) and PR binaries, 20 per binary, on a 12-core machine: median 702 ms -> 432 ms (Mann-Whitney p = 6.8e-8, Welch p = 1.8e-21), and no change for a 1M key build side, a multi-key join, or a join without runtime filters.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118336&sha=b4a7e250382525575e3d467dd803093b507aff62&name_0=PR

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_019Y56AP2MkgeFa9TAJ9oMjE
const double least_distinct_keys = static_cast<double>(*distinct_keys_hint) / HashJoinEntry::MAX_OVERESTIMATION_FACTOR;
const double predicted_fill_rate = -std::expm1(
-static_cast<double>(bloom_filter_hash_functions) * least_distinct_keys / (static_cast<double>(bloom_filter_bytes) * 8.0));
if (predicted_fill_rate > max_ratio_of_set_bits_in_bloom_filter)

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.

This makes join_runtime_filter_size_from_hash_table_stats more than a sizing knob: with the setting enabled, planning can now skip building the Bloom filter altogether. The source-level setting docs still say it only sizes the runtime filter and otherwise falls back to join_runtime_bloom_filter_bytes, so users will not see this new behavior documented. Please update the DECLARE text in src/Core/Settings.cpp (and the matching SettingsChangesHistory.cpp blurb if you keep them aligned).

<fill_query>INSERT INTO rf_probe SELECT number FROM numbers(1000000)</fill_query>
<fill_query>INSERT INTO rf_build SELECT number * 2 FROM numbers(40000000)</fill_query>

<query>SELECT count() FROM rf_probe INNER JOIN rf_build ON rf_probe.k = rf_build.k</query>

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.

We'd need to run the same query twice here ... which the test framework doesn't allow.

The test was added by some agent. Let's remove it?

}
else
/// We can only merge the min-max value envelopes.
if (source_typed->is_fully_disabled)

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.

Someone reading

    if (source_typed->is_fully_disabled)
        disable();

will be too confused. Could you give the member variable and the function more fitting names please?

raimannma and others added 2 commits September 8, 2026 19:25
The state means the filter gave up on its key set and passes all rows while still tracking the key-range
envelope, so name it `key_set_dropped` / `markKeySetDropped` / `dropKeySet` instead.

Requested in ClickHouse#118336 (comment)

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_015spRVzDCnLCTyZZ5to1u8h
@rschu1ze
rschu1ze added this pull request to the merge queue Sep 9, 2026
Merged via the queue into ClickHouse:master with commit 8d93bd4 Sep 9, 2026
175 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 9, 2026
@raimannma
raimannma deleted the runtime-filter-skip-saturated-bloom-filter branch September 12, 2026 19:48
groeneai pushed a commit to groeneai/ClickHouse that referenced this pull request Oct 9, 2026
… hash table statistics

The hash table of a join is keyed on both `Equals` and `NullSafeEquals` pairs, so its statistics count
distinct tuples of all of them, while runtime filters are built only from the `Equals` keys
(`JoinStepLogical::preCalculateKeys`). For `ON a = b AND c <=> d` the single filter key was marked as
matching the statistics, and `AdaptiveSetRuntimeFilter::switchToApproximateFilter` predicted a
saturated Bloom filter from the inflated tuple count and skipped it from the second run on.

Mark the statistics as matching the filter key only when the filter keys are all the hash table keys.
Such filters are still sized by the statistics, but never skipped.

ClickHouse#122167
Related: ClickHouse#118336

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.

4 participants