Skip to content

Record TopK PREWHERE granule skips in the query condition cache - #118703

Closed
alexey-milovidov wants to merge 8 commits into
masterfrom
topk-prewhere-query-condition-cache
Closed

alexey-milovidov wants to merge 8 commits into
masterfrom
topk-prewhere-query-condition-cache

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 8, 2026 •

Copy link
Copy Markdown
Member

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 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 the WHERE FilterTransform) already use the narrower isDeterministicAllowingTopKFilter gate; the PREWHERE one did not, and MergeTreeDataSelectExecutor documented the gap:

/// The PREWHERE write path in `MergeTreeSelectProcessor::read` does not (yet) apply this salt, so we must
/// not apply it on the PREWHERE read path either - otherwise the keys diverge and the lookup always misses.

The granules a WHERE empties are recorded, but a granule that __topKFilter empties never produces a chunk, so it never reaches the FilterTransform either — 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 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 already 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, since the comments on them already warned that they must agree.

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.

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 smallest EventTime is 2013-07-01 20:00:01; only 69 of ~12000 granules hold a row at or below it.

Q24, repeated run selected marks wall CPU
before 11900 / 12349 154 ms 378 ms
after 16 / 12349 5 ms 6 ms

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 EventTime column (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):

  • Performance Improvement

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

Repeated ORDER BY <column> LIMIT n queries over MergeTree are 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]

`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]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [03a2346]

Summary: ❌

job_name test_name status info comment
Performance Comparison (amd_release, master_head, 1/6) FAIL Performance dashboard
timeseries_to_grid_scalar_add #0 FAIL dashboard
timeseries_to_grid_scalar_add #2 FAIL dashboard
Performance Comparison (arm_release, master_head, 5/6) FAIL Performance dashboard
lazy_final_early_exit_limit #1 FAIL dashboard

AI Review

Summary

This PR teaches the query condition cache to keep the granules emptied by the dynamic __topKFilter PREWHERE, and it now keeps the cache key consistent across the WHERE writer, the PREWHERE writer, the index-analysis writer, and the read-side probes. I re-checked the current code at the PR head, including the two earlier review threads, and did not find any unresolved correctness, safety, or coverage issues in the patch itself.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Measured on commit 03a2346.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.40% 79.40% +0.00%

Changed lines: Changed C/C++ lines covered: 90/93 (96.77%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Sep 8, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 33 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: 85026231-2b33-44e6-921b-9c04ce7cdca9
  • MIRAI run: edb27fda-7771-47ae-a63a-0c14168cb20b
  • PR check IDs:
    • clickbench_1634788_1790244690
    • clickbench_1634794_1790244690
    • clickbench_1634800_1790244690
    • tpch_adapted_1_official_1634812_1790244690
    • tpch_adapted_1_official_1634824_1790244690
    • tpch_adapted_1_official_1634859_1790244690

@clickhouse-gh

clickhouse-gh Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 03a234651 with master ed7bae423 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

336 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.
The matched translation units cost +188.9 s (+6%) in total before that adjustment.

Job report

alexey-milovidov and others added 2 commits September 16, 2026 15:10
…-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]>
Comment thread src/Storages/VirtualColumnUtils.cpp Resolved
alexey-milovidov and others added 5 commits September 24, 2026 06:35
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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Closing as superseded by #114659 (merged 2026-09-27), which does the same thing on master.

I checked this against master at 31d2addbabda0d8e14ffd325fc0a9106528aa1c7:

Merging master into this branch now conflicts in every file the PR touches, because both sides implement the same feature. The remaining difference is only a refactor (getQueryConditionCacheConditionHash).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant