Repository navigation
Conversation
Is runtime_filter will be used as keyword only for bloom filters in JOIN step. (For example DISTINCT, #77728, it's not called runtime filter, but probably can be) |
This comment was marked as resolved.
This comment was marked as resolved.
|
Workflow [PR], commit [2e13141] Summary: ❌
|
ffd84a8 to
f8274fa
Compare
|
Let's please discuss how this should work at all. As of today, runtime filters can be dynamically (at runtime) disabled because of two reasons:
In other words, 1. protects against cases where the values on the probe side are uniformly distributed whereas 2. protects against cases where the probe-side value distribution is skewed. I think we should generally try to align the new static disabling conditions with the existing dynamic disabling conditions. For the existing dynamic disabling condition 1. this means, we should try to estimate at optimization time if more than 70% of all rows in the bloom filter will be set. Such an estimation can be done based on
The other existing disabling condition 2. is harder. In the absence of histograms, we must again assume a uniform distribution on the probe side. We want (conceptually) estimate how many rows This PR introduces three criteria which look at the probe side.
These criterial don't look very convincing to me, to be honest. Given that the math makes a lot of assumptions and dynamic disabling at probe time provides a fallback, I am very tempted to have static disabling only for the build side. |
| return std::nullopt; | ||
| } | ||
|
|
||
| static bool shouldDisableRuntimeFilter( |
There was a problem hiding this comment.
All of this will need lots of code comments that explain the rationale and math.
| @@ -5634,6 +5634,11 @@ Possible values: | |||
|
|
|||
| - 0 - Disable all optimizations at the query plan level | |||
| - 1 - Enable optimizations at the query plan level (but individual optimizations may still be disabled via their individual settings) | |||
| )", 0) \ | |||
| DECLARE(Double, query_plan_join_runtime_filter_saturation_threshold, 0.9, R"( | |||
There was a problem hiding this comment.
Let's move this next to the related settings with prefix join_runtime_* and rename to join_runtime_[...]
f8274fa to
a7ff2b7
Compare
Thank you for such detailed feedbacks and the excellent paper reference! I've just pushed an update that completely refactors this optimization based on your feedback:
Please let me know what you think of this revised approach. |
|
@il9ue Would you please update the PR message? Thanks. |
b7ffb6b to
3051b85
Compare
This comment was marked as resolved.
This comment was marked as resolved.
This comment was marked as resolved.
This comment was marked as resolved.
| "Saturation Check: Disabling filter for '{}' (n={})", | ||
| build_key_name, effective_n); | ||
| continue; | ||
| } |
There was a problem hiding this comment.
Redundant duplicate saturation check for each join key
Low Severity
shouldDisableRuntimeFilter is called twice per join key. When build_stats has ndv > 0, both calls compute identical n values, making the first call entirely redundant. When ndv == 0, the first call always returns false. Only the second call (using effective_n with build_side_row_count fallback) is needed.
There was a problem hiding this comment.
Lines 400..405: continue if
build_stats && build_stats) && shouldDisableRuntimeFilter(build_stats, optimization_settings, build_stats->ndv)
Lines 416..421: continue if:
build_stats && build_stats->ndv <= 0 && shouldDisableRuntimeFilter(build_stats, optimization_settings, build_side_row_count)orbuild_stats && build_stats->ndv > 0 && shouldDisableRuntimeFilter(build_stats, optimization_settings, build_stats->ndv)
There was a problem hiding this comment.
Consolidated per your suggestion — single call with effective_n = distinct_values > 0 ? distinct_values : build_side_row_count
There was a problem hiding this comment.
With this change now, isn't line 400..412 the same as line 418..428 (except for the if (build_stats))?
// If stats exist, perform the check
if (build_stats)
{
const auto effective_n = (build_stats->distinct_values > 0)
? build_stats->distinct_values
: build_side_row_count;
if (shouldDisableRuntimeFilter(build_stats, optimization_settings, effective_n))
{
LOG_DEBUG(getLogger("JoinRuntimeFilter"),
"Saturation Check: Disabling filter for '{}' (n={})",
build_key_name, effective_n);
continue;
}
}
// Determine effective n
// Priority 1: NDV from column stats (if > 0)
// Priority 2: Total rows from the plan step (fallback)
size_t effective_n = build_side_row_count;
if (build_stats && build_stats->distinct_values > 0)
effective_n = static_cast<size_t>(build_stats->distinct_values);
if (shouldDisableRuntimeFilter(build_stats, optimization_settings, effective_n))
{
LOG_DEBUG(getLogger("joinRuntimeFilter"),
"Saturation Check: Disabling filter for '{}' (n={})",
build_key_name, effective_n);
continue;
}
There was a problem hiding this comment.
I'll address it and ping you, then we can move to merge it :)
| QueryPlan::Node * curr = build_filter_node; | ||
| while (curr) | ||
| { | ||
| if (const auto * limit = typeid_cast<const LimitStep *>(curr->step.get())) |
There was a problem hiding this comment.
This traversal stops at the first LimitStep, so it can miss a tighter LIMIT deeper in the build subtree. For example, with nested limits like (SELECT id FROM (SELECT id FROM t LIMIT 10) LIMIT 100), this records 100 and ignores the inner 10, overestimating n and potentially disabling runtime filters that should stay enabled.
Please track the minimum limit across the whole unary chain instead of breaking at the first LimitStep.
|
Dear @cv4g, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself. |
| } | ||
|
|
||
| /// Planning-time saturation is only meaningful for Bloom-capable runtime filters. | ||
| if (!is_left_anti_join && shouldDisableRuntimeFilter(build_stats, optimization_settings, effective_n)) |
There was a problem hiding this comment.
The saturation check is applied before we know that this runtime filter will actually be Bloom-based. BuildRuntimeFilterTransform falls back to ExactContainsRuntimeFilter when ApproximateRuntimeFilter::isDataTypeSupported is false, and with enable_join_runtime_filter_shared_fixed_hash_table enabled it can later replace the Set/Bloom filter with SharedFixedHashTableRuntimeFilter. In both cases, skipping here because a hypothetical Bloom filter is saturated loses an exact runtime filter.
Please gate this branch on the filter being Bloom-capable and not eligible for the shared fixed-hash replacement, or otherwise let those exact-filter paths bypass the planning-time Bloom saturation check.
| /// If 'n' is 0, it means the estimator is uninitialized (common with new tables or missing stats). | ||
| /// Should fallback to the raw storage count, BUT re-apply the LIMIT check should also be done. | ||
| /// This prevents a "LIMIT 10" query on a 1M row table from being treated as 1M rows. | ||
| if (n == 0) |
There was a problem hiding this comment.
profile.rows == 0 is also a valid estimate for an empty or unsatisfiable build-side predicate; it does not only mean that statistics are missing. The no-statistics path already returned std::nullopt when getConditionSelectivityEstimator was unavailable, so falling back from a real zero estimate to getRowsCountAllParts can turn an empty build side into a large n and disable the runtime filter.
Please keep a real zero-row estimate as zero, or otherwise distinguish "estimator missing" from "estimator says no rows".
| const auto & dag = filter_step->getExpression(); | ||
| const auto * predicate = static_cast<const ActionsDAG::Node *>(dag.tryFindInOutputs(filter_step->getFilterColumnName())); | ||
| if (predicate) | ||
| filter_node = predicate; |
There was a problem hiding this comment.
This traversal has the same predicate-loss problem as the open estimateBuildSubtreeRows thread: each FilterStep assignment overwrites the previously collected predicate. With FilterStep(A) -> FilterStep(B) -> ReadFromMergeTree, only B reaches estimateRelationProfile, so the build-side rows and NDV can be overestimated and the saturation check can disable a filter that should remain enabled.
Please accumulate the predicates as A AND B while walking the chain, the same way ConditionSelectivityEstimator combines filter and prewhere.
| if (typeid_cast<const ExpressionStep *>(node->step.get())) | ||
| return estimateBuildSubtreeRows(child, filter); | ||
|
|
||
| return estimateBuildSubtreeRows(child, filter); |
There was a problem hiding this comment.
estimateBuildSubtreeRows currently recurses through every unrecognized unary step as if it preserved row count. That is not true for steps such as AggregatingStep, DistinctStep, or LimitByStep. For a build side that reduces a large table to a small result before the JOIN, this will use the underlying ReadFromMergeTree row count, overestimate n, and can skip a useful runtime filter as "saturated".
Please only recurse through steps that are known to preserve cardinality, add explicit estimates for row-reducing steps, or return std::nullopt instead of treating unknown unary steps as preserving rows.
|
Dear @cv4g, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself. |
|
Will rebase to #114824 as a next step |
…runtime-filter-disable Resolve the conflict with the move of the settings changes history into the setting declarations (ee6b44f): the history records this PR added to `SettingsChangesHistory.cpp` now live as trailing arguments of the `DECLARE` of each setting. - retargeted PR record [email protected] to 26.10 (settings-history check rule) Also resolved conflicts in: - `src/Processors/QueryPlan/BuildRuntimeFilterStep.cpp` - `src/Processors/QueryPlan/Optimizations/QueryPlanOptimizationSettings.h` - `src/Processors/QueryPlan/Optimizations/joinRuntimeFilter.cpp` - `src/Processors/QueryPlan/RuntimeFilterLookup.cpp` - `src/Processors/QueryPlan/RuntimeFilterLookup.h` - `src/Storages/Statistics/ConditionSelectivityEstimator.cpp` - `src/Core/Settings.cpp` `RuntimeFilterLookup.{h,cpp}` follow master's rewrite; the PR's logging-only build statistics are dropped. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
|
📊 Cloud Performance Report ✅ AI verdict: This PR only changes planning for JOIN runtime filters. It adds a new setting, join_runtime_bloom_filter_max_estimated_ratio_of_set_bits, which is off by default at 1.0, plus build-side row and distinct-value estimation and suffix matching of column names in the statistics estimator. All four flagged queries are single-table ClickBench queries on hits with no JOIN, so none of them runs that code, and tpch_adapted_1_official, where joins are actually exercised, had no flagged queries. Q16 (+16.5%, noisy history) and Q23 (-44.7%) are downgraded to not sure; Q23 falls outside master's current range with a large CPU drop, which points to a different branch base or environment, not to this diff. Q18 (+10.6%) and Q33 (+6.1%) stay suppressed as within master's normal range, which matches the diff. clickbenchFlagged queries (4 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 No significant changes Debug info
|
Assign the `std::optional` directly instead of dereferencing and re-wrapping it (`bugprone-optional-value-conversion`), and use `std::min` for clamping the build-side statistics (`readability-use-std-min-max`). Build log: https://d1k2gkhrlfqv31.cloudfront.net/clickhouse-test-reports-private/PRs/77668/312f2ae1988eb31baf0c1f0ce206cfa7773e71aa/pr/build_arm_tidy/build_clickhouse/build_clickhouse.log Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
|
Dear @cv4g, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself. |


Resolves #96095
Summary
Runtime filters built on high-NDV join keys (e.g., large PK-FK joins) can saturate the Bloom filter, causing it to pass almost every probe row. This wastes CPU for building and evaluating the filter with zero query speedup. This optimization detects saturation at planning time using build-side statistics.
This PR adds a planning-phase heuristic that skips building join runtime filters when table statistics indicate the filter will be ineffective due to high saturation. This avoids unnecessary CPU cost from building and evaluating Bloom filters that would pass nearly all probe rows.
New setting:
join_runtime_bloom_filter_max_estimated_ratio_of_set_bits(float, default: 1.0).1.0to disable this optimization entirely.Changes
joinRuntimeFilter.cpp: AddedshouldDisableRuntimeFilter()andgetJoinKeyStats()helpers. Injected statistics check insidetryAddJoinRuntimeFilterbefore filter steps are added to the plan.Settings.cpp**: Addedjoin_runtime_filter_build_saturation_threshold(Float, default 0.9).QueryPlanOptimizationSettings.h/.cpp: Exposed the new setting and the existing Bloom filter settings (bytes,hashes) to the optimizer.03437_runtime_filter_saturation.sqlto cover saturation scenarios using small, highly-saturated Bloom filters.Disabling Conditions
The optimization estimates the expected Bloom Filter Saturation using:
join_runtime_bloom_filter_bytes* 8)join_runtime_bloom_filter_hash_functions)If the expected saturation () exceeds
join_runtime_filter_build_saturation_threshold(default 0.9), the runtime filter is skipped at planning time.Example:
The optimization is a no-op when table statistics are unavailable — runtime filters remain enabled in that case.
Changelog category (leave one):
Changelog entry:
Added setting
join_runtime_bloom_filter_max_estimated_ratio_of_set_bits(default 1.0) which skips building join runtime filters at planning time when column statistics indicate the Bloom filter will be highly saturated. This avoids wasting CPU time to build an ineffective runtime filter for joins that have a high number of distinct values (NDV) on the build side. The new check uses the build-side NDV and configured Bloom filter size to mathematically estimate saturation.Note
Medium Risk
Changes query-plan optimization to conditionally omit JOIN runtime filters based on build-side statistics and configured Bloom filter parameters, which can alter generated plans and performance characteristics. Logic is best-effort and has fallbacks, but misestimation could skip beneficial filters or add overhead in edge cases.
Overview
Adds a planning-phase heuristic in
joinRuntimeFilter.cppthat estimates Bloom filter saturation (1 - exp(-k*n/m)) from build-side NDV/row-count stats (respectingLIMIT) and skips creating runtime filters when they are expected to be ineffective, usingjoin_runtime_bloom_filter_max_ratio_of_set_bitsas the threshold.Plumbs Bloom filter size/hash settings into
QueryPlanOptimizationSettings(and adjusts types tosize_t), updates the setting documentation to note its planning-time use, and adds stateless tests asserting when runtime filters are present/absent under high saturation, low saturation viaLIMIT, and missing statistics fallbacks.Separately, silences specific static-analysis/compiler warnings (empty
catchinmemory.h, clang diagnostic aroundreinterpret_castinIAST::flags()).Written by Cursor Bugbot for commit cc6d6ca. This will update automatically on new commits. Configure here.
Workflow [PR]
Sync PR [sync-upstream/pr/97501]