You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Introduce statistics-based disabling of join runtime filters #96095
Disabling runtime filters during query planning when they are expected to be ineffective.
Describe the solution you'd like
Sometimes it’s possible to estimate the effectiveness of a runtime filter during the planning phase before the filter is built. This spares the cost of building ineffective filters.
This could be done by taking statistics about the build and probe tables into account (size, distinct count, value range).
One obvious example, if the tables have a primary key - foreign key relationship with no other predicates, the runtime filter will not be effective.
We should come up and implement such criteria for early disabling of runtime filters.
Here is an observation-based way to do this, with measurements and a patch.
The patch skips a JOIN runtime filter when, the last time the same join built it, more than 95% of the rows it checked passed (or its Bloom filter of the same size was dropped as too full). The observation is kept in the hash-table statistics cache, so it needs collect_hash_table_stats_during_joins. After 16 skips, or an hour after the observation, the filter is built again so that changed data is noticed. It is behind join_runtime_filter_skip_ineffective (on by default in the patch).
Why observed rather than estimated. In the #97501 review, @rschu1ze leaned towards static disabling only for the build side, because estimating how many probe rows pass needs many assumptions and the dynamic join_runtime_filter_pass_ratio_threshold_for_disabling rule is the fallback. That fallback still builds the filter on every run, and the cost is not small:
TPC-DS q64 builds 43 filters per run. 14 of them pass more than 95% of the rows they check, so the dynamic rule switches them off for most blocks. Not building them takes q64 from 2.11 to 1.53 s (CPU 6.3 → 4.2 s).
When q50's plan uses the 28.8M-row store_sales as the build side, its filters are applied to store_returns, whose rows all have a matching sale, so 4 of them pass almost every row. This is the PK-FK case from this issue, and master's statistics-based build-side check does not fire for these filters (RuntimeFilterBloomFilterBuildsSkipped stays 0). Not building them takes that plan from 3.1 to 2.6 s. An earlier profile put Bloom building in this plan shape at about 2 s of CPU per warm run (q50, q93).
An observed pass ratio needs no NDV or containment assumptions. It complements a build-side estimate such as #97501's, which can act on the first run.
Iceberg TPC-DS SF10, warm. One binary (master 230ae8e + #128139 + patch), setting off vs on: median ms, change of paired runs with 95% CI.
Query (pairs)
Off
On
Change [95% CI]
q64 (20, incl. a rebuild run)
2106
1526
−27% [−30%, −23%]
q05 (20)
1185
997
−14% [−18%, −11%]
q95 (20)
4615
3949
−14% [−17%, −11%]
q33, q93 (20)
1159, 2541
876, 2045 in runs 1–16
−25%, −19% until the first rebuild; −3%, 0% after it
q07, q47, q70, q86 (2 × 7)
1185, 2906, 898, 134
1154, 2921, 894, 130
between −3% and +3%; no CI excludes 0 in both sessions
geomean −1.3%; 6 faster by more than 5%, none slower by more than 5%
What counts as the same join. An observation is reused only by the same join over the same inputs: the same hash-table-statistics output key (it covers both inputs), the same values of all constants in the actions of the join and of both inputs (including String literals and query parameters, which the statistics keys leave out), and the same build and probe key columns. A dropped key set is reused only with the same Bloom size inputs. A pass ratio is reused with any size: with the default 3 hash functions and at most 70% of its bits set, a Bloom filter passes at most 34% of the non-matching rows, so more than 95% passing with one size means more than 92% with any other. On Iceberg and in the new test 05497_join_runtime_filter_skip_ineffective, a selective query that runs after a non-selective one with the same build side and key columns, but with another probe side or another String literal, keeps its filter in every run, with unchanged latency.
Depends on #128139 (open). Without it, q07, q47, q70 and q86 are 7–10% slower with the setting on; with it they are unchanged. The dynamic rule had already switched those filters off for most rows; earlier profiling pointed at the scattered Parquet decoding of the join-key column, which #128139 makes dense.
Limits.
The first run is unchanged. Every 17th run rebuilds the skipped filters (for q64 one run of about 2.1 s, included above).
q33 and q93 gain only until the first rebuild: the first run's default-size Bloom filters pass more than 95%, the statistics-sized ones slightly less, so the rebuilt filters are kept.
q50 is left out of the table. Its plan after the first run flips between about 0.86 s and 2.5–3.2 s from session to session, with the setting off or on (the slow plan came up in 3 of 9 fresh sessions with the setting off, 5 of 9 with it on). That plan is chosen from the first run's statistics, before anything is skipped. With the fast plan both settings take about 0.86 s.
Plans and EXPLAIN depend on earlier runs, as they already do through the hash-table statistics. A filter whose keys a reader uses for index analysis is never judged.
Results are identical with the setting off and on for all 99 queries and for the 350 stateless tests that mention runtime filters (03580_join_runtime_filter now pins the setting off, because it checks EXPLAIN after running the same joins). One 4-vCPU x86 host, SF10, local files.
Data: TPC-DS SF10 written by ClickHouse into IcebergLocal tables (Parquet, unpartitioned, rows sorted by each table's sorting key).
Queries: tests/benchmarks/tpc-ds/queries with data_type_default_nullable=1, group_by_use_nulls=1, join_use_nulls=1, union_default_mode='DISTINCT', intersect_default_mode='DISTINCT', joined_subquery_requires_alias=0. All other settings are defaults, so runtime filters and hash-table statistics are on.
Two fresh servers on separate copies of the same binary over the same files, one with join_runtime_filter_skip_ineffective = 0. For each query: one warm-up per server (results compared), then N pairs in alternating order. Metric: query_duration_ms from system.query_log; geometric mean of the paired ratios with a Student-t 95% interval. "2 × 7" means two sessions of 7 pairs with the servers' roles swapped.
Isolation test on Iceberg, each selective query run after its non-selective one had already skipped its filter: store_sales joined with item, then the same join with the probe keys shifted by 51000 (about half match): 0 skips in every run, on/off 1.02 [0.98, 1.07]. Build side item WHERE i_category >= 'A', then >= 'Sports': 0 skips, 1.02 [0.97, 1.08].
diff --git a/src/Common/ProfileEvents.cpp b/src/Common/ProfileEvents.cpp
index 00594862f82..3b122b6af36 100644
--- a/src/Common/ProfileEvents.cpp+++ b/src/Common/ProfileEvents.cpp@@ -1891,6 +1891,7 @@ The server successfully detected this situation and will download merged part fr
M(RuntimeFilterReceivesAbandoned, "Number of JOIN Runtime Filter streams whose sender disconnected after the connection was established, before the end of the stream; if the sender's state had not arrived, the affected filter is not used and rows pass unfiltered", ValueType::Number) \
M(RuntimeFilterReceiveBranchFailures, "Number of tasks that failed to receive a JOIN Runtime Filter from another task; that task does not use the filter and rows pass unfiltered", ValueType::Number) \
M(RuntimeFilterBloomFilterBuildsSkipped, "Number of JOIN Runtime Filter Bloom filter builds skipped because the build-side key count from the hash table statistics predicted that the filter would exceed the maximal ratio of set bits", ValueType::Number) \
+ M(RuntimeFiltersSkippedAsIneffective, "Number of JOIN Runtime Filters not built because the last run of the same join that built them observed that they filtered out almost nothing (see `join_runtime_filter_skip_ineffective`)", ValueType::Number) \
M(RuntimeFilterIndexAnalysisReads, "Number of reads set up to prune granules with a JOIN runtime filter at read time. Counted when the read reaches its pipeline carrying the descriptors and has a primary key or skip index to prune them with, whether or not a granule is later examined, so it shows that the descriptors survived every rebuild of the read step.", ValueType::Number) \
M(RuntimeFilterGranulesConsidered, "Number of granules examined for read time pruning by JOIN Runtime Filters", ValueType::Number) \
M(RuntimeFilterGranulesDropped, "Number of granules pruned at read time by JOIN Runtime Filters", ValueType::Number) \
diff --git a/src/Core/Settings.cpp b/src/Core/Settings.cpp
index acc8d42786a..ac0957f1f36 100644
--- a/src/Core/Settings.cpp+++ b/src/Core/Settings.cpp@@ -11358,6 +11358,14 @@ The granule pruning is also skipped for a probe side read with `FINAL` (the prun
Use hash table size statistics collected from previous executions to size the JOIN runtime filter. When disabled, fall back to the fixed `join_runtime_bloom_filter_bytes`.
)", 0, \
{"26.7", false, true, "Use hash table size statistics collected from previous executions to size the JOIN runtime filter. When disabled, fall back to the fixed `join_runtime_bloom_filter_bytes`."}) \
+ DECLARE(Bool, join_runtime_filter_skip_ineffective, true, R"(+Do not build a JOIN runtime filter that filtered out almost nothing the last time the same join built it: more than `join_runtime_filter_skip_ineffective_pass_ratio` of the rows it checked passed, or its Bloom filter of the same size was dropped as too full. The same join means the same join of the same inputs with the same constants. The observation is kept with the hash table statistics, so it needs `collect_hash_table_stats_during_joins`. After 16 skips, or an hour after the observation, the filter is built once more to refresh the observation. Filters that are used to prune granules at read time are never skipped.+)", 0, \+ {"26.11", false, true, "New setting: skip JOIN runtime filters that filtered out almost nothing in a previous run of the same join."}) \+ DECLARE(Double, join_runtime_filter_skip_ineffective_pass_ratio, 0.95, R"(+With `join_runtime_filter_skip_ineffective`, a JOIN runtime filter is skipped when more than this share of the rows it checked passed in the last run that built it. It is higher than `join_runtime_filter_pass_ratio_threshold_for_disabling` because a skipped filter cannot be enabled again for the parts of the data where it does filter.+)", 0, \+ {"26.11", 0.95, 0.95, "New setting"}) \
DECLARE(Bool, rewrite_in_to_join, false, R"(
Rewrite expressions like 'x IN subquery' to JOIN. This might be useful for optimizing the whole query with join reordering.
)", EXPERIMENTAL, \
diff --git a/src/Interpreters/HashJoin/HashJoin.cpp b/src/Interpreters/HashJoin/HashJoin.cpp
index fa761aa2446..657c0847df1 100644
--- a/src/Interpreters/HashJoin/HashJoin.cpp+++ b/src/Interpreters/HashJoin/HashJoin.cpp@@ -2782,8 +2782,8 @@ void HashJoin::publishSharedRuntimeFilters()
RuntimeFilter::SharedFixedHashTable(
existing->getFilterColumnTargetType(),
probe_fn,
- existing->getRecordedKeyRanges(),- existing->getRecordedKeyValues()));+ existing->getRecordedKeyRanges(/*mark_used=*/false),+ existing->getRecordedKeyValues(/*mark_used=*/false)));
/// `replace` keeps the original registration's display name in the lookup, so stats stay legible.
LOG_TRACE(getLogger("HashJoin"), "Published shared fixed-hash-table runtime filter under key '{}'", descriptor.filter_key);
lookup->replace(descriptor.filter_key, std::move(filter));
diff --git a/src/Interpreters/HashTablesStatistics.cpp b/src/Interpreters/HashTablesStatistics.cpp
index 3297aa7146c..127532921c7 100644
--- a/src/Interpreters/HashTablesStatistics.cpp+++ b/src/Interpreters/HashTablesStatistics.cpp@@ -1,4 +1,5 @@
#include <Interpreters/HashTablesStatistics.h>
+#include <Processors/QueryPlan/RuntimeFilterStatistics.h>
#include <Poco/Logger.h>
#include <Common/logger_useful.h>
@@ -176,4 +177,5 @@ template class HashTablesStatistics<AggregationEntry>;
template class HashTablesStatistics<HashJoinEntry>;
template class HashTablesStatistics<HashJoinMatchEntry>;
template class HashTablesStatistics<RadixUniqExactEntry>;
+template class HashTablesStatistics<RuntimeFilterEntry>;
}
diff --git a/src/Processors/QueryPlan/Optimizations/QueryPlanOptimizationSettings.cpp b/src/Processors/QueryPlan/Optimizations/QueryPlanOptimizationSettings.cpp
index 1ae954147ac..a554df73d7f 100644
--- a/src/Processors/QueryPlan/Optimizations/QueryPlanOptimizationSettings.cpp+++ b/src/Processors/QueryPlan/Optimizations/QueryPlanOptimizationSettings.cpp@@ -160,6 +160,8 @@ namespace Setting
extern const SettingsUInt64 join_runtime_filter_exact_values_limit;
extern const SettingsUInt64 join_runtime_filter_min_probe_rows;
extern const SettingsBool join_runtime_filter_size_from_hash_table_stats;
+ extern const SettingsBool join_runtime_filter_skip_ineffective;+ extern const SettingsDouble join_runtime_filter_skip_ineffective_pass_ratio;
extern const SettingsUInt64 max_bytes_to_transfer;
extern const SettingsUInt64 max_limit_for_vector_search_queries;
extern const SettingsUInt64 max_rows_to_transfer;
@@ -469,6 +471,8 @@ QueryPlanOptimizationSettings::QueryPlanOptimizationSettings(
join_runtime_bloom_filter_max_ratio_of_set_bits = from[Setting::join_runtime_bloom_filter_max_ratio_of_set_bits];
join_runtime_filter_min_probe_rows = from[Setting::join_runtime_filter_min_probe_rows];
join_runtime_filter_size_from_hash_table_stats = from[Setting::join_runtime_filter_size_from_hash_table_stats];
+ join_runtime_filter_skip_ineffective = from[Setting::join_runtime_filter_skip_ineffective];+ join_runtime_filter_skip_ineffective_pass_ratio = from[Setting::join_runtime_filter_skip_ineffective_pass_ratio];
query_plan_optimize_join_order_algorithm = from[Setting::query_plan_optimize_join_order_algorithm];
query_plan_optimize_join_order_conflict_detector = from[Setting::query_plan_optimize_join_order_conflict_detector];
diff --git a/src/Processors/QueryPlan/Optimizations/QueryPlanOptimizationSettings.h b/src/Processors/QueryPlan/Optimizations/QueryPlanOptimizationSettings.h
index e48b6792798..614d6afe041 100644
--- a/src/Processors/QueryPlan/Optimizations/QueryPlanOptimizationSettings.h+++ b/src/Processors/QueryPlan/Optimizations/QueryPlanOptimizationSettings.h@@ -284,6 +284,8 @@ struct QueryPlanOptimizationSettings
Float64 join_runtime_bloom_filter_max_ratio_of_set_bits = 0.7;
UInt64 join_runtime_filter_min_probe_rows = 1000;
bool join_runtime_filter_size_from_hash_table_stats = false;
+ bool join_runtime_filter_skip_ineffective = false;+ Float64 join_runtime_filter_skip_ineffective_pass_ratio = 0.95;
std::vector<JoinOrderAlgorithm> query_plan_optimize_join_order_algorithm;
diff --git a/src/Processors/QueryPlan/Optimizations/joinRuntimeFilter.cpp b/src/Processors/QueryPlan/Optimizations/joinRuntimeFilter.cpp
index 01133a4ee34..beea0498379 100644
--- a/src/Processors/QueryPlan/Optimizations/joinRuntimeFilter.cpp+++ b/src/Processors/QueryPlan/Optimizations/joinRuntimeFilter.cpp@@ -14,10 +14,13 @@
#include <Interpreters/Context.h>
#include <Interpreters/HashTablesStatistics.h>
#include <Processors/QueryPlan/BuildRuntimeFilterStep.h>
+#include <Processors/QueryPlan/RuntimeFilterStatistics.h>+#include <Common/ProfileEvents.h>
#include <Processors/QueryPlan/ExpressionStep.h>
#include <Processors/QueryPlan/FilterStep.h>
#include <Processors/QueryPlan/JoinStepLogical.h>
#include <Processors/QueryPlan/ReadFromMergeTree.h>
+#include <Processors/QueryPlan/SourceStepWithFilter.h>
#include <Processors/QueryPlan/Optimizations/Optimizations.h>
#include <Processors/QueryPlan/Optimizations/Utils.h>
#include <Processors/QueryPlan/Optimizations/actionsDAGUtils.h>
@@ -28,6 +31,11 @@
#include <Common/thread_local_rng.h>
+namespace ProfileEvents+{+ extern const Event RuntimeFiltersSkippedAsIneffective;+}+
namespace DB
{
@@ -154,7 +162,9 @@ static const ActionsDAG::Node & addJoinKeyRuntimeFilter(
const RuntimeFilterGeometry & filter_geometry,
bool check_left_does_not_contain,
std::optional<UInt64> distinct_keys_hint,
- bool distinct_keys_hint_matches_filter_key)+ bool distinct_keys_hint_matches_filter_key,+ UInt64 statistics_key,+ UInt64 statistics_geometry)
{
LOG_TRACE(
getLogger("joinRuntimeFilter"),
@@ -179,7 +189,10 @@ static const ActionsDAG::Node & addJoinKeyRuntimeFilter(
.polarity = check_left_does_not_contain ? RuntimeFilterPolarity::NotContains : RuntimeFilterPolarity::Contains,
.track_key_range = optimization_settings.enable_join_runtime_filters_index_analysis,
.distinct_keys_hint = distinct_keys_hint,
- .distinct_keys_hint_matches_filter_key = distinct_keys_hint_matches_filter_key});+ .distinct_keys_hint_matches_filter_key = distinct_keys_hint_matches_filter_key,+ .statistics_key = statistics_key,+ .max_entries_for_statistics = statistics_key ? optimization_settings.max_entries_for_hash_table_stats : 0,+ .statistics_geometry = statistics_geometry});
new_build_filter_node->step->setStepDescription(fmt::format("Build runtime join filter on {}", join_key_build_side.name), 200);
new_build_filter_node->children = {build_filter_node};
build_filter_node = new_build_filter_node;
@@ -286,6 +299,147 @@ static size_t countHashTableKeys(const JoinStepLogical & join_step)
return count;
}
+/// Upper bound of the bytes of variable-size constants that `runtimeFilterJoinIdentity` hashes.+static constexpr size_t MAX_CONSTANT_BYTES_IN_JOIN_IDENTITY = 1 << 20;++/// The join that observations of its runtime filters belong to: the join with both of its inputs, as its output cache key+/// identifies them, and the values of all constants in the actions of the join and of both inputs. The cache keys leave+/// out the values of variable-size constants, so without them `WHERE s = 'a'` and `WHERE s = 'b'` on either side (or two+/// values of a query parameter) would share an observation. The filters that other joins added to the inputs are left+/// out, so that skipping one of them does not change the identity of this join. 0 if the join has no cache key or its+/// constants are too large to hash cheaply: then the filters of this join are neither observed nor skipped.+static UInt64 runtimeFilterJoinIdentity(+ const JoinStepLogical & join_step, const QueryPlan::Node & probe_input, const QueryPlan::Node & build_input)+{+ const UInt64 output_key = join_step.getJoinOutputCacheKey();+ const UInt64 right_key = join_step.getRightHashTableCacheKey();+ if (!output_key || !right_key)+ return 0;++ SipHash hash;+ hash.update(output_key);+ hash.update(right_key);++ size_t constant_bytes = 0;+ /// Returns false if the constants are too large.+ auto add_actions = [&](const ActionsDAG & dag)+ {+ for (const auto & dag_node : dag.getNodes())+ {+ /// A filter added by another join, see above.+ if (dag_node.is_runtime_filter_id)+ return true;+ if (dag_node.column && !dag_node.column->valuesHaveFixedSize())+ constant_bytes += dag_node.column->byteSize();+ }+ if (constant_bytes > MAX_CONSTANT_BYTES_IN_JOIN_IDENTITY)+ return false;+ dag.updateHash(hash, /*build_independent=*/false, /*input_header=*/nullptr, /*with_variable_size_constant_values=*/true);+ return true;+ };++ if (!add_actions(join_step.getActionsDAG()))+ return 0;++ std::vector<const QueryPlan::Node *> stack{&probe_input, &build_input};+ while (!stack.empty())+ {+ const QueryPlan::Node * plan_node = stack.back();+ stack.pop_back();+ for (const auto * child : plan_node->children)+ stack.push_back(child);++ const IQueryPlanStep * step = plan_node->step.get();+ bool small_enough = true;+ if (const auto * expression = typeid_cast<const ExpressionStep *>(step))+ small_enough = add_actions(expression->getExpression());+ else if (const auto * filter = typeid_cast<const FilterStep *>(step))+ small_enough = add_actions(filter->getExpression());+ else if (const auto * join = typeid_cast<const JoinStepLogical *>(step))+ small_enough = add_actions(join->getActionsDAG());+ else if (const auto * read = dynamic_cast<const SourceStepWithFilterBase *>(step))+ {+ if (const auto & filter_dag = read->getFilterActionsDAG())+ small_enough = add_actions(*filter_dag);+ if (auto prewhere = read->getPrewhereInfo(); small_enough && prewhere)+ small_enough = add_actions(prewhere->prewhere_actions);+ if (auto row_level_filter = read->getRowLevelFilter(); small_enough && row_level_filter)+ small_enough = add_actions(row_level_filter->actions);+ }++ if (!small_enough)+ return 0;+ }++ const UInt64 identity = hash.get64();+ return identity ? identity : 1;+}++/// The statistics key of a runtime filter: the join (`runtimeFilterJoinIdentity`) and the actual build and probe key columns.+static UInt64 runtimeFilterStatisticsKey(UInt64 join_identity, const String & build_key_name, const String & probe_key_name)+{+ if (!join_identity)+ return 0;+ SipHash hash;+ hash.update(join_identity);+ hash.update(build_key_name);+ hash.update(probe_key_name);+ const UInt64 key = hash.get64();+ return key ? key : 1;+}++/// What the size and the number of hash functions of a Bloom filter are chosen from (see `BuildRuntimeFilterTransform`).+static UInt64 runtimeFilterGeometryFingerprint(+ const RuntimeFilterGeometry & geometry, std::optional<UInt64> distinct_keys_hint, bool distinct_keys_hint_matches_filter_key)+{+ SipHash hash;+ hash.update(geometry.exact_values_limit);+ hash.update(geometry.bloom_filter_bytes);+ hash.update(geometry.bloom_filter_hash_functions);+ hash.update(geometry.max_ratio_of_set_bits_in_bloom_filter);+ hash.update(distinct_keys_hint.has_value());+ hash.update(distinct_keys_hint.value_or(0));+ hash.update(distinct_keys_hint_matches_filter_key);+ return hash.get64();+}++/// Whether the last run that built this runtime filter saw it filter out almost nothing (see `RuntimeFilterEntry`).+/// Such a filter is built again after `RUNTIME_FILTER_SKIPS_BEFORE_REBUILD` skips, or when the observation is older than+/// `RUNTIME_FILTER_OBSERVATION_MAX_AGE_SECONDS`, to refresh the observation.+///+/// A dropped key set is used only for the same geometry. A pass ratio is used for any: a Bloom filter that keeps its keys+/// has at most `join_runtime_bloom_filter_max_ratio_of_set_bits` of its bits set, so with the default 0.7 and 3 hash+/// functions at most 0.34 of the rows that do not match pass it, and a filter whose pass ratio is above 0.95 with one size+/// passes more than 0.92 with any other. The dynamic disabling turns such a filter off for most blocks anyway.+static bool skipIneffectiveRuntimeFilter(+ UInt64 statistics_key, UInt64 statistics_geometry, const QueryPlanOptimizationSettings & optimization_settings)+{+ const StatsCollectingParams params{+ statistics_key,+ /*enable_=*/true,+ optimization_settings.max_entries_for_hash_table_stats,+ optimization_settings.max_size_to_preallocate_for_joins};+ auto & statistics = getHashTablesStatistics<RuntimeFilterEntry>();+ const auto entry = statistics.getSizeHint(params);+ if (!entry || entry->skipped_runs >= RUNTIME_FILTER_SKIPS_BEFORE_REBUILD)+ return false;+ if (runtimeFilterObservationTime() > entry->observed_at + RUNTIME_FILTER_OBSERVATION_MAX_AGE_SECONDS)+ return false;+ const bool dropped_with_same_geometry = entry->key_set_dropped && entry->geometry == statistics_geometry;+ if (!dropped_with_same_geometry && entry->pass_ratio <= optimization_settings.join_runtime_filter_skip_ineffective_pass_ratio)+ return false;++ /// EXPLAIN shows the plan that would run, but must not count as a run.+ if (optimization_settings.is_explain)+ return true;++ auto updated_entry = *entry;+ ++updated_entry.skipped_runs;+ statistics.update(updated_entry, params);+ ProfileEvents::increment(ProfileEvents::RuntimeFiltersSkippedAsIneffective);+ return true;+}+
bool tryAddJoinRuntimeFilter(QueryPlan::Node & node, QueryPlan::Nodes & nodes, const QueryPlanOptimizationSettings & optimization_settings)
{
/// Is this a join step?
@@ -617,8 +771,21 @@ bool tryAddJoinRuntimeFilter(QueryPlan::Node & node, QueryPlan::Nodes & nodes, c
{
/// Standard per-column runtime filters (for INNER, SEMI, RIGHT, and single-key ANTI joins)
ActionsDAG::NodeRawConstPtrs all_filter_conditions;
+ const bool distinct_keys_hint_matches_filter_key = hash_table_keys_count == 1;+ UInt64 join_identity = 0;+ UInt64 statistics_geometry = 0;+ if (optimization_settings.join_runtime_filter_skip_ineffective && optimization_settings.collect_hash_table_stats_during_joins)+ {+ join_identity = runtimeFilterJoinIdentity(*join_step, *apply_filter_node, *build_filter_node);+ statistics_geometry = runtimeFilterGeometryFingerprint(filter_geometry, distinct_keys_hint, distinct_keys_hint_matches_filter_key);+ }+
for (size_t i = 0; i < join_keys_build_side.size(); ++i)
{
+ const UInt64 statistics_key = runtimeFilterStatisticsKey(join_identity, join_keys_build_side[i].name, join_keys_probe_side[i].name);+ if (statistics_key && skipIneffectiveRuntimeFilter(statistics_key, statistics_geometry, optimization_settings))+ continue;+
auto id = make_id(i);
const auto & join_key_build_side = join_keys_build_side[i];
@@ -638,12 +805,18 @@ bool tryAddJoinRuntimeFilter(QueryPlan::Node & node, QueryPlan::Nodes & nodes, c
filter_geometry,
check_left_does_not_contain,
distinct_keys_hint,
- /*distinct_keys_hint_matches_filter_key=*/hash_table_keys_count == 1);+ distinct_keys_hint_matches_filter_key,+ statistics_key,+ statistics_geometry);
all_filter_conditions.push_back(
check_left_does_not_contain ? addNullBypassForAntiJoin(filter_dag, &filter_condition, {join_key_probe_side})
: &filter_condition);
}
+ /// Every filter was skipped as ineffective, nothing has been added to the plan.+ if (all_filter_conditions.empty())+ return false;+
if (all_filter_conditions.size() == 1)
{
filter_dag.addOrReplaceInOutputs(*all_filter_conditions.front());
diff --git a/src/Processors/QueryPlan/RuntimeFilterBuildOptions.h b/src/Processors/QueryPlan/RuntimeFilterBuildOptions.h
index e8064672723..340492fc8a8 100644
--- a/src/Processors/QueryPlan/RuntimeFilterBuildOptions.h+++ b/src/Processors/QueryPlan/RuntimeFilterBuildOptions.h@@ -16,6 +16,11 @@ struct RuntimeFilterBuildOptions
bool track_key_range;
std::optional<UInt64> distinct_keys_hint;
bool distinct_keys_hint_matches_filter_key;
+ /// Non-zero: record in the hash table statistics under this key whether the filter filtered anything.+ UInt64 statistics_key = 0;+ UInt64 max_entries_for_statistics = 0;+ /// Recorded with the observation, see `RuntimeFilterEntry::geometry`.+ UInt64 statistics_geometry = 0;
};
}
diff --git a/src/Processors/QueryPlan/RuntimeFilterLookup.cpp b/src/Processors/QueryPlan/RuntimeFilterLookup.cpp
index c31d03dbaad..c7cc3db180c 100644
--- a/src/Processors/QueryPlan/RuntimeFilterLookup.cpp+++ b/src/Processors/QueryPlan/RuntimeFilterLookup.cpp@@ -31,6 +31,7 @@
#include <Interpreters/PreparedSets.h>
#include <Processors/QueryPlan/RuntimeFilterBloomSizing.h>
#include <Processors/QueryPlan/RuntimeFilterLookup.h>
+#include <Processors/QueryPlan/RuntimeFilterStatistics.h>
#include <Common/FieldAccurateComparison.h>
#include <Common/FailPoint.h>
#include <Common/MergeLock.h>
@@ -943,6 +944,45 @@ ColumnPtr SharedFixedHashTableRuntimeFilter::find(const ColumnWithTypeAndName &
return probe_fn(values);
}
+RuntimeFilter::~RuntimeFilter()+{+ const auto & config = evaluation_state.getConfig();+ if (!config.statistics_key)+ return;++ try+ {+ /// A filter that prunes data at read time can be useful even if most of the rows that are read pass it.+ if (key_metadata_used.load(std::memory_order_relaxed))+ return;++ const auto & stats = evaluation_state.getStats();+ const Int64 rows_checked = stats.rows_checked.load(std::memory_order_relaxed);+ const Int64 rows_passed = stats.rows_passed.load(std::memory_order_relaxed);+ const bool key_set_dropped = evaluation_state.isKeySetDropped();+ if (!key_set_dropped && rows_checked < MIN_ROWS_CHECKED_TO_JUDGE_RUNTIME_FILTER)+ return;++ const double pass_ratio = rows_checked > 0 ? static_cast<double>(rows_passed) / static_cast<double>(rows_checked) : 1.0;+ LOG_TRACE(+ getLogger("RuntimeFilter"),+ "Observation for statistics key {}: rows checked {}, passed {} ({:.3f}), skipped {}, key set dropped {}",+ config.statistics_key, rows_checked, rows_passed, pass_ratio, stats.rows_skipped.load(std::memory_order_relaxed), key_set_dropped);+ const StatsCollectingParams params{config.statistics_key, /*enable_=*/true, config.max_entries_for_statistics, /*max_size_to_preallocate_=*/0};+ getHashTablesStatistics<RuntimeFilterEntry>().update(+ {.pass_ratio = pass_ratio,+ .key_set_dropped = key_set_dropped,+ .skipped_runs = 0,+ .geometry = config.statistics_geometry,+ .observed_at = runtimeFilterObservationTime()},+ params);+ }+ catch (...)+ {+ tryLogCurrentException(__PRETTY_FUNCTION__);+ }+}+
RuntimeFilter::RuntimeFilter(RuntimeFilterConfig config_, Data data_)
: filter_column_target_type(std::visit([](const auto & filter) { return filter.getTargetType(); }, data_.filter))
, evaluation_state(std::move(config_))
@@ -1040,20 +1080,26 @@ void RuntimeFilter::enableIndexAnalysis()
data.index_analysis.enable();
}
-ColumnPtr RuntimeFilter::getRecordedKeyValues() const+ColumnPtr RuntimeFilter::getRecordedKeyValues(bool mark_used) const
{
SharedLockGuard lock(mutex);
if (!data.index_analysis.canUseExactValues() || !data.build_state.isFinished())
return nullptr;
- return std::visit([](const auto & filter) { return filter.getRecordedKeyValues(); }, data.filter);+ auto values = std::visit([](const auto & filter) { return filter.getRecordedKeyValues(); }, data.filter);+ if (values && mark_used)+ key_metadata_used.store(true, std::memory_order_relaxed);+ return values;
}
-std::optional<Range> RuntimeFilter::getRecordedKeyRanges() const+std::optional<Range> RuntimeFilter::getRecordedKeyRanges(bool mark_used) const
{
SharedLockGuard lock(mutex);
if (!data.build_state.isFinished())
return {};
- return data.index_analysis.getRange();+ auto range = data.index_analysis.getRange();+ if (range && mark_used)+ key_metadata_used.store(true, std::memory_order_relaxed);+ return range;
}
template class ExactSetRuntimeFilter<false>;
diff --git a/src/Processors/QueryPlan/RuntimeFilterLookup.h b/src/Processors/QueryPlan/RuntimeFilterLookup.h
index deca897099c..2599c654719 100644
--- a/src/Processors/QueryPlan/RuntimeFilterLookup.h+++ b/src/Processors/QueryPlan/RuntimeFilterLookup.h@@ -47,6 +47,10 @@ struct RuntimeFilterConfig
{
const Float64 pass_ratio_threshold_for_disabling = 0.7;
const UInt64 blocks_to_skip_before_reenabling = 30;
+ /// Non-zero: when the filter is destroyed, record under this key whether it filtered anything (see `RuntimeFilterEntry`).+ const UInt64 statistics_key = 0;+ const UInt64 max_entries_for_statistics = 0;+ const UInt64 statistics_geometry = 0;
};
namespace detail
@@ -125,6 +129,7 @@ public:
const RuntimeFilterStats & getStats() const { return stats; }
const RuntimeFilterConfig & getConfig() const { return config; }
void markKeySetDropped() { key_set_dropped = true; }
+ bool isKeySetDropped() const { return key_set_dropped.load(); }
/// Checks if a block should bypass the filter because its key set was dropped or evaluation is temporarily throttled.
bool shouldSkip(size_t next_block_rows) const;
@@ -395,6 +400,9 @@ public:
{
}
+ /// Records whether the filter filtered anything, see `RuntimeFilterConfig::statistics_key`.+ ~RuntimeFilter();+
void insert(ColumnPtr values);
/// No more inserts after this call, only finds.
@@ -416,8 +424,8 @@ public:
/// Opt in to collecting build-side metadata for storage index analysis.
void enableIndexAnalysis();
- ColumnPtr getRecordedKeyValues() const;- std::optional<Range> getRecordedKeyRanges() const;+ ColumnPtr getRecordedKeyValues(bool mark_used = true) const;+ std::optional<Range> getRecordedKeyRanges(bool mark_used = true) const;
DataTypePtr getFilterColumnTargetType() const { return filter_column_target_type; }
/// Usage statistics
@@ -428,6 +436,8 @@ private:
const DataTypePtr filter_column_target_type;
RuntimeFilterEvaluationState evaluation_state;
+ /// Set when a reader took the build-side keys to prune data at read time (not when they are only copied).+ mutable std::atomic<bool> key_metadata_used = false;
mutable SharedMutex mutex;
Data data TSA_GUARDED_BY(mutex);
};
diff --git a/src/Processors/QueryPlan/RuntimeFilterStatistics.h b/src/Processors/QueryPlan/RuntimeFilterStatistics.h
new file mode 100644
index 00000000000..141dc4cf05d
--- /dev/null+++ b/src/Processors/QueryPlan/RuntimeFilterStatistics.h@@ -0,0 +1,58 @@+#pragma once++#include <base/types.h>+#include <fmt/format.h>++#include <chrono>+#include <string>++namespace DB+{++/// What the last run that built a JOIN runtime filter observed about it (see `join_runtime_filter_skip_ineffective`).+/// Kept in the hash table statistics cache under `runtimeFilterStatisticsKey`.+struct RuntimeFilterEntry+{+ bool shouldBeUpdated(const RuntimeFilterEntry & new_entry) const+ {+ return new_entry.pass_ratio != pass_ratio || new_entry.key_set_dropped != key_set_dropped || new_entry.skipped_runs != skipped_runs+ || new_entry.geometry != geometry || new_entry.observed_at != observed_at;+ }++ std::string dump() const+ {+ return fmt::format(+ "pass_ratio={}, key_set_dropped={}, skipped_runs={}, geometry={}, observed_at={}",+ pass_ratio, key_set_dropped, skipped_runs, geometry, observed_at);+ }++ /// The share of the checked rows that passed the filter.+ double pass_ratio = 0;+ /// The Bloom filter was dropped as too full, so it let every row pass.+ bool key_set_dropped = false;+ /// Runs that skipped the filter since it was last built.+ size_t skipped_runs = 0;+ /// What the size of the filter was chosen from in the run that made the observation (`runtimeFilterGeometryFingerprint`).+ /// A Bloom filter that was dropped as too full can keep its keys with another size, so `key_set_dropped` is used only+ /// for the same geometry.+ UInt64 geometry = 0;+ /// When the observation was made, see `runtimeFilterObservationTime`.+ UInt64 observed_at = 0;+};++/// An ineffective filter is built again after this many skips, so that a change of the data is noticed.+inline constexpr size_t RUNTIME_FILTER_SKIPS_BEFORE_REBUILD = 16;++/// An observation older than this is not used, so that a change of the data is noticed in a query that runs rarely.+inline constexpr UInt64 RUNTIME_FILTER_OBSERVATION_MAX_AGE_SECONDS = 3600;++/// A filter that checked fewer rows than this (and kept its key set) gives no evidence either way.+inline constexpr Int64 MIN_ROWS_CHECKED_TO_JUDGE_RUNTIME_FILTER = 10000;++/// Seconds of a monotonic clock, for `RuntimeFilterEntry::observed_at`.+inline UInt64 runtimeFilterObservationTime()+{+ return static_cast<UInt64>(std::chrono::duration_cast<std::chrono::seconds>(std::chrono::steady_clock::now().time_since_epoch()).count());+}++}diff --git a/src/Processors/Transforms/BuildRuntimeFilterTransform.cpp b/src/Processors/Transforms/BuildRuntimeFilterTransform.cpp
index d45d24b4796..8e6fb0f433b 100644
--- a/src/Processors/Transforms/BuildRuntimeFilterTransform.cpp+++ b/src/Processors/Transforms/BuildRuntimeFilterTransform.cpp@@ -38,7 +38,12 @@ BuildRuntimeFilterTransform::BuildRuntimeFilterTransform(
cast_to_target_type = createInternalCast(filter_column, filter_column_target_type, CastType::nonAccurate, {}, nullptr);
const auto & geometry = build_options_.geometry;
- const RuntimeFilterConfig runtime_filter_config{geometry.pass_ratio_threshold_for_disabling, geometry.blocks_to_skip_before_reenabling};+ const RuntimeFilterConfig runtime_filter_config{+ geometry.pass_ratio_threshold_for_disabling,+ geometry.blocks_to_skip_before_reenabling,+ build_options_.statistics_key,+ build_options_.max_entries_for_statistics,+ build_options_.statistics_geometry};
if (build_options_.polarity == RuntimeFilterPolarity::Contains)
{
diff --git a/tests/queries/0_stateless/03580_join_runtime_filter.sql.j2 b/tests/queries/0_stateless/03580_join_runtime_filter.sql.j2
index a85ad4485f8..044aff29c34 100644
--- a/tests/queries/0_stateless/03580_join_runtime_filter.sql.j2+++ b/tests/queries/0_stateless/03580_join_runtime_filter.sql.j2@@ -19,6 +19,7 @@ INSERT INTO customer SELECT number, 202 FROM numbers(2);
INSERT INTO orders SELECT number, number/10000, number%1000 FROM numbers(1000000);
SET enable_join_runtime_filters=1, join_runtime_filter_min_probe_rows = 0;
+SET join_runtime_filter_skip_ineffective = 0; -- The test checks EXPLAIN after running the same joins
SET enable_parallel_replicas=0;
SET query_plan_optimize_join_order_algorithm='greedy';
SET query_plan_optimize_join_order_limit=1;
diff --git a/tests/queries/0_stateless/05497_join_runtime_filter_skip_ineffective.reference b/tests/queries/0_stateless/05497_join_runtime_filter_skip_ineffective.reference
new file mode 100644
index 00000000000..aa9df483939
--- /dev/null+++ b/tests/queries/0_stateless/05497_join_runtime_filter_skip_ineffective.reference@@ -0,0 +1,18 @@+300000 600000 899982+300000 600000 899982+300000 600000 899982+42858 85710+42858 85710+60000 120000 180012+300000 600000+300000 600000+42852 85704+05497_first 0 1+05497_second 1 0+05497_disabled 0 1+05497_selective_1 0 1+05497_selective_2 0 1+05497_other_probe 0 1+05497_string_all_1 0 1+05497_string_all_2 1 0+05497_string_selective 0 1diff --git a/tests/queries/0_stateless/05497_join_runtime_filter_skip_ineffective.sql b/tests/queries/0_stateless/05497_join_runtime_filter_skip_ineffective.sql
new file mode 100644
index 00000000000..0ecfd7a1167
--- /dev/null+++ b/tests/queries/0_stateless/05497_join_runtime_filter_skip_ineffective.sql@@ -0,0 +1,43 @@+-- Tags: no-random-settings, no-random-merge-tree-settings, no-parallel-replicas+-- A runtime filter built from the primary-key side of a join filters nothing on the foreign-key side.+-- The first run records that, the second run does not build it, and results stay the same.+-- The observation belongs to that join only: the same build side with another probe side, or with+-- another String constant, keeps its filter.++SET enable_analyzer = 1;+SET enable_join_runtime_filters = 1, join_runtime_filter_min_probe_rows = 0;+SET collect_hash_table_stats_during_joins = 1, join_runtime_filter_skip_ineffective = 1;++DROP TABLE IF EXISTS fk_side;+DROP TABLE IF EXISTS fk_other;+DROP TABLE IF EXISTS pk_side;+CREATE TABLE pk_side (k UInt64, w UInt64, s String) ENGINE = Memory;+CREATE TABLE fk_side (k UInt64, v UInt64) ENGINE = Memory;+CREATE TABLE fk_other (k UInt64, v UInt64) ENGINE = Memory;+INSERT INTO pk_side SELECT number, number % 7, toString(number % 7) FROM numbers(50000);+INSERT INTO fk_side SELECT number % 50000, number % 5 FROM numbers(300000);+-- Only a fifth of these keys are in pk_side.+INSERT INTO fk_other SELECT number % 50000 + 40000, number % 5 FROM numbers(300000);++SELECT count(), sum(v), sum(w) FROM fk_side INNER JOIN pk_side ON fk_side.k = pk_side.k SETTINGS log_comment = '05497_first';+SELECT count(), sum(v), sum(w) FROM fk_side INNER JOIN pk_side ON fk_side.k = pk_side.k SETTINGS log_comment = '05497_second';+SELECT count(), sum(v), sum(w) FROM fk_side INNER JOIN pk_side ON fk_side.k = pk_side.k SETTINGS log_comment = '05497_disabled', join_runtime_filter_skip_ineffective = 0;+-- A filter that does filter is kept.+SELECT count(), sum(v) FROM fk_side INNER JOIN (SELECT * FROM pk_side WHERE w = 3) AS d ON fk_side.k = d.k SETTINGS log_comment = '05497_selective_1';+SELECT count(), sum(v) FROM fk_side INNER JOIN (SELECT * FROM pk_side WHERE w = 3) AS d ON fk_side.k = d.k SETTINGS log_comment = '05497_selective_2';+-- The same build side and key columns with another probe side.+SELECT count(), sum(v), sum(w) FROM fk_other AS fk_side INNER JOIN pk_side ON fk_side.k = pk_side.k SETTINGS log_comment = '05497_other_probe';+-- Build sides that differ only in a String constant.+SELECT count(), sum(v) FROM fk_side INNER JOIN (SELECT * FROM pk_side WHERE s >= '0') AS d ON fk_side.k = d.k SETTINGS log_comment = '05497_string_all_1';+SELECT count(), sum(v) FROM fk_side INNER JOIN (SELECT * FROM pk_side WHERE s >= '0') AS d ON fk_side.k = d.k SETTINGS log_comment = '05497_string_all_2';+SELECT count(), sum(v) FROM fk_side INNER JOIN (SELECT * FROM pk_side WHERE s >= '6') AS d ON fk_side.k = d.k SETTINGS log_comment = '05497_string_selective';++SYSTEM FLUSH LOGS query_log;+SELECT log_comment, ProfileEvents['RuntimeFiltersSkippedAsIneffective'] AS skipped, ProfileEvents['RuntimeFilterRowsChecked'] > 0 AS checked+FROM system.query_log+WHERE current_database = currentDatabase() AND log_comment LIKE '05497_%' AND type = 'QueryFinish'+ORDER BY event_time_microseconds;++DROP TABLE fk_side;+DROP TABLE fk_other;+DROP TABLE pk_side;
Activity
il9ue commentedon Feb 20, 2026
Let me try to investigate this interesting feature!
Introduce statistics-based disabling of join runtime filters (ClickHo…
snelheidai commentedon Nov 3, 2026
Here is an observation-based way to do this, with measurements and a patch.
The patch skips a JOIN runtime filter when, the last time the same join built it, more than 95% of the rows it checked passed (or its Bloom filter of the same size was dropped as too full). The observation is kept in the hash-table statistics cache, so it needs
collect_hash_table_stats_during_joins. After 16 skips, or an hour after the observation, the filter is built again so that changed data is noticed. It is behindjoin_runtime_filter_skip_ineffective(on by default in the patch).Why observed rather than estimated. In the #97501 review, @rschu1ze leaned towards static disabling only for the build side, because estimating how many probe rows pass needs many assumptions and the dynamic
join_runtime_filter_pass_ratio_threshold_for_disablingrule is the fallback. That fallback still builds the filter on every run, and the cost is not small:store_salesas the build side, its filters are applied tostore_returns, whose rows all have a matching sale, so 4 of them pass almost every row. This is the PK-FK case from this issue, and master's statistics-based build-side check does not fire for these filters (RuntimeFilterBloomFilterBuildsSkippedstays 0). Not building them takes that plan from 3.1 to 2.6 s. An earlier profile put Bloom building in this plan shape at about 2 s of CPU per warm run (q50, q93).An observed pass ratio needs no NDV or containment assumptions. It complements a build-side estimate such as #97501's, which can act on the first run.
Iceberg TPC-DS SF10, warm. One binary (master 230ae8e + #128139 + patch), setting off vs on: median ms, change of paired runs with 95% CI.
What counts as the same join. An observation is reused only by the same join over the same inputs: the same hash-table-statistics output key (it covers both inputs), the same values of all constants in the actions of the join and of both inputs (including String literals and query parameters, which the statistics keys leave out), and the same build and probe key columns. A dropped key set is reused only with the same Bloom size inputs. A pass ratio is reused with any size: with the default 3 hash functions and at most 70% of its bits set, a Bloom filter passes at most 34% of the non-matching rows, so more than 95% passing with one size means more than 92% with any other. On Iceberg and in the new test
05497_join_runtime_filter_skip_ineffective, a selective query that runs after a non-selective one with the same build side and key columns, but with another probe side or another String literal, keeps its filter in every run, with unchanged latency.Depends on #128139 (open). Without it, q07, q47, q70 and q86 are 7–10% slower with the setting on; with it they are unchanged. The dynamic rule had already switched those filters off for most rows; earlier profiling pointed at the scattered Parquet decoding of the join-key column, which #128139 makes dense.
Limits.
03580_join_runtime_filternow pins the setting off, because it checks EXPLAIN after running the same joins). One 4-vCPU x86 host, SF10, local files.@m-selmi @rschu1ze would a PR along these lines be welcome, next to #97501?
Method
IcebergLocaltables (Parquet, unpartitioned, rows sorted by each table's sorting key).tests/benchmarks/tpc-ds/querieswithdata_type_default_nullable=1, group_by_use_nulls=1, join_use_nulls=1, union_default_mode='DISTINCT', intersect_default_mode='DISTINCT', joined_subquery_requires_alias=0. All other settings are defaults, so runtime filters and hash-table statistics are on.join_runtime_filter_skip_ineffective = 0. For each query: one warm-up per server (results compared), then N pairs in alternating order. Metric:query_duration_msfromsystem.query_log; geometric mean of the paired ratios with a Student-t 95% interval. "2 × 7" means two sessions of 7 pairs with the servers' roles swapped.store_salesjoined withitem, then the same join with the probe keys shifted by 51000 (about half match): 0 skips in every run, on/off 1.02 [0.98, 1.07]. Build sideitem WHERE i_category >= 'A', then>= 'Sports': 0 skips, 1.02 [0.97, 1.08].Patch (against master 230ae8e)