Repository navigation
Record the static conditions of a PREWHERE shared with a join runtime filter in the query condition cache - #122380
Conversation
… 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: ClickHouse#122044 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…fier map The frozen filter condition and the PREWHERE conjuncts that the attribution compares both read storage columns already, so mapping column identifiers to storage columns a second time only mattered for a storage column named like another column's identifier: `__table1.k` then compared equal to `k`, and a join could record the granules its condition on `__table1.k` emptied under a key that a later query filtering `k` trusts. Collapse aliases and re-derive function names only. The test's pruned-read bound drops to 1000 rows, so recording only part of the emptied granules fails it. The LEFT ANTI arm gets its own IN list and cache assertions; the multi-key arm stays a result check, because its runtime filter on the small `pad` column can be ordered ahead of the static condition. A new arm covers the column named like a qualified name. 03229_query_condition_cache_cte_constant_folding clears the whole query condition cache, so it no longer runs in parallel with tests that expect cache hits across their queries. Co-Authored-By: Claude Opus 5.5 <[email protected]>
getNormalizedHash no longer catches exceptions to fall back to no attribution. The frozen filter condition it compares against comes from the same buildFilterActionsDAG call on these nodes in ReadFromMergeTree::applyFilters, which runs unguarded, and cloneSubDAG has no throw site. MergeTreeReadersChain takes the attribution snapshots only when the reader uses the query condition cache: computeUnmatchedMarkRanges is valid only then, because only then are granules read whole. The snapshots were discarded otherwise, so no result changes. 03229_query_condition_cache_cte_constant_folding keeps running in parallel. Instead of a no-parallel tag it drops its SYSTEM CLEAR QUERY CONDITION CACHE, which protected nothing of its own: the test creates its table, and so a new table UUID, on every run. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop the comments that explained the attribution's own design (why a flag, why full attribution returns, why an emptied batch may skip the snapshot) and shorten the normalized-hash and PREWHERE split comments to one line each. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 3 rounds, 4 findings, none in the last round), plus my own cold review in each round.
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-8:20260926-031510 |
|
Workflow [PR], commit [267a4a0] Summary: ❌
AI ReviewSummaryThis PR teaches Findings
Tests
Final Verdict
|
|
📊 Cloud Performance Report ✅ AI verdict: 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
|
CI finish ledger - beec72dEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Fix presence for #121590: this Upgrade check installed All 176 check runs completed (157 pass, 14 not selected, 5 red), Session id: cron:our-pr-ci-monitor:20260926-143040 |
…ere-shared-with-runtime-filter # Conflicts: # src/Storages/MergeTree/MergeTreeReadTask.cpp # src/Storages/MergeTree/MergeTreeSelectProcessor.cpp # src/Storages/MergeTree/MergeTreeSplitPrewhereIntoReadSteps.cpp
CI finish ledger - f82d184Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20261010-193004 |
|
Fixing PR for |
| return prewhere_info; | ||
| } | ||
|
|
||
| /// `query_condition_cache_attribution` is not serialized: a deserialized plan does not attribute. |
There was a problem hiding this comment.
query_condition_cache_attribution cannot just disappear on the wire if this optimization is supposed to work for shipped plans too. ReadFromMergeTree already serializes query_info.prewhere_info to workers, and the worker re-optimizes the fragment; after deserialization the read still has an existing PREWHERE, so the later optimizePrewhere pass never calls setQueryConditionCacheAttribution again. The result is that make_distributed_plan / plan-based parallel replicas keep the old behavior and never populate the WHERE-keyed query condition cache entry for this case.
Please either serialize this field as part of PrewhereInfo (with the needed query-plan version bump), or add a worker-side recomputation path that can distinguish a deserialized optimizer-generated PREWHERE from a user-specified one.
CI finish ledger - 267a4a0Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
CIDB has no other Session id: cron:our-pr-ci-monitor:20261013-070008 |
64da8a0
|
@fm4v This fix looks fragile and frankly, it looks like slop. Did you review the code? Did you carefully weight the pros and cons? Did the assignee (@shankar-iyer ) approve? We should to avoid bad code in all shapes and forms. |
|
@rschu1ze I asked you to review the fixes from https://github.com/orgs/ClickHouse/projects/333 which had a deadline to land in 26.10. As for this PR, I believe the new tests validate the fix correctly, and I guess you are also interested in enabling |
|
Sorry, this is too dirty. We should re-implement this properly. @groeneai Create a revert PR please. |
|
Acknowledged. I'm preparing the revert of this PR; I'll link the revert PR here shortly. |
…rewhere-attribution Conflict in MergeTreeSplitPrewhereIntoReadSteps.cpp with ClickHouse#131511: keep its `crosses_dynamic_filter_boundary` split rule, drop only `is_first_unattributed` added by ClickHouse#122380. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…rewhere-attribution Conflict in MergeTreeSplitPrewhereIntoReadSteps.cpp with ClickHouse#132112: keep its `may_throw` / `prewhereConditionCannotThrow` split rule, drop only `is_first_unattributed` added by ClickHouse#122380. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…rewhere-attribution Conflict in MergeTreeSplitPrewhereIntoReadSteps.cpp with ClickHouse#129445, which replaced the grouping loop by `appendGroups` / `ConjunctionSplitter` and carried the ClickHouse#122380 query condition cache attribution boundary into it (`ConditionGroup::ends_cache_prefix`, the `cache_prefix` parameter, `attributed_children`). Keep ClickHouse#129445's conjunction and alias splitting, drop only the attribution parts. Without an attribution, master's code already ran with `cache_prefix = 0`, which is the reverted behaviour. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… runtime filter in the query condition cache" This reverts commit 64da8a0, reversing changes made to be89302. Conflicts resolved by keeping the later changes in the same lines: `is_query_prewhere` (ClickHouse#130645), the `last_reader_evaluating_defaults` argument (ClickHouse#128452), `readsSameColumns` (ClickHouse#124880), `follows_top_k_filter` (ClickHouse#129882), and the PREWHERE query condition cache write of ClickHouse#115522 in its own form before it merged ClickHouse#122380. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
The query condition cache now records the static
WHEREconditions of a join whosePREWHEREalso holds a join runtime filter, so a repeated join skips the granules those conditions exclude instead of reading them again. This helps whenever the runtime filter cannot skip those granules through an index itself, for example when no primary key or skip index covers the join key, or whenenable_join_runtime_filters_index_analysisis disabled.Description
#122044 (@ fm4v): with join runtime filters a repeated join gets no query condition cache hits, not even for its static
WHEREcondition. Reproduced on master (plainMergeTree/AggregatingMergeTree): withenable_join_runtime_filters_index_analysis = 0(its default in 26.8 and 26.9; 26.6 has no such setting) every run reads 8,639,765 rows instead of 311,335.Cause. The runtime filter lands in the probe's
PREWHEREnext to the static conjunct, e.g.and(in(c1, ...), __applyFilter(...)).__applyFilteris non-deterministic on purpose, so thePREWHEREwriter refuses the whole condition, and theWHEREkey is lost when the two filter steps are merged.Change. When a
PREWHEREstarts with conjuncts that are structurally conjuncts of the read'sWHEREcondition (compared by an alias-insensitive hash) and continues with others, those leading conjuncts get read steps of their own, and the granules they empty are recorded under the key the read side already probes for that condition. Granules emptied by the runtime filter or any later conjunct are never recorded. Other reads are unchanged.Validation. On the reporter's fixture runs 2 and 3 read 311,335 rows (base 8,639,765), and
RuntimeFilterRowsCheckeddrops from 8,639,728 to 4 since the runtime filter now sees only rows passing the static conjunct. The new test fails on master, passes 50/50 randomized, and five mutations each redden it, two with wrong results. No new failures among 415PREWHEREand cache tests.Limitation. With the index analysis on (the master default) and join keys in the primary key, the runtime filter's index reader already prunes that query to 319,527 rows, and an existing guard keeps the cache write off. Unchanged too: a runtime filter ordered first, a single-step
PREWHERE, aWHEREkept out ofPREWHERE.On master the issue's
enable_join_runtime_filters = 0case misses the cache too, for a separate reason: #122339.Workflow [PR]
Sync PR [sync-upstream/pr/122380]
Version info
26.10.1.2260-master(included in26.10and later)