Repository navigation
Record TopK PREWHERE granule skips in the query condition cache - #118703
alexey-milovidov wants to merge 8 commits into
Conversation
`ORDER BY <col> LIMIT n` is served by the dynamic `__topKFilter` PREWHERE, whose running threshold empties whole granules as the scan proceeds. Those granule verdicts were computed and then thrown away on every execution. The write in `MergeTreeSelectProcessor::read` is gated on the PREWHERE predicate being deterministic, and `__topKFilter` is deliberately not: it compares against a running threshold, so it must not be constant-folded, deduplicated, or shipped to a replica. Index analysis and the `WHERE` `FilterTransform` already use the narrower `isDeterministicAllowingTopKFilter` gate; the PREWHERE one did not, and a granule that `__topKFilter` empties never produces a chunk, so it never reaches the `FilterTransform` either - it was recorded nowhere. The key has to cover the query's whole filter, not just the PREWHERE predicate: the running threshold is derived from the rows that survive the `WHERE`, while the bare `__topKFilter(col)` predicate hashes identically across queries with different `WHERE` clauses. So the emptied granules are now recorded under the hash of `query_info.filter_actions_dag` salted with the TopK plan parameters and the part set - the key `updateQueryConditionCache` gives the `WHERE` filter, that `selectRangesToReadImpl` gives the index-analysis exclusions, and that `filterPartsByQueryConditionCache` already probes. The three copies of the determinism gate are folded into one, `VirtualColumnUtils::isDeterministicAllowingTopKFilter`. Recording is sound for the same reason the `WHERE` side already is: the threshold only tightens, so a granule whose rows all failed `__topKFilter` at any point holds no row that the final threshold would have kept. On ClickBench `hits` (100M rows), Q24 repeated: 11900/12349 marks and 378 ms of CPU before, 16/12349 marks and 6 ms after. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
Workflow [PR], commit [03a2346] Summary: ❌
AI ReviewSummaryThis PR teaches the query condition cache to keep the granules emptied by the dynamic Final VerdictStatus: ✅ Approve LLVM Coverage ReportMeasured on commit 03a2346.
Changed lines: Changed C/C++ lines covered: 90/93 (96.77%) · Uncovered code |
|
📊 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
|
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units336 translation units recompiled, 3442 s compile time in total, 336 of them have a recent master baseline. Median compile-time ratio to the baselines is ×1.06 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio. |
…-condition-cache Master folds `queryConditionCacheSettingsSalt` into every query condition cache key (`MergeTreeReaderSettings::query_condition_cache_settings_salt`). The PR's unified `ReadFromMergeTree::getQueryConditionCacheConditionHash` now takes that salt and applies it before the TopK plan salt, in the same order as `updateQueryConditionCache` and `filterPartsByQueryConditionCache`, so the PREWHERE `__topKFilter` write path, the index-analysis write path and the read path keep agreeing on the key. The deterministic-PREWHERE write path in `MergeTreeSelectProcessor::read` applies the salt as on master. Co-Authored-By: Claude Fable 5.1 <[email protected]>
CI setting randomization set `query_plan_max_limit_for_top_k_optimization = 1`, so `ORDER BY v LIMIT 3` was not served by the `__topKFilter` PREWHERE and the second run read every granule instead of hitting the query condition cache (`05088_run2 1 0` instead of `0 1`). The randomized settings diagnosis in CI identified this setting as the sole culprit and the test passes 145/145 times without randomization. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118703&sha=b11d0a9677f5fc3ecf8a8a6399cc885b85e8cadc&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20sequential%29 #118703 Co-Authored-By: Claude Fable 5.1 <[email protected]>
Master added a PREWHERE check in `updateQueryConditionCache` that calls the file-local helper which this branch moved to `VirtualColumnUtils`. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Address review: the helper only inspected explicit `FUNCTION` nodes, so a non-deterministic call hidden inside a constant-folded lambda (`ColumnFunction` carrier) was accepted and the query condition cache could record granules under a stable key. Now it is `isDeterministic` with the single exception of the `__topKFilter` call itself. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…topKFilter` Address review: `tryOptimizeTopK` also marks reads that only use a skip index, and those may have a deterministic user PREWHERE. Recording its emptied granules under the TopK-salted whole-filter key hid them from plain queries (and other TopK queries) with the same PREWHERE, which probe the PREWHERE hash. Test `05243` fails without the gate (`05243_plain` gets no cache hit). Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
|
🕵 Closing as superseded by #114659 (merged 2026-09-27), which does the same thing on I checked this against
Merging |
ORDER BY <col> LIMIT nis served by the dynamic__topKFilterPREWHERE, whose running threshold empties whole granules as the scan proceeds. Those granule verdicts were computed and then thrown away on every execution.The write in
MergeTreeSelectProcessor::readis gated on the PREWHERE predicate being deterministic, and__topKFilteris deliberately non-deterministic — it compares against a running threshold, so it must not be constant-folded, deduplicated, or shipped to a replica. Two of the three query-condition-cache writers (index analysis and theWHEREFilterTransform) already use the narrowerisDeterministicAllowingTopKFiltergate; the PREWHERE one did not, andMergeTreeDataSelectExecutordocumented the gap:The granules a
WHEREempties are recorded, but a granule that__topKFilterempties never produces a chunk, so it never reaches theFilterTransformeither — it is recorded nowhere.The key must cover the query's whole filter, not just the PREWHERE predicate: the running threshold is derived from the rows that survive the
WHERE, while the bare__topKFilter(col)predicate hashes identically across queries with differentWHEREclauses. So the emptied granules are now recorded under the hash ofquery_info.filter_actions_dag, salted with the TopK plan parameters and the part set — the keyupdateQueryConditionCachealready gives theWHEREfilter, thatselectRangesToReadImplgives the index-analysis exclusions, and thatfilterPartsByQueryConditionCachealready probes. The three copies of the determinism gate are folded into one,VirtualColumnUtils::isDeterministicAllowingTopKFilter, since the comments on them already warned that they must agree.Recording is sound for the same reason the
WHEREside already is: the threshold only tightens, so a granule whose rows all failed__topKFilterat any point holds no row that the final threshold would have kept.Measurements
ClickBench
hits(100M rows, one part,c6a.metal-shaped data), queries Q24 and Q26 (SELECT SearchPhrase FROM hits WHERE SearchPhrase <> '' ORDER BY EventTime [, SearchPhrase] LIMIT 10). The 10th smallestEventTimeis2013-07-01 20:00:01; only 69 of ~12000 granules hold a row at or below it.Before the change the dynamic filter still did its job within one run — the main reader saw 3.7M rows instead of 99.3M — but the full
EventTimecolumn (400 MB) was re-read and re-decompressed on every repetition, which by itself costs ~273 ms of CPU here.On https://benchmark.clickhouse.com this is the whole of the Q24/Q26 gap against the TCHouse-C build (ClickHouse 0.092 s / 0.072 s hot vs 0.018 s / 0.015 s on
c6a.metal, with the cold runs a tie); that build carries #81944, which salts and stores the same verdicts.Related: #89835
Related: #111492
Related: #81944
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Repeated
ORDER BY <column> LIMIT nqueries overMergeTreeare much faster: the granules that the top-N threshold filter discards are now stored in the query condition cache, so a later run of the same query skips them instead of re-reading the sorting column. On ClickBench Q24 and Q26 the hot run goes from ~0.09 s to ~0.02 s.Workflow [PR]
Sync PR [sync-upstream/pr/118703]