Skip to content

Record the static conditions of a PREWHERE shared with a join runtime filter in the query condition cache - #122380

Merged
fm4v merged 6 commits into
ClickHouse:masterfrom
groeneai:qcc-attribute-prewhere-shared-with-runtime-filter
Oct 13, 2026
Merged

fm4v merged 6 commits into
ClickHouse:masterfrom
groeneai:qcc-attribute-prewhere-shared-with-runtime-filter

Conversation

@groeneai

@groeneai groeneai commented Sep 26, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Performance Improvement

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

The query condition cache now records the static WHERE conditions of a join whose PREWHERE also 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 when enable_join_runtime_filters_index_analysis is disabled.

Description

#122044 (@ fm4v): with join runtime filters a repeated join gets no query condition cache hits, not even for its static WHERE condition. Reproduced on master (plain MergeTree/AggregatingMergeTree): with enable_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 PREWHERE next to the static conjunct, e.g. and(in(c1, ...), __applyFilter(...)). __applyFilter is non-deterministic on purpose, so the PREWHERE writer refuses the whole condition, and the WHERE key is lost when the two filter steps are merged.

Change. When a PREWHERE starts with conjuncts that are structurally conjuncts of the read's WHERE condition (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 RuntimeFilterRowsChecked drops 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 415 PREWHERE and 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, a WHERE kept out of PREWHERE.

On master the issue's enable_join_runtime_filters = 0 case misses the cache too, for a separate reason: #122339.


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

Version info

  • Merged into: 26.10.1.2260-master (included in 26.10 and later)

groeneai and others added 4 commits September 25, 2026 21:45
… 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]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 26, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
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.

# Sev Finding Verdict Evidence / action
1 ⚠️ The conjunct normalization applied the identifier-to-column map to DAGs that already read storage names, so a column named like another column's qualified name (__table1.k next to k) could share its cache verdicts (optimizePrewhere.cpp) AGREE, fixed @ e4634ff normalized with an empty map; a test arm covers the column pair
2 ⚠️ The test's pruned check (read_rows < 20000) passes when one granule of 157 is skipped AGREE, fixed @ e4634ff bound tightened to read_rows < 1000 (at most 394 rows are needed)
3 ⚠️ The multi-key and ANTI arms never observe the cache AGREE, fixed @ e4634ff ANTI gets its own entry and hit assertion; multi-key stays result-checked, because its second runtime filter can be ordered first
4 ⚠️ Miss assertions on the explicit-PREWHERE and runtime-filter-first arms, exact mark counts DISAGREE the change is not reached on those arms (optimizePrewhere.cpp:356, empty prefix at :222-233); granule sizes are randomized, so exact counts would be flaky
5 ⚠️ The normalization catches exceptions and falls back to no attribution (optimizePrewhere.cpp) AGREE, fixed @ 3b32d45 the try/catch is gone; applyFilters runs the same DAG rebuild unguarded
6 ⚠️ The test was not run with the CI user profile (users.d/limits.yaml), which changes when index analysis runs AGREE, fixed @ 3b32d45 measured: fix 20/20 green, master 3/3 red on the same four lines; no setting pin needed
7 💡 03229_query_condition_cache_cte_constant_folding was made no-parallel to stop it clearing the cache under this test AGREE, fixed @ 3b32d45 tag reverted; the redundant clear is dropped instead, since the test creates its own table
8 💡 Attribution snapshots are taken even when the reader has the cache off AGREE, fixed @ 3b32d45 gated on the reader setting, as the existing call site is
9 💡 The normalization runs at plan time for every multi-conjunct PREWHERE read noted one small sub-DAG rebuild per conjunct, plan time only
10 💡 The first commit's message calls enable_join_runtime_filters_index_analysis = 0 the 26.6 default noted 26.6 has no such setting; 0 is the default in 26.8 and 26.9, as the description says

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-8:20260926-031510

@clickhouse-gh

clickhouse-gh Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [267a4a0]

Summary: ❌

job_name test_name status info comment
AST fuzzer (amd_release, oracle) FAIL
AST fuzzer oracle mismatch FAIL cidb IGNORED

AI Review

Summary

This PR teaches PREWHERE splitting to attribute deterministic leading conjuncts to the storage WHERE query-condition-cache key when a join runtime filter makes the full PREWHERE non-deterministic. The local read/write path looks consistent, but the new attribution metadata is explicitly dropped when a plan fragment is serialized, so shipped reads fall back to the pre-patch behavior. Because this is a Performance Improvement PR, I would not approve it until that supported execution mode is fixed.

Findings

⚠️ Majors

  • [src/Storages/SelectQueryInfo.cpp:62] query_condition_cache_attribution is intentionally not serialized, but shipped ReadFromMergeTree fragments still carry prewhere_info and are re-optimized on the worker. After deserialization the worker sees an existing PREWHERE, so optimizePrewhere does not rebuild the attribution and the new WHERE-keyed cache write never happens for make_distributed_plan / plan-based parallel replicas.
    Suggested fix: carry query_condition_cache_attribution in PrewhereInfo's wire format (with the corresponding versioning), or add a recomputation path for deserialized optimizer-generated PREWHEREs.
Tests
  • ⚠️ Add a focused regression that exercises the same join through a shipped-plan path and checks that the second execution gets the WHERE-keyed query condition cache hit there too.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions: preserve query_condition_cache_attribution across shipped plan fragments, and cover that path with a targeted regression.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Sep 26, 2026
@shankar-iyer shankar-iyer self-assigned this Sep 26, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 26, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

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

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 2a2e3f90-a460-451c-8a1c-aa0d9d45698c
  • MIRAI run: 07fe1d70-f615-4014-894b-5ed58e67b4f3
  • PR check IDs:
    • clickbench_1141425_1791846436
    • clickbench_1141438_1791846436
    • clickbench_1141444_1791846436
    • tpch_adapted_1_official_1141455_1791846435
    • tpch_adapted_1_official_1141463_1791846436
    • tpch_adapted_1_official_1141496_1791846436

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - beec72d

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stress test (arm_debug) / Received signal 6 (internal) (STID 3593-560a) crash: the intrusive_ptr assertion on a null query AST in ReadFromMerge::createChildrenPlans (src/Storages/StorageMerge.cpp:1213), during SELECT count() FROM test_5.buf_top PREWHERE y != 0 with serialize_query_plan = true, i.e. a serialized plan read that reaches a Merge table through a Buffer table. Not caused by this PR: 21 rows on 20 pull requests and 1 true-master run since 2026-09-11, on 6 Stress flavours. This diff never touches StorageMerge or SelectQueryInfo::query; it only adds a cache-attribution field to PrewhereInfo #119387 (mine, open)
Upgrade check (amd_release) / Error message in clickhouse-server.log release-side metadata round-trip, not PR-caused. The pre-upgrade v26.9.2.8 server leaves t_pfl_05079 as AggregateFunction(quantile('0.5'), Float64), and the upgraded server refuses to attach it (Code 70 CANNOT_CONVERT_TYPE). 78 PRs carry this signature since 2026-09-21, and no master run does #121590 (external, merged into 26.9, not yet in a published release)
Upgrade check (amd_release) / Cannot check whether the mutation submitted before the upgrade was finished same cause: the system.mutations probe dies with ASYNC_LOAD_WAIT_FAILED behind the same failed t_pfl_05079 load #121590 (external, merged into 26.9)
Performance Comparison (amd_release, master_head, 2/6) / rewrite_array_exists #0 dashboard confirmed_regression, client_time 0.0628 -> 0.0726 s (+15.5%). The shard's own report does not flag it (4 too long, 1 unstable, the unstable one being codecs_int_insert #4), so the dashboard verdict alone made the shard red. The query runs arrayExists over numbers(10000000): it reads no MergeTree table and builds no PREWHERE, which is all this PR changes ClickHouse/performance-comparison#5 (external, open): the dashboard's confidence scoring, where @ fm4v handles these verdicts after #121847, which is present in this head. That repository is not publicly readable, so its state cannot be measured from here
Mergeable Check, PR rollups, red only because of the rows above #119387, #121590 and ClickHouse/performance-comparison#5, the owners of the rows above

Fix presence for #121590: this Upgrade check installed v26.9.2.8-stable, which is still the newest
published 26.9 release, and #121590 merged into 26.9 after it. A master merge cannot pick it up.

All 176 check runs completed (157 pass, 14 not selected, 5 red), Finish Workflow is green and
CH Inc sync passed.

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
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - f82d184

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Fast test (arm_darwin) / 05238_pretty_squash_broken_pipe not from this PR (it does not touch output formats or clickhouse-local): the first subtest, SELECT number FROM numbers(1e18) FORMAT PrettyCompact piped to head -n 1, exits with 241 (MEMORY_LIMIT_EXCEEDED) instead of 75. The test came with #117005 (merged 2026-10-09); 10 PRs show this on macOS since 02:11Z today (7 with 241, 3 killed by the per-test timeout). #125028 fixed a different abort of this test a fix task is created (investigating at full effort, fixing-PR link to follow here)
Stateless tests (arm_binary, ParallelReplicas, s3 storage, sequential) / 03254_system_prewarm_mark_cache flaky, not from this PR (114 of 116 reruns pass): with parallel replicas the LoadedMarksCount check reads only the initiator's query_log row and gets 0 instead of 1. 9 PRs show it in 48h #124942 (mine, open)
Mergeable Check, PR praktika rollups of the two rows above a fix task is created; #124942 (mine, open)

Session id: cron:our-pr-ci-monitor:20261010-193004

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for 05238_pretty_squash_broken_pipe on Fast test (arm_darwin) created: #125102

return prewhere_info;
}

/// `query_condition_cache_attribution` is not serialized: a deserialized plan does not attribute.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 267a4a0

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_release, oracle) / AST fuzzer oracle mismatch wrong result in the analyzer, not from this PR: in the fuzzed query * APPLY lambda(tuple(x), toString(x)) and * REPLACE (... AS d) APPLY lambda(tuple(x), toString(x)) both produce a column named toString(d), and the subquery-wrap oracle's SELECT * FROM (...) collapses the two same-named columns. It reproduces on master #107127 (mine, open)
Mergeable Check, PR praktika rollups of the row above #107127 (mine, open)

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261013-070008

@fm4v
fm4v added this pull request to the merge queue Oct 13, 2026
Merged via the queue into ClickHouse:master with commit 64da8a0 Oct 13, 2026
175 of 177 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 13, 2026
@rschu1ze

rschu1ze commented Nov 9, 2026

Copy link
Copy Markdown
Member

@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.

@fm4v

fm4v commented Nov 9, 2026

Copy link
Copy Markdown
Member

@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 enable_join_runtime_filters by default

@rschu1ze

Copy link
Copy Markdown
Member

Sorry, this is too dirty. We should re-implement this properly.

@groeneai Create a revert PR please.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Acknowledged. I'm preparing the revert of this PR; I'll link the revert PR here shortly.

@groeneai

Copy link
Copy Markdown
Collaborator Author

The revert is #131167. It also reverts the test-only follow-up #125702, and with it the query condition cache miss of #122044 comes back until this is re-implemented.

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 16, 2026
…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]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 18, 2026
…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]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 21, 2026
…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]>
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 22, 2026
@robot-clickhouse robot-clickhouse added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 22, 2026
thevar1able pushed a commit to actueleai/ClickHouse that referenced this pull request Nov 24, 2026
… 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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo v26.10-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Join runtime filters (default in 26.6) disable query condition cache hits: repeated query reads 28x more rows

7 participants