Repository navigation
Record TopK-filtered granules in the query condition cache - #114659
Conversation
The dynamic `__topKFilter` PREWHERE injected by `tryOptimizeTopK` for `ORDER BY ... LIMIT n` queries drops granules whose rows cannot beat the running top-N threshold, but those drops were never recorded in the query condition cache: the PREWHERE write path in `MergeTreeSelectProcessor::read` rejects non-deterministic conditions, and `__topKFilter` is one. Only the downstream WHERE `FilterTransform` wrote entries, at whole-chunk granularity, so repeat runs of e.g. ClickBench Q24/Q26 re-read almost the whole table (~95M of 100M rows) while the original implementation of the optimization (PR #81944) skipped ~98% of granules on repeat runs. Recording such granules is sound: for a fixed plan and data the threshold only tightens, so a granule with no surviving rows contains no row that could reach the final top-N, regardless of the threshold trajectory. The entries are keyed with the TopK plan salt (`TopKFilterInfo::condition_hash`, which also folds in the part-set snapshot), so only the same TopK plan over the same part set ever reuses them - mirroring what the WHERE write path (`updateQueryConditionCache`) already does. - Move `isDeterministicAllowingTopKFilter` (two identical static copies in `updateQueryConditionCache.cpp` and `ReadFromMergeTree.cpp`) into `VirtualColumnUtils`, next to `isDeterministic`. - Plumb the TopK salt to the reader via `MergeTreeReaderSettings::query_condition_cache_top_k_salt`. - PREWHERE write path: allow a `__topKFilter`-bearing condition when the salt is present, folding the salt into the key. - PREWHERE consult path (`filterPartsByQueryConditionCache`): apply the salt exactly when the PREWHERE contains `__topKFilter`, so the keys match the write side; deterministic user PREWHERE conditions keep using plain, unsalted entries shared with non-TopK queries. Part of the fix for #114639
…cache The stateless test isolates the PREWHERE write path with a query that has no WHERE at all, asserts the salt keeps ASC/DESC plans separate, and checks that a repeat run selects fewer marks. The performance test uses the ClickBench Q24/Q26 shapes over `hits_100m_single` from #114639
…entries Each TopK plan now writes two query condition cache entries per part: the WHERE filter entry and the dynamic `__topKFilter` PREWHERE entry, both salted with the TopK plan parameters. `04217_query_condition_cache_topk` and `04242_query_condition_cache_topk_collate` pin exact entry counts, so their references double. Also avoid an apostrophe in a `04891` echo line - the TSV output escapes it, which would break the reference comparison.
|
Workflow [PR], commit [1b218cd] Summary: ❌
AI ReviewSummaryThis PR extends the query condition cache so TopK reads can record granules dropped by the dynamic Findings❌ Blockers
Final VerdictChanges requested. LLVM Coverage ReportMeasured on commit 1b218cd.
Changed lines: Changed C/C++ lines covered: 336/356 (94.38%) · Uncovered code |
|
📊 Cloud Performance Report
Release-transition baseline: compared against the most recent available 26.9 masters at or before the trusted base-commit anchor because no 26.10 master baseline exists there. This PR records granules filtered by the dynamic threshold of clickbench🟢 1 improved · Flagged queries (4 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_official🟢 No significant changes Debug info
|
Build profile diff (arm_release)Commit See the job log for details. |
Do not consult dynamic `TopK` `PREWHERE` query-condition-cache entries when a row-level policy is active. These entries are shared across users and an unrestricted query could otherwise cause a restricted query to skip rows before its policy is applied. Add a regression that primes the cache without a policy, then reads as a restricted user. #114659
Align projection query-condition-cache lookups with the `parent_part:projection` key used by writers and verify warm `TopK` reads reuse the cache.\n\nhttps://github.com//pull/114659
|
🕵 Pass of 2026-09-26.
Local run on a fresh build: 10/10 pass ( |
…ithout parts `MergeTreeDataSelectExecutor::readFromParts` builds no step when the local snapshot has no parts. `ReadFromMergeTree::deserialize` then threw `LOGICAL_ERROR` for a read whose query condition cache was disabled (lazy `FINAL`, vector search, lookup filters), and returned the null step for any other read, which the plan deserializer dereferences. Return a `ReadNothingStep` instead, matching what `MergeTreeDataSelectExecutor::read` does for the same case. A bucketed distributed read keeps failing, as before. Addresses #114659 (comment)
Follow-up to the coexistence change earlier on this branch, which merged the dynamic TopN threshold filter into the read's existing PREWHERE but appended it as the last conjunct. Conjunct order is read-step order, so the last slot made the ClickBench-shaped query read 56.1% more compressed bytes than master (27,934,717 vs 17,898,967 on a 2M-row table, deterministic across repeats): the filter only ran after the user's condition had already read its own column. __topKFilter is the cheapest condition available: it reads one column, the sort key, which the query has to read anyway. Putting it first is what the feature owner asked for on the issue, and it is what the measurements support. Measured on 2M rows, max_threads = 1, compressed bytes read: shape dyn=0 master this change WHERE url LIKE (0 rows match) 49,816,933 57,843,021 57,822,861 WHERE sp != '' (ClickBench) 27,934,717 17,898,967 18,140,951 PREWHERE url LIKE 49,816,933 49,816,933 57,822,861 PREWHERE sp != '' 27,934,717 27,934,717 18,140,951 The explicit-PREWHERE row is the reported regression: master cannot use dynamic filtering at all when a PREWHERE already exists, so it reads 27,934,717 bytes either way, and sharing the slot brings that down 35%. The two url LIKE rows are not improved, and the second regresses. That shape matches almost no rows, so PartialSortingTransform never sets a threshold and __topKFilter stays constant-true: it reads the sort column and rejects nothing. That is a property of the threshold, not of the placement, and it is unchanged from the previous behaviour of this branch. 03711_top_k_by_skip_index pinned the old shape, in which a query carrying WHERE v2 > 0 ended up with a PREWHERE holding only __topKFilter. Its reference now shows the merged conjunction, which is the point of the change. The test gained pins for optimize_move_to_prewhere, query_plan_optimize_prewhere and query_plan_remove_unused_columns, because the printed filter column now depends on the WHERE being promoted and on the action positions being stable; without them the test failed 9 of 100 randomized runs. Correctness is unchanged: 18 query shapes (selective and ClickBench-like WHERE, explicit PREWHERE, two- and three-condition PREWHERE, no filter, LowCardinality and Nullable predicates, DESC and multi-key ORDER BY, row policy, view, Distributed, IN subquery, JOIN, parallel replicas, FINAL, and with optimize_move_to_prewhere, query_plan_optimize_prewhere and enable_multiple_prewhere_read_steps individually disabled) return byte-identical rows with use_top_k_dynamic_filtering on and off under a tie-free total ORDER BY. One trade-off worth stating: merging __topKFilter into the root conjunction makes the whole root non-deterministic for VirtualColumnUtils::isDeterministic, so the PREWHERE query-condition-cache entry is no longer written for a TopK read whose skip-index arm is inactive. Measured with positive controls: 1 entry before, 0 after, for that shape only; non-TopK reads, the skip-index arm, the index-analysis path and the plain-WHERE shape are all unchanged. ClickHouse#114659 adds the salted write that restores it and composes with this change. Co-Authored-By: Claude Opus 5 <[email protected]>
Prepending `__topKFilter` to the user's own conditions changes what a stateful
predicate sees. `enable_multiple_prewhere_read_steps` defaults to true
(`src/Core/Settings.cpp:985`), so the merged root is split into read steps, and
`MergeTreeSplitPrewhereIntoReadSteps.cpp:255-262` merges only adjacent
conditions specifically to preserve the order the user wrote. Each step
filters the block the next one sees, so a condition that depends on its
position within a block observes a different block than it does alone.
Measured on a 200,000-row table keyed by `intHash32(number)`, three
repetitions per cell with `max_threads = 1` and zero spread:
SELECT groupArray(k) FROM (
SELECT k FROM t PREWHERE rowNumberInBlock() < 100 ORDER BY k LIMIT 3)
read [470574,1032774,2727291] at `use_top_k_dynamic_filtering = 0` and
[8612,23139,25905] at 1 before this change, and the same rows at both values
after it. The two arms hold byte-identical data (`sum(cityHash64(k))` equal)
and the same part layout, so only the install differs. The divergence needs
the threshold to cut inside a block: it does not appear with a key that is
monotone in row order, nor with a predicate tight enough to leave the top-K
heap below capacity, nor with `enable_multiple_prewhere_read_steps = 0`.
Two existing sites treat a stateful condition the same way. `FilterStep.cpp:292`
refuses to split an AND chain into multiple filter transforms when
`hasStatefulFunctions()`, and `filterPushDown.cpp:1137` refuses to push a
stateful filter down at all.
A stateful predicate that stays in the `WHERE` above the read is not affected
by this check and is unchanged from master: dynamic filtering installs its own
PREWHERE beneath the filter, so both arms produce
`Filter column: less(rowNumberInBlock(), 100_UInt8)` over
`Prewhere filter column: __topKFilter(k)` and both diverge the same way.
`rowNumberInBlock` is documented non-deterministic, and `max_block_size` alone
already changes that query's answer, so what the optimization should promise
for such a predicate is a semantics question rather than a defect here.
Three comments are corrected in the same commit. `installTopKDynamicFilter`
runs at `optimizeTree.cpp:559`, after the only pass that builds
`query_info.filter_actions_dag` for a non-FINAL MergeTree read
(`optimizePrimaryKeyConditionAndLimit` adds the storage PREWHERE and calls
`applyFilters` at `optimizePrimaryKeyConditionAndLimit.cpp:24,83`, run at
`optimizeTree.cpp:247`); the other `applyFilters` callers are FINAL-only and
`tryOptimizeTopK` returns 0 on FINAL. So `__topKFilter` can no longer reach
that DAG, and the docs claiming otherwise were stale. `isTopKFilterFunction`,
the strip branch and both copies of `isDeterministicAllowingTopKFilter` are
deliberately kept, because ClickHouse#114659 works in this area.
Also drops a dead `std::erase(outputs, filter_node)`: `addFunction` reaches
`addNode`, which appends only to `inputs` and only for INPUT nodes, so a
freshly built node cannot be among the cloned DAG's outputs.
…down # Conflicts: # src/Processors/QueryPlan/ReadFromMergeTree.cpp
…EWHERE it will execute Since #117968, `installTopKDynamicFilter` merges `__topKFilter` into the read's PREWHERE at the end of the second optimization pass. Projection candidate analysis runs before that, so it probed the cache under the PREWHERE without the filter, while the executed read writes its TopK-salted entries under `and(__topKFilter, ...)`. The keys never met and a warm projection-backed TopK query never reused the granules, which `05053_query_condition_cache_topk_projection_warm_reuse` caught on every job. Extract the construction of that PREWHERE into `buildTopKDynamicFilterPrewhere` and use it both in `installTopKDynamicFilter` and in `filterPartsByQueryConditionCache` for a read whose dynamic filter is still pending, so both sides derive the same condition hash. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=114659&sha=0be6c373974069050a6655298ed4d33ee9cd02e2&name_0=PR
`analyzeProjectionCandidate` and `filterPartsAndCollectProjectionCandidates` passed `use_query_condition_cache = true` to `estimateNumMarksToRead` even for a read that had called `disableQueryConditionCache` for correctness (vector search, lazy `FINAL`). Their result is reused by the projection read, so it pruned marks under a cache contract the read rejects. Pass the read's own gate. Addresses #114659 (comment)
| /// by normal reads: those may exclude a granule whose only matching rows are deleted. | ||
| || !settings[Setting::apply_deleted_mask] | ||
| || (!select_query_info.prewhere_info && !select_query_info.filter_actions_dag) | ||
| || (!prewhere_info_for_cache && !select_query_info.filter_actions_dag) |
There was a problem hiding this comment.
This still lets sampled TopK reads reuse unsampled query-condition-cache entries. The write side already turns QCC off once sampling is active (ReadFromMergeTree::initializePipeline and the index-analysis writer), but this consult path never mirrors that gate. With the new PREWHERE TopK entries, a warm SELECT ... ORDER BY k LIMIT 5 can cache later granules and a later SELECT ... SAMPLE 0.1 ORDER BY k LIMIT 5 will probe the same TopK-salted key and drop those granules before the sample-specific threshold is recomputed, even though the sample's top-N rows may live there. Please skip TopK QCC consults under SAMPLE as well, or include the effective sampling contract in the key.
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]>
A TopK-salted entry records granules without a row in the top N of the whole table. A `SAMPLE` read computes its threshold from a subset of the rows, whose top N can lie in exactly those granules, so reusing the entry dropped rows from the result. `filterPartsByQueryConditionCache` now takes `use_sampling` and, for a sampled read, consults only plain entries, which stay sound under sampling. The writers already skip sampled reads. Addresses ClickHouse#114659 (comment)
…ted read `ReadFromMergeTree::deserialize` passed `build_empty_step_for_distributed_read = true` for every read, so a non-bucketed read on an empty snapshot became a real empty `ReadFromMergeTree`. Master now handles that case itself (3034d31, ClickHouse#114659): a null step from `readFromParts` for a non-bucketed read is rebuilt as a `ReadNothingStep`, which `ReadFromMergeTreeQueryConditionCacheFlag.DeserializationOnEmptyTableIsEmptyRead` asserts. The unconditional flag bypassed that fallback and failed the test for both cache variants. Pass the flag only for a bucketed read (`distributed_read_bucket_count > 0`). That read is pinned to the coordinator's marks, so it still needs a real step for `initializePipeline` to check it (`NO_SUCH_DATA_PART` on divergence, an empty read otherwise) instead of hitting the `LOGICAL_ERROR`. A non-bucketed read falls through to master's `ReadNothingStep`. The comments that described the flag as covering every read, and master's note that a bucketed read keeps failing, are updated to match. 04371 now also sets `distributed_plan_prefer_replicas_over_workers = 1`: its failpoint lives in the replica deserializer, and in a Cloud build an eligible read is otherwise replaced by `ReadFromMergeTreeAtWorker` (makeDistributed.cpp), so the failpoint would never fire there. The setting is read only by Cloud code, so open-source runs are unaffected. Verified on the master merge f47d9f0: - flag `true` (previous head): DeserializationOnEmptyTableIsEmptyRead fails (2 failures). - flag `false`: 04371 aborts the server, `Logical error: 'ReadFromMergeTree step is expected to be created by readFromParts'`, signal 6 from `ReadFromMergeTree::deserialize`. - this commit: the 5 ReadFromMergeTreeQueryConditionCacheFlag tests and 157 related query-plan gtests pass; 04371 passes under random settings and with forced `index_granularity = 65536`. Addresses ClickHouse#110929 (comment) 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 to CHANGELOG.md):
Granules fully filtered by the dynamic threshold of an
ORDER BY ... LIMIT n(TopK) read are now recorded in the query condition cache, so repeat runs of such queries skip them at the mark-selection stage instead of re-reading and re-filtering most of the table. On the ClickBench Q24/Q26 shapes (SELECT SearchPhrase FROM hits WHERE SearchPhrase <> '' ORDER BY EventTime LIMIT 10), a warm run drops from ~95M rows / ~12000 granules read to ~1.3M rows / ~160 granules, and from ~15–30 ms to ~8 ms on a 96-core machine.The
ORDER BY ... LIMIT n(TopK) optimization pushes a dynamic__topKFilterthreshold into theMergeTreeread as a PREWHERE, dropping rows that cannot beat the running top-N. But the granules it emptied were never recorded in the query condition cache: the PREWHERE write path inMergeTreeSelectProcessor::readrejects non-deterministic conditions, and__topKFilteris one. Only the downstream WHEREFilterTransformwrote entries, at whole-chunk granularity, which learns almost nothing (a single surviving row voids the attribution of the whole chunk) — measured on hits, warm runs still selected 11766 of 12348 granules and re-read ~95M of 100M rows. The original out-of-tree build of this optimization (PR #81944, commit2e2f594308f4plus the follow-up making the TopN dynamic filters deterministic and reusable for the cache) recorded them and skipped ~98% of granules on warm runs — that is the 2–3x Q24/Q26 gap measured in issue #114639.Recording these granules is sound: for a fixed plan and data, the running threshold only tightens, so a granule none of whose rows survive the filter contains no row that could reach the final top-N, regardless of the threshold trajectory. The entries are keyed with the TopK plan salt (
TopKFilterInfo::condition_hash: sort column, type,LIMIT, direction,NULLSdirection, collation locale, number of sort columns, and the part-set snapshot), mirroring what the WHERE write path already does since #104478/#110507 — only the same TopK plan over the same part set ever reuses them.Changes:
isDeterministicAllowingTopKFilter(two identical static copies inupdateQueryConditionCache.cppandReadFromMergeTree.cpp) moved intoVirtualColumnUtils.MergeTreeReaderSettings::query_condition_cache_top_k_salt.__topKFilter-bearing condition when the salt is present, folding the salt into the cache key. Any other non-deterministic condition is still never cached.filterPartsByQueryConditionCache) applies the salt exactly when the PREWHERE contains__topKFilter, so the keys match the write side; deterministic user PREWHERE conditions keep using plain, unsalted entries shared with non-TopK queries.04217_query_condition_cache_topkand04242_query_condition_cache_topk_collatepin exact cache entry counts, which double (each TopK plan now writes a WHERE entry and a PREWHERE entry per part).04891_query_condition_cache_topk_prewhere_granulesisolates the PREWHERE write path with a WHERE-less TopK query (on current master such a query writes no cache entries at all), asserts that the ASC and DESC plans do not share granule decisions, and that a warm run selects fewer marks.topk_query_condition_cache.xmlwith the ClickBench Q24/Q26 shapes overhits_100m_single.Measured on the 100M-row single-part ClickBench
hits(96-core aarch64, hot, interleaved runs): warm Q24/Q26 at 0.007–0.009 s, on par with the original bench-opt build (0.009–0.011 s), against 0.015–0.03 s for current master; warm runs read 159 of 12348 granules against master's 11766. A first run with an empty cache shows no measurable overhead (0.016–0.019 s with the mechanism on and off).Closes: #114639
Related: #81944
Related: #110507
Workflow [PR]
Sync PR [sync-upstream/pr/114659]
Version info
26.10.1.831-master(included in26.10and later)