Repository navigation
Conversation
…x analysis With a JOIN over a `MergeTree` table, join-order estimation asks the read step for a row count, which runs and memoizes `selectRangesToRead` while `query_info.prewhere_info` is still null. Its query condition cache probe therefore takes the `filter_actions_dag` branch and keys on the WHERE-derived condition. `optimizePrewhere` then installs the moved-down predicate through `updatePrewhereInfo`, which left that verdict in place, and nothing probes the cache again, while the reader writes its entry under the PREWHERE key. The entry is written, is correct, and is never consulted, so a repeated query prunes nothing. Both `optimize_move_to_prewhere` and `query_plan_optimize_prewhere` are on by default, so this is the default path. Apply the verdict for the new PREWHERE to the ranges the memoized analysis already selected, by calling the same probe the analysis uses on a copy of `parts_with_ranges`, and refresh the five fields that are by definition derived from those ranges: `selected_parts`, `selected_ranges`, `selected_marks`, `selected_rows` and `has_exact_ranges`. The probe indexes its verdict by absolute mark number per part and only ever removes marks, and every mark it removes is one the cache recorded as containing no row matching the condition, so applying it to the already-selected ranges cannot change the query's result. Applying it to a narrower input can drop marks a full re-analysis would have kept, never the reverse. `total_parts`, `total_marks_pk` and `index_stats` are kept, so `SelectedMarksTotal` keeps describing the table and the comparison of `SelectedMarks` against it stays the observable statement that pruning happened. The WHERE verdict is already in the memo, so the probe is handed a copy of `query_info` with the filter DAG cleared and consults only the new PREWHERE. One logical consultation then reports one event: without this, a read that now prunes perfectly also reports a cache miss for the condition it had already applied. Discarding the memo instead would be simpler, and is what the first version of this change did, but it costs a full second index analysis: measured +25% CPU on a 300-part table, paid by every cache-eligible join read at default settings and paid in full exactly when the cache has least to offer. This shape adds no analysis pass, so `ProfileEvents['IndexAnalysisRounds']` is unchanged, which the test pins, and a difference-in-differences benchmark over 300 runs per cell with the binaries crossed over puts the remaining cost at -3.4% and +0.6% of query CPU. The gate mirrors the two soundness conditions the probe cannot check for itself, a unique key and a filter over a non-deterministic virtual column, whose key of table, part and condition cannot express either. Reads that take part in parallel replicas are excluded: a coordinator-driven read must keep the ranges the coordinator assigned, and the remaining shapes are left to the analysis that already handles them. Everything the probe self-gates on is hoisted into the same condition through `canFilterPartsByQueryConditionCache`, so a read the cache cannot serve returns before any ranges are copied. Second run of a repeated query on the fixture from issue ClickHouse#122044: 8,639,765 -> 311,335 rows and 1056 -> 39 granules, with identical results. On a 500k single-part fixture: 500,001 -> 8,193 rows and 62 -> 2 granules. Related: ClickHouse#122044
Drop the design narration from the new comments in updatePrewhereInfo and on canFilterPartsByQueryConditionCache; keep the reason for the unique-key and non-deterministic-virtual exclusions. 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; 8 findings across my own cold pass
Noted, not blocking:
Fold of the parallel-replicas case (2026-09-29): my own cold pass (1 finding) plus the independent model
Noted, not blocking:
Severity: ❌ blocker / Session id: cron:clickhouse-review-self-slot-58:20260925-202800 (fold: cron:clickhouse-review-slot-11:20260929-010700) |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-self-slot-57:20260925-181951 |
|
Workflow [PR], commit [fb5dc09] Summary: ❌
AI ReviewSummaryReviewed Missing context / blind spots
Final Verdict✅ Approve. No new inline findings. |
…analysis The test server profile sets `max_rows_to_read`. Under a row limit that throws, join-order estimation analyzes the read without memoizing the result, so the read is analyzed again after `optimizePrewhere` installs the PREWHERE, and that analysis already probes the cache under the PREWHERE key. Base and fix then print the same values, two index analyses per table and one more cache miss per run, which is what Fast test reported. Pin the default of no limit, which is the path the fix changes. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
📊 Cloud Performance Report ✅ AI verdict: This PR changes query condition cache handling: it checks the cache again once PREWHERE is chosen after join reordering, and turns the cache off for tables with masking policies. None of the flagged queries is a plausible beneficiary. ClickBench Q33/Q34 are unfiltered GROUP BYs that never use the cache, TPC-H Q1 has no join, and TPC-H Q7's shipdate filter matches rows in nearly every granule, so all four improvements (-13.8%, -13.5%, -18.5%, -24.7%) are downgraded to not sure. In each case the base run sat at the slow edge of master's normal range and the PR run falls inside it. The ClickBench Q31 slowdown (+14.9%) stays within master's normal range with slightly lower CPU time, and I see no reason to challenge that. clickbenchFlagged queries (3 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_officialFlagged queries (2 of 22)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. Debug info
|
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units128 translation units recompiled, 1645 s compile time in total, 128 of them have a recent master baseline. |
CI finish ledger - cb8da84Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
All other check runs completed (136 pass, 35 not selected, 4 red), Session id: cron:our-pr-ci-monitor:20260926-063421 |
|
@shankar-iyer Another fix in the query condition cache area :-( If you have time, like to check? Thanks. |
Master's ClickHouse#114659 and ClickHouse#117968 added the `allow_top_k_prewhere_query_condition_cache` parameter and the pending-TopK `prewhere_info_for_cache` to `filterPartsByQueryConditionCache`, which the textual merge spliced into the extracted `canFilterPartsByQueryConditionCache`, so it did not compile. Resolved by keeping master's `filterPartsByQueryConditionCache` behind the eligibility helper, which now counts a pending TopK filter as a PREWHERE, and by keeping TopK reads out of the refresh in `updatePrewhereInfo`, whose probe does not carry the post-PREWHERE filter that a TopK PREWHERE entry is keyed on. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…lel replicas `updatePrewhereInfo` probes the query condition cache for a PREWHERE installed after the read was analyzed, but it skipped every read that takes part in parallel replicas. That also excluded the initiator's local read, which reuses the analysis made before the condition moved to PREWHERE, by the `parallel_replicas_min_number_of_rows_per_replica` estimate or by join reordering. With `parallel_replicas_index_analysis_only_on_coordinator` that analysis is the snapshot replica's announcement, so a repeated query read the unpruned ranges on every replica (`04249_query_condition_cache_fine_grained_granules`: 100 marks instead of 1 on the warm run). Only a follower's read is excluded now, because it must keep every part the coordinator may assign to it. Found while investigating `04249_query_condition_cache_fine_grained_granules` on ClickHouse#71028, in the reruns of this job: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=71028&sha=ccaacd566915d761c4f0e4a722eb36956ab147ad&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20sequential%29 Co-Authored-By: Claude Opus 5.5 <[email protected]>
A masking policy rewrites, for the querying user only, the values a read returns. It is appended to the part's alter conversions at read time, which the mutations snapshot does not see, so the existing exclusion of reads with on-the-fly mutations never fires for it, while the cached verdicts are computed on the stored values: a masked read could skip granules whose masked values match. Exclude such reads at both places that consult the cache, the index analysis in `selectRangesToRead` and the refresh in `updatePrewhereInfo`. The write side already skips them, because a masked column the query reads produces on-the-fly mutation steps. Statistics pruning and the sparsity statistics use the same gate (b724707, e258bd9). `hasEnabledMaskingPolicies` is constant false outside the Cloud build. Also drop the comment on the follower exclusion in the refresh: its reason did not hold, since a replica is only assigned parts it announced. Follower reads are left as they were. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…N read by parallel replicas The tests checked the marks a warm run reads only as a fraction of the table (`SelectedMarks * 4 < SelectedMarksTotal`), which still passes when the cache prunes only three quarters of the granules. Assert instead that the cold run reads every mark and that the warm run reads at most the matching granule, the one of the joined table and, on a compact part, sometimes the next granule: a compact part read in blocks of more than one and at most two granules leaves the granule after the matching one unrecorded. The control without a JOIN now reads `k` too, so its condition moves to PREWHERE as in the other arms. As a WHERE filter it records whole read blocks, whose size follows `max_block_size`. 05257 gains an arm for a JOIN read by parallel replicas. Without a row estimate, join reordering inside the local plan is the only analysis made before PREWHERE, a different producer than the estimate 05292 covers. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Merge the TopK exclusion's comment into the one above the gate, shorten that one to two lines, and drop the doc comment of canFilterPartsByQueryConditionCache, which restated its name. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
CI finish ledger - fd1999dEvery 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-230007 |
…e-probe a restored PREWHERE Masked reads now neither read nor write the cache (`selectRangesToRead` and `initializePipeline`). `updatePrewhereInfo` remembers the PREWHERE it probed, so the clear/restore in the text index optimization does not double `QueryConditionCacheHits`/`QueryConditionCacheMisses`.
…amic filter `updatePrewhereInfo` skipped every TopK-stamped read, so a repeated `ORDER BY ... LIMIT` query whose condition moves from WHERE to PREWHERE kept the stale verdict of the memoized analysis in the JOIN and parallel-replicas cases this PR fixes. The warm run read 61/61 marks under `parallel_replicas_min_number_of_rows_per_replica = 1` and 62/62 under a reordered JOIN, against 1 and 2 marks for the same queries without `ORDER BY ... LIMIT`. The refresh now probes a TopK read while its `__topKFilter` is still pending: the cache then consults the PREWHERE with the filter merged in and salts it with the TopK plan and the WHERE, which is what the reader writes under. To keep the WHERE for that salt, `filterPartsByQueryConditionCache` gets `consult_where` instead of the refresh clearing `filter_actions_dag`. The call from `installTopKDynamicFilter` is not probed: it installs the PREWHERE that the pending probe already used, so probing it would only count the cache twice (the plain TopK path keeps 2 misses, then 1 hit and 1 miss). Warm runs now read 1 mark (parallel replicas) and 2 marks (JOIN). 05257 and 05292 gain a TopK arm each; both arms are red on 616d785 (0 hits, every mark read) and green with this change. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`query_condition_cache_probed_prewhere` was set only by a probe in `updatePrewhereInfo`, so the text-index clear/restore of an explicit PREWHERE looked the restored PREWHERE up again although the memoized analysis already carried its verdict. With an explicit PREWHERE on a table with a text index and `parallel_replicas_min_number_of_rows_per_replica = 1` that was 3 misses and 3 hits where master has 2 and 2; now it is 2 and 2. Until the first probe, the guard now holds the PREWHERE the read had when its analysis was memoized. The TopK arms of 05257 and 05292 now also check the miss count and `IndexAnalysisRounds`, and 05292's arm anchors the `__topKFilter` PREWHERE in the plan, so a lost TopK stamp or an extra WHERE lookup turns them red. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…d after index analysis `tryOptimizeGroupByTopK` installed the `__topKFilter` PREWHERE before stamping the read with `setTopKColumn`, so when the read already had a memoized analysis (e.g. from evaluating an aggregate projection that was then rejected), the refresh in `updatePrewhereInfo` looked the new PREWHERE up without the TopK salt. No entry is ever written under that key, so the lookup was a wasted miss, and the warm query still read every mark the primary key selects. The read is now stamped first, and `updatePrewhereInfo` also refreshes a non-pending TopK read whose analysis predates the stamp. A pending read keeps skipping the install call, whose PREWHERE the pending probe already used. Measured on a 500k-row table with a rejected aggregate projection, warm `SELECT w, count() ... WHERE k < 100000 AND v > 5 GROUP BY w ORDER BY w LIMIT 3`: 13 marks and 1 hit before (master too), 8 marks and 2 hits after, the same as without the projection. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…in 05257 The warm run prints its rows, which equal those of the query without the cache, reads the same marks as the arm without the projection, and does not add an index analysis. Co-Authored-By: Claude Opus 5.5 <[email protected]>
CI finish ledger - 1d0782eEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
The Fast test failure dropped the remaining jobs, so this head has no other test signal yet. CIDB has no other Session id: cron:our-pr-ci-monitor:20261013-110003 |
Please explain in simple plain English
Make the least introsive and most minimal fix. We currently add member variables query_condition_cache_probed_prewhere and query_condition_cache_analysis_before_top_k to generic code and I think we can do without them. |
|
What problem does this PR solve? The query condition cache remembers, per part, which granules have no row matching a filter, so a repeated query can skip them. When the table is read under a JOIN, this never works: the second run reads everything again. CREATE TABLE hits (id UInt64, user_id UInt64, duration UInt64) ENGINE = MergeTree ORDER BY id;
INSERT INTO hits SELECT number, number % 1000, number FROM numbers(1000000);
CREATE TABLE users (user_id UInt64, name String) ENGINE = MergeTree ORDER BY user_id;
INSERT INTO users SELECT number, toString(number) FROM numbers(1000);
-- run it twice
SELECT count() FROM hits JOIN users ON hits.user_id = users.user_id WHERE hits.duration = 42;On today's master, Why: to pick the join order, the planner asks How does it solve it? When the condition is moved to PREWHERE and the read already has a kept analysis, the read looks up the cache once for the new PREWHERE condition and removes the granules it rules out from the kept ranges. No second index analysis runs. Making it minimal Agreed, I'm reducing the change to that. The lookup will be called from |
…zePrewhere Reduce the fix to its core, as asked in review. An analysis memoized before optimizePrewhere moves a WHERE condition to PREWHERE (join order estimation, the parallel_replicas_min_number_of_rows_per_replica estimate) looked the query condition cache up for the WHERE condition only, while the read records its verdict under the PREWHERE condition. optimizePrewhere now calls ReadFromMergeTree::applyPrewhereQueryConditionCache right after installing the PREWHERE, which looks the cache up for that PREWHERE and narrows the memoized ranges, without a second index analysis. Calling it from optimizePrewhere instead of updatePrewhereInfo means the text index clear/restore and the TopK filter installs never look the cache up again, so the members query_condition_cache_probed_prewhere and query_condition_cache_analysis_before_top_k, the consult_where parameter, canFilterPartsByQueryConditionCache and the reordering in optimizeGroupByTopK are gone. TopK reads are left out (their PREWHERE key also hashes the WHERE condition, which this lookup drops) and keep master's behaviour; the TopK test cases are removed with them. The masking policy write gate stays. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…x-analysis # Conflicts: # src/Processors/QueryPlan/ReadFromMergeTree.cpp
|
Pushed the minimal version in fccd0e7, plus a master merge (227c68a) because the branch had conflicts. The fix is now one method, |
…ache is disabled `applyPrewhereQueryConditionCache` copied the memoized analysis and recounted its ranges even with `use_query_condition_cache = 0`, where `filterPartsByQueryConditionCache` returns at once. Return before the copy. Measured on a debug build, a JOIN over a 3000-part table with the condition moved to PREWHERE: 0.61% of planning CPU samples were in this method with the cache disabled, 0 after the change. With the cache enabled the lookup count is unchanged (6000 misses, IndexAnalysisRounds 2). Co-Authored-By: Claude Opus 5.5 <[email protected]>
CI finish ledger - fb5dc09Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20261109-183010 |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
A repeated query now uses the query condition cache for a
MergeTreetable read under aJOIN, or by parallel replicas sized byparallel_replicas_min_number_of_rows_per_replica, when its filter is moved toPREWHERE(the default), so the second run reads only the granules that can match instead of the whole table.Description
To pick the join order, the planner asks a
MergeTreetable how many rows it will read. That index analysis, including the query condition cache lookup, runs while the filter is still a WHERE condition, and it is kept for the real read. The filter is then moved to PREWHERE, and the read stores its result in the cache under the PREWHERE condition, which the kept analysis never looks up, so every run reads the whole table. Theparallel_replicas_min_number_of_rows_per_replicaestimate does the same, and with parallel replicas the kept analysis is what the coordinator hands out to the replicas.optimizePrewherenow callsReadFromMergeTree::applyPrewhereQueryConditionCacheright after it moves the condition. It looks the cache up for the new PREWHERE condition and removes the granules it rules out from the kept analysis. No second index analysis runs (IndexAnalysisRoundsis unchanged). TopK reads are left as they are. Reads under a masking policy (Cloud only) do not write the cache.Second run of
SELECT count() FROM hits JOIN users ON hits.user_id = users.user_id WHERE hits.duration = 42on 1M rows: 124 marks before, 2 after, same result. Both new tests fail without the change.Closes: #134069
Related: #122044
Related: #71028 (comment)
Workflow [PR]
Sync PR [sync-upstream/pr/122339]