Skip to content

Commit ad32f3c

Browse files
groeneaiclaude
andcommitted
Record the static PREWHERE conditions of a join with a runtime filter in the query condition cache
A join runtime filter is pushed into the probe side's PREWHERE together with the static `WHERE` conditions, e.g. `and(in(c1, ...), __applyFilter(rf_c1, c1), __applyFilter(rf_c2, c2))`. `__applyFilter` is non-deterministic on purpose, so the PREWHERE writer refuses the whole condition, and the `WHERE` key set by `updateQueryConditionCache` is lost when the forced filter merges fuse the runtime filter step with the `WHERE` step. Nothing records the static conjunct, so with `enable_join_runtime_filters_index_analysis = 0` (the 26.6 default) a repeated join reads every granule on every run: 8,639,765 rows per run instead of 311,335 on the reporter's fixture. When the PREWHERE is such a mix, `optimizePrewhere` now finds the leading conjuncts that are, structurally, conjuncts of the frozen `filter_actions_dag`. They are compared by a hash taken after collapsing aliases and applying the identifier-to-column mapping `applyFilters` used, because the PREWHERE reads `c1` through `__table1.c1` while the frozen condition reads `c1` directly. The `PrewhereInfo` then carries the key the read side already probes for that condition and the hashes of those conjuncts. `tryBuildPrewhereSteps` keeps them in steps of their own (it would otherwise group `in(c1, ...)` with `__applyFilter(rf_c1, c1)`, which read the same column) and flags the last one; a later rewrite of the PREWHERE actions fails the hash check and installs no flag. The readers chain snapshots the granules emptied up to that step, and the select processor records them under the key at the end of a task, only when there is something to record, since an empty write still creates an entry. Granules emptied by the runtime filter or by any later conjunct are never recorded, including a conjunct that join push-down adds after the key was fixed. A PREWHERE whose conjuncts are all attributable is unchanged, and so are its key and its entry count. Measured on the reporter's fixture (plain `MergeTree`/`AggregatingMergeTree`, 8.64M rows), median of 5, debug build, `enable_join_runtime_filters_index_analysis = 0`: runs 2 and 3 read 311,335 rows instead of 8,639,765, and `RuntimeFilterRowsChecked` drops from 8,639,728 to 4 because the runtime filter now sees only rows that passed the static conjunct. With the index analysis on (the master default) and join keys in the primary key, the runtime filter's own mark-skipping reader already prunes to 319,527 rows and the existing guard against such readers keeps the PREWHERE writes off, as before. The separate JOIN plus double-PREWHERE key desync that also costs `enable_join_runtime_filters = 0` its hits is left to its own fix. Related: #122044 Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 711f560 commit ad32f3c

11 files changed

Lines changed: 363 additions & 18 deletions

‎src/Processors/QueryPlan/Optimizations/optimizePrewhere.cpp‎

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
#include <Functions/FunctionsLogical.h>
66
#include <Functions/IFunctionAdaptors.h>
77
#include <Interpreters/ActionsDAG.h>
8+
#include <Interpreters/Cache/QueryConditionCache.h>
89
#include <Interpreters/Context.h>
910
#include <Processors/QueryPlan/ExpressionStep.h>
1011
#include <Processors/QueryPlan/FilterStep.h>
@@ -16,6 +17,7 @@
1617
#include <Storages/MergeTree/MergeTreeWhereOptimizer.h>
1718
#include <Storages/StorageDummy.h>
1819
#include <Storages/StorageMerge.h>
20+
#include <Storages/VirtualColumnUtils.h>
1921
#include <Common/Exception.h>
2022

2123
namespace DB
@@ -26,6 +28,7 @@ namespace Setting
2628
extern const SettingsBool optimize_move_to_prewhere;
2729
extern const SettingsBool optimize_move_to_prewhere_if_final;
2830
extern const SettingsBool optimize_prewhere_after_pushdown;
31+
extern const SettingsBool use_query_condition_cache;
2932
extern const SettingsBool vector_search_with_rescoring;
3033
}
3134

@@ -175,6 +178,78 @@ ActionsDAG splitAndFillPrewhereInfo(
175178
return std::move(split_result.second);
176179
}
177180

181+
/// Hash of `node` with aliases collapsed and column identifiers mapped to storage columns, as
182+
/// `ReadFromMergeTree::applyFilters` does, so it does not depend on the renames the node reads through.
183+
static std::optional<UInt64> getNormalizedHash(
184+
const ActionsDAG::Node * node, const std::unordered_map<std::string, ColumnWithTypeAndName> & node_name_to_input_node_column)
185+
{
186+
try
187+
{
188+
auto dag = ActionsDAG::cloneSubDAG({node}, /*remove_aliases=*/ true);
189+
for (const auto & dag_node : dag.getNodes())
190+
if (dag_node.type == ActionsDAG::ActionType::ARRAY_JOIN || dag_node.type == ActionsDAG::ActionType::PLACEHOLDER)
191+
return {};
192+
193+
auto normalized = ActionsDAG::buildFilterActionsDAG(dag.getOutputs(), node_name_to_input_node_column);
194+
if (!normalized || normalized->getOutputs().size() != 1)
195+
return {};
196+
return normalized->getOutputs()[0]->getHash();
197+
}
198+
catch (const Exception &)
199+
{
200+
return {};
201+
}
202+
}
203+
204+
static void setQueryConditionCacheAttribution(
205+
PrewhereInfo & prewhere_info, const ReadFromMergeTree & read_from_merge_tree_step, const Settings & settings)
206+
{
207+
if (!settings[Setting::use_query_condition_cache] || read_from_merge_tree_step.isSelectedForTopKFilterOptimization()
208+
|| read_from_merge_tree_step.getVectorSearchParameters().has_value())
209+
return;
210+
211+
const auto & query_info = read_from_merge_tree_step.getQueryInfo();
212+
const auto & filter_actions_dag = query_info.filter_actions_dag;
213+
if (!filter_actions_dag || query_info.isFinal()
214+
|| ReadFromMergeTree::filterDependsOnNonDeterministicVirtuals(read_from_merge_tree_step.getStorageMetadata()->virtuals, query_info))
215+
return;
216+
217+
const auto & outputs = filter_actions_dag->getOutputs();
218+
if (outputs.size() != 1 || !VirtualColumnUtils::isDeterministic(outputs.front()))
219+
return;
220+
221+
const auto & condition_root = prewhere_info.prewhere_actions.findInOutputs(prewhere_info.prewhere_column_name);
222+
if (condition_root.type != ActionsDAG::ActionType::FUNCTION || condition_root.function_base->getName() != "and")
223+
return;
224+
225+
auto node_name_to_input_node_column = query_info.buildNodeNameToInputNodeColumn();
226+
std::unordered_set<UInt64> filter_atom_hashes;
227+
for (const auto * atom : ActionsDAG::extractConjunctionAtoms(outputs.front()))
228+
if (auto hash = getNormalizedHash(atom, node_name_to_input_node_column))
229+
filter_atom_hashes.insert(*hash);
230+
231+
std::vector<UInt64> conjunct_hashes;
232+
for (const auto * conjunct : condition_root.children)
233+
{
234+
if (!VirtualColumnUtils::isDeterministic(conjunct))
235+
break;
236+
auto hash = getNormalizedHash(conjunct, node_name_to_input_node_column);
237+
if (!hash || !filter_atom_hashes.contains(*hash))
238+
break;
239+
conjunct_hashes.push_back(conjunct->getHash());
240+
}
241+
242+
/// With every conjunct attributed the ordinary PREWHERE write already covers the read.
243+
if (conjunct_hashes.empty() || conjunct_hashes.size() == condition_root.children.size())
244+
return;
245+
246+
prewhere_info.query_condition_cache_attribution = PrewhereInfo::QueryConditionCacheAttribution{
247+
.key = queryConditionCacheHash(outputs.front()->getHash(), queryConditionCacheSettingsSalt(settings)),
248+
.condition = filter_actions_dag->getNames()[0],
249+
.conjunct_hashes = std::move(conjunct_hashes),
250+
};
251+
}
252+
178253
void optimizePrewhere(QueryPlan::Node & parent_node, const bool remove_unused_columns, const bool suppress_for_vector_search)
179254
{
180255
/// Assume that there are at least 2 nodes:
@@ -289,6 +364,9 @@ void optimizePrewhere(QueryPlan::Node & parent_node, const bool remove_unused_co
289364
optimize_result.prewhere_nodes,
290365
optimize_result.prewhere_nodes_list);
291366

367+
if (!existing_prewhere_info && read_from_merge_tree_step)
368+
setQueryConditionCacheAttribution(*prewhere_info, *read_from_merge_tree_step, settings);
369+
292370
if (existing_prewhere_info)
293371
{
294372
const bool existing_removable = existing_prewhere_info->remove_prewhere_column;

‎src/Storages/MergeTree/MergeTreeRangeReader.h‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,10 @@ struct PrewhereExprStep
5151

5252
/// Version of mutation if step is a part of on-fly mutation.
5353
std::optional<UInt64> mutation_version;
54+
55+
/// The last step of the PREWHERE part covered by `PrewhereInfo::query_condition_cache_attribution`.
56+
/// A flag rather than an index, so that steps prepended to the chain cannot move it.
57+
bool query_condition_cache_attribution_boundary = false;
5458
};
5559

5660
using PrewhereExprStepPtr = std::shared_ptr<PrewhereExprStep>;
@@ -292,6 +296,9 @@ class MergeTreeRangeReader
292296
/// All read marks.
293297
MarkRanges read_mark_ranges;
294298

299+
/// Marks emptied by the steps up to the query condition cache attribution boundary.
300+
MarkRanges query_condition_cache_attributable_marks;
301+
295302
/// The number of rows were added to block as a result of reading chain.
296303
size_t numReadRows() const { return num_read_rows; }
297304
/// The number of bytes read from disk.

‎src/Storages/MergeTree/MergeTreeReadTask.cpp‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -540,6 +540,7 @@ MergeTreeReadTask::BlockAndProgress MergeTreeReadTask::read()
540540
.unmatched_mark_ranges = readers.main->getMergeTreeReaderSettings().use_query_condition_cache
541541
? read_result.computeUnmatchedMarkRanges()
542542
: MarkRanges{},
543+
.query_condition_cache_attributable_marks = std::move(read_result.query_condition_cache_attributable_marks),
543544
.row_count = read_result.num_rows,
544545
.num_read_rows = num_read_rows,
545546
.num_read_bytes = num_read_bytes };
@@ -552,6 +553,11 @@ void MergeTreeReadTask::addPrewhereUnmatchedMarks(const MarkRanges & mark_ranges
552553
prewhere_unmatched_marks.insert(prewhere_unmatched_marks.end(), mark_ranges_.begin(), mark_ranges_.end());
553554
}
554555

556+
void MergeTreeReadTask::addQueryConditionCacheAttributableMarks(const MarkRanges & mark_ranges_)
557+
{
558+
query_condition_cache_attributable_marks.insert(query_condition_cache_attributable_marks.end(), mark_ranges_.begin(), mark_ranges_.end());
559+
}
560+
555561
bool MergeTreeReadTask::readersChainCanSkipMarksBeforePrewhere() const
556562
{
557563
/// Only `prepared_index` (a `MergeTreeReaderIndex`) sits ahead of the PREWHERE readers in the

‎src/Storages/MergeTree/MergeTreeReadTask.h‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,7 @@ struct MergeTreeReadTask : private boost::noncopyable
181181
/// Superset of what addPrewhereUnmatchedMarks recorded with the old coarse approach,
182182
/// because it captures individual filtered-out granules even in partially-passing batches.
183183
MarkRanges unmatched_mark_ranges;
184+
MarkRanges query_condition_cache_attributable_marks;
184185
size_t row_count = 0;
185186
size_t num_read_rows = 0;
186187
size_t num_read_bytes = 0;
@@ -214,6 +215,9 @@ struct MergeTreeReadTask : private boost::noncopyable
214215
void addPrewhereUnmatchedMarks(const MarkRanges & mark_ranges_);
215216
const MarkRanges & getPrewhereUnmatchedMarks() { return prewhere_unmatched_marks; }
216217

218+
void addQueryConditionCacheAttributableMarks(const MarkRanges & mark_ranges_);
219+
const MarkRanges & getQueryConditionCacheAttributableMarks() const { return query_condition_cache_attributable_marks; }
220+
217221
/// Returns true if a reader earlier in the chain than PREWHERE can skip whole marks based on
218222
/// secondary indexes (skip-index or projection-index). When true, marks that appear in
219223
/// `read_mark_ranges` with `row_count == 0` may have been filtered before PREWHERE evaluated
@@ -270,6 +274,7 @@ struct MergeTreeReadTask : private boost::noncopyable
270274

271275
/// Tracks which mark ranges are not matched by PREWHERE (needed for query condition cache)
272276
MarkRanges prewhere_unmatched_marks;
277+
MarkRanges query_condition_cache_attributable_marks;
273278

274279
BlockSizeParams block_size_params;
275280

‎src/Storages/MergeTree/MergeTreeReadersChain.cpp‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -302,6 +302,11 @@ MergeTreeReadersChain::ReadResult MergeTreeReadersChain::read(
302302

303303
auto & first_reader = range_readers.front();
304304

305+
size_t num_attributed_readers = 0;
306+
for (size_t i = 0; i < range_readers.size(); ++i)
307+
if (const auto * step = range_readers[i].getPrewhereInfo(); step && step->query_condition_cache_attribution_boundary)
308+
num_attributed_readers = i + 1;
309+
305310
try
306311
{
307312
read_result = first_reader.startReadingChain(max_rows, ranges);
@@ -331,6 +336,9 @@ MergeTreeReadersChain::ReadResult MergeTreeReadersChain::read(
331336

332337
executePrewhereActions(first_reader, read_result, {}, range_readers.size() == 1);
333338
addPatchVirtuals(read_result, first_reader.getSampleBlock());
339+
340+
if (num_attributed_readers != 0)
341+
read_result.query_condition_cache_attributable_marks = read_result.computeUnmatchedMarkRanges();
334342
}
335343

336344
for (size_t i = 1; i < range_readers.size(); ++i)
@@ -371,6 +379,10 @@ MergeTreeReadersChain::ReadResult MergeTreeReadersChain::read(
371379
}
372380

373381
executePrewhereActions(range_readers[i], read_result, previous_header, i + 1 == range_readers.size());
382+
383+
/// A batch emptied earlier skips this: the snapshot taken then already has every granule.
384+
if (i < num_attributed_readers)
385+
read_result.query_condition_cache_attributable_marks = read_result.computeUnmatchedMarkRanges();
374386
}
375387

376388
applyPatchesAfterReader(read_result, range_readers.size() - 1);

‎src/Storages/MergeTree/MergeTreeSelectProcessor.cpp‎

Lines changed: 35 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -325,11 +325,16 @@ MergeTreeSelectProcessor::readCurrentTask(MergeTreeReadTask & current_task, IMer
325325
/// Some rows survived PREWHERE, but individual granules within this batch may
326326
/// still have been fully filtered out. Record those granules immediately so that
327327
/// future queries can skip them without waiting for an entire batch to be zero.
328-
if (prewhere_info && !res.unmatched_mark_ranges.empty()
328+
if (prewhere_info
329329
&& !current_task.readersChainCanSkipMarksBeforePrewhere()
330330
&& !current_task.appliesMutationsBeforePrewhere()
331331
&& !row_level_filter)
332-
current_task.addPrewhereUnmatchedMarks(res.unmatched_mark_ranges);
332+
{
333+
if (!res.unmatched_mark_ranges.empty())
334+
current_task.addPrewhereUnmatchedMarks(res.unmatched_mark_ranges);
335+
if (!res.query_condition_cache_attributable_marks.empty())
336+
current_task.addQueryConditionCacheAttributableMarks(res.query_condition_cache_attributable_marks);
337+
}
333338
}
334339

335340
return ChunkAndProgress{
@@ -350,7 +355,11 @@ MergeTreeSelectProcessor::readCurrentTask(MergeTreeReadTask & current_task, IMer
350355
&& !current_task.readersChainCanSkipMarksBeforePrewhere()
351356
&& !current_task.appliesMutationsBeforePrewhere()
352357
&& !row_level_filter)
358+
{
353359
current_task.addPrewhereUnmatchedMarks(res.read_mark_ranges);
360+
/// Not `read_mark_ranges`: the steps after the attribution boundary may be what emptied them.
361+
current_task.addQueryConditionCacheAttributableMarks(res.query_condition_cache_attributable_marks);
362+
}
354363

355364
return {Chunk(), res.num_read_rows, res.num_read_bytes, false, std::move(res.read_mark_ranges)};
356365
}
@@ -441,32 +450,42 @@ ChunkAndProgress MergeTreeSelectProcessor::read()
441450
/// QueryConditionCache needs the concrete part's storage UUID; skip for borrowed parts.
442451
&& task->getInfo().data_part_info->getDataPart())
443452
{
453+
const auto & data_part_info = task->getInfo().data_part_info;
454+
auto write_to_query_condition_cache = [&](UInt64 condition_hash, const String & condition, const MarkRanges & marks)
455+
{
456+
String part_name = data_part_info->isProjectionPart()
457+
? fmt::format("{}:{}", data_part_info->getParentPartName(), data_part_info->getPartName())
458+
: data_part_info->getPartName();
459+
Context::getGlobalContextInstance()->getQueryConditionCache()->write(
460+
/// QueryConditionCache is a coordinator feature; concrete part present here.
461+
data_part_info->getDataPart()->storage.getStorageID().uuid,
462+
part_name,
463+
condition_hash,
464+
condition,
465+
marks,
466+
data_part_info->getIndexGranularity().getMarksCount(),
467+
data_part_info->getIndexGranularity().hasFinalMark());
468+
};
469+
444470
for (const auto * output : prewhere_info->prewhere_actions.getOutputs())
445471
{
446472
if (output->result_name == prewhere_info->prewhere_column_name)
447473
{
448474
if (!VirtualColumnUtils::isDeterministic(output))
449475
continue;
450476

451-
auto query_condition_cache = Context::getGlobalContextInstance()->getQueryConditionCache();
452-
const auto & data_part_info = task->getInfo().data_part_info;
453-
454-
String part_name = data_part_info->isProjectionPart()
455-
? fmt::format("{}:{}", data_part_info->getParentPartName(), data_part_info->getPartName())
456-
: data_part_info->getPartName();
457-
query_condition_cache->write(
458-
/// QueryConditionCache is a coordinator feature; concrete part present here.
459-
data_part_info->getDataPart()->storage.getStorageID().uuid,
460-
part_name,
477+
write_to_query_condition_cache(
461478
queryConditionCacheHash(output->getHash(), reader_settings.query_condition_cache_settings_salt),
462479
prewhere_info->prewhere_actions.getNames()[0],
463-
task->getPrewhereUnmatchedMarks(),
464-
data_part_info->getIndexGranularity().getMarksCount(),
465-
data_part_info->getIndexGranularity().hasFinalMark());
466-
480+
task->getPrewhereUnmatchedMarks());
467481
break;
468482
}
469483
}
484+
485+
/// An empty write would still create an entry.
486+
const auto & attribution = prewhere_info->query_condition_cache_attribution;
487+
if (attribution && !task->getQueryConditionCacheAttributableMarks().empty())
488+
write_to_query_condition_cache(attribution->key, attribution->condition, task->getQueryConditionCacheAttributableMarks());
470489
}
471490

472491
task = algorithm->getNewTask(*pool, task.get());

‎src/Storages/MergeTree/MergeTreeSplitPrewhereIntoReadSteps.cpp‎

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -204,6 +204,19 @@ bool tryBuildPrewhereSteps(
204204
return false;
205205
auto condition_nodes = condition_root.children;
206206

207+
/// The leading conditions covered by the query condition cache attribution get steps of their own.
208+
/// A hash mismatch means the PREWHERE actions were rewritten after the attribution was computed.
209+
size_t num_attributed_conditions = 0;
210+
if (const auto & attribution = prewhere_info->query_condition_cache_attribution)
211+
{
212+
const auto & hashes = attribution->conjunct_hashes;
213+
bool matches = !hashes.empty() && hashes.size() < condition_nodes.size();
214+
for (size_t i = 0; matches && i < hashes.size(); ++i)
215+
matches = condition_nodes[i]->getHash() == hashes[i];
216+
if (matches)
217+
num_attributed_conditions = hashes.size();
218+
}
219+
207220
/// 2. Collect the set of columns that are used in the condition
208221
std::unordered_map<const ActionsDAG::Node *, NodeInfo> nodes_info;
209222
for (const auto & node : condition_nodes)
@@ -227,10 +240,16 @@ bool tryBuildPrewhereSteps(
227240
/// For the WHERE-to-PREWHERE path this is not a problem: `MergeTreeWhereOptimizer` already groups
228241
/// conditions by their physical storage columns, so subcolumns of the same column arrive here adjacent.
229242
std::vector<std::vector<const ActionsDAG::Node *>> condition_groups;
230-
for (const auto & node : condition_nodes)
243+
size_t num_attributed_steps = 0;
244+
for (size_t i = 0; i < condition_nodes.size(); ++i)
231245
{
246+
const auto * node = condition_nodes[i];
232247
const auto & node_info = nodes_info[node];
233-
if (!condition_groups.empty()
248+
const bool is_first_unattributed = num_attributed_conditions != 0 && i == num_attributed_conditions;
249+
if (is_first_unattributed)
250+
num_attributed_steps = condition_groups.size();
251+
252+
if (!condition_groups.empty() && !is_first_unattributed
234253
&& nodes_info[condition_groups.back().front()].required_storage_columns == node_info.required_storage_columns)
235254
{
236255
condition_groups.back().push_back(node);
@@ -338,6 +357,7 @@ bool tryBuildPrewhereSteps(
338357
.perform_alter_conversions = true,
339358
.columns_overwritten_by_chain = {},
340359
.mutation_version = std::nullopt,
360+
.query_condition_cache_attribution_boundary = step_index + 1 == num_attributed_steps,
341361
};
342362

343363
prewhere.steps.push_back(std::make_shared<PrewhereExprStep>(std::move(new_step)));

‎src/Storages/SelectQueryInfo.cpp‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,10 +54,12 @@ PrewhereInfo PrewhereInfo::clone() const
5454
prewhere_info.prewhere_column_name = prewhere_column_name;
5555
prewhere_info.remove_prewhere_column = remove_prewhere_column;
5656
prewhere_info.need_filter = need_filter;
57+
prewhere_info.query_condition_cache_attribution = query_condition_cache_attribution;
5758

5859
return prewhere_info;
5960
}
6061

62+
/// `query_condition_cache_attribution` is not serialized: a deserialized plan does not attribute.
6163
void PrewhereInfo::serialize(IQueryPlanStep::Serialization & ctx) const
6264
{
6365
prewhere_actions.serialize(ctx.out, ctx.registry);

‎src/Storages/SelectQueryInfo.h‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,17 @@ struct PrewhereInfo
4848
bool remove_prewhere_column = false;
4949
bool need_filter = false;
5050

51+
/// Set when only a leading part of the PREWHERE conjunction consists of conjuncts of
52+
/// `SelectQueryInfo::filter_actions_dag`. Marks emptied by that part alone are recorded under its key.
53+
struct QueryConditionCacheAttribution
54+
{
55+
UInt64 key;
56+
String condition;
57+
/// Hashes of the leading conjuncts of the PREWHERE condition that the key covers.
58+
std::vector<UInt64> conjunct_hashes;
59+
};
60+
std::optional<QueryConditionCacheAttribution> query_condition_cache_attribution;
61+
5162
PrewhereInfo() = default;
5263
explicit PrewhereInfo(ActionsDAG prewhere_actions_, String prewhere_column_name_)
5364
: prewhere_actions(std::move(prewhere_actions_)), prewhere_column_name(std::move(prewhere_column_name_)) {}

0 commit comments

Comments
 (0)