Repository navigation
Disable the query condition cache for ORDER BY ... LIMIT n queries by default - #111492
Conversation
This disables (without reverting) the feature that enabled the query condition cache (QCC) for queries going through the TopK dynamic-filtering plan (`ORDER BY <column> LIMIT n`), added in PR #104478 and extended in PR #110507. A TopK read can drop granules during execution depending on the running `__topKFilter` threshold, which is derived from the rows of all parts the query reads. QCC entries are keyed by `(table_uuid, part_name, condition_hash)` and are threshold-oblivious, so a granule-skip decision recorded under one threshold (or one set of parts) can be reused when it no longer holds. The feature added salting of the cache key with the TopK plan parameters and a part-set snapshot to make this sound, but out of caution we turn the feature off in the stable release until its soundness is fully established. Rather than reverting, this restores the pre-#104478 behavior at each QCC touch point while keeping all of the added infrastructure (the salting helpers, `TopKFilterInfo::condition_hash`, the part-set snapshot hashing, the predicate-only reuse path) in place but inert: - `updateQueryConditionCache`: skip the QCC write for the WHERE filter of a TopK-filtered read (early return, as before #104478). - `ReadFromMergeTree::setTopKColumn`: turn off `use_query_condition_cache` in the reader settings, so execution-time QCC writes/consults are disabled for TopK reads. - `ReadFromMergeTree::selectRangesToRead`: do not record index-analysis QCC exclusions for TopK reads (their excluded ranges depend on the threshold). - `MergeTreeDataSelectExecutor::filterPartsByQueryConditionCache`: consult the WHERE condition with the plain (unsalted) hash and do not take the predicate-only reuse path. The stateless and performance tests that assert QCC caching for TopK reads are removed; a revert of this change cleanly re-enables the feature together with its tests. The change is behavior-only for TopK reads: for non-TopK reads none of these code paths differ from current master. Related: #104478 Related: #110507 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Workflow [PR], commit [233573e] Summary: ✅
AI ReviewSummaryThis PR adds Findings❌ Blockers
Final VerdictChanges requested. |
Replace the hard-coded disable from the previous commit with a proper setting, `use_query_condition_cache_for_top_k` (default `false`), that enables/disables the query condition cache (QCC) for queries going through the TopK dynamic-filtering plan (`ORDER BY <column> LIMIT n`). The feature (added in PR #104478 and extended in PR #110507) is thus disabled by default without removing it or its tests. When the setting is off, each QCC touch point for TopK reads restores the pre-#104478 behavior; when it is on, the current master behavior (salted QCC entries) is used. The gated points are: - `updateQueryConditionCache`: skip the QCC write for the WHERE filter of a TopK read. - `ReadFromMergeTree::setTopKColumn`: turn off `use_query_condition_cache` in the reader settings for the read. - `ReadFromMergeTree::selectRangesToRead`: do not record index-analysis QCC exclusions for TopK reads. - `MergeTreeDataSelectExecutor::filterPartsByQueryConditionCache`: consult the WHERE condition with the plain (unsalted) hash and skip the predicate-only reuse path. The stateless and performance tests for the feature are kept; each now sets `use_query_condition_cache_for_top_k = 1` so it still exercises the feature. The new setting is registered in `SettingsChangesHistory` for 26.7. Related: #104478 Related: #110507 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
ORDER BY ... LIMIT n queriesORDER BY ... LIMIT n queries by default
|
CI triage — all three failures are unrelated to this PR (which only gates the query condition cache for TopK reads behind a default-off setting):
@groeneai, investigate the failures: |
…_for_top_k` Address review: all retained TopK/QCC tests opt back into `use_query_condition_cache_for_top_k = 1`, so a wiring mistake in the gated call sites would go unnoticed. The new test `04628_query_condition_cache_topk_default_off` pins the gate to its default value and asserts that a TopK read neither reuses an entry primed by a plain `SELECT ... WHERE` with the same predicate nor writes any entry into `system.query_condition_cache`, while plain `WHERE` queries keep using the cache (positive control). Co-Authored-By: Claude Fable 5 <[email protected]>
|
@alexey-milovidov Acknowledged, investigating both; separate fix PRs will follow here.
|
|
The AST-fuzzer |
|
Fix for Root cause is not this PR. It is a server-wide OvercommitTracker rejection on
The second failure (AST fuzzer amd_msan use-of-uninit in the |
… gate is off `tryOptimizeTopK` stamps a plan as TopK for both the dynamic-filtering and the skip-index-only paths, but for skip-index-only shapes (or a query with a `PREWHERE`) no `__topKFilter` node is folded into the filter DAG, so consulting `filterPartsByQueryConditionCache` with the plain condition hash could still hit entries primed by an ordinary `SELECT ... WHERE` even with `use_query_condition_cache_for_top_k = 0`. Short-circuit the consult for any read stamped as TopK when the setting is off, so a TopK read neither reads nor writes the query condition cache by default, as the PR contract states. Extend `04628_query_condition_cache_topk_default_off` with a skip-index-only TopK shape (dynamic filtering off, minmax index on the sort column) that pins this path: verified that with the gate on the same read hits the plain-primed entry via the predicate-only reuse path, and with the gate off it does not. Co-Authored-By: Claude Fable 5 <[email protected]>
On the private sync flaky check this test ran 186s, past the 180s per-run "test runs too long" limit, on the slower `SharedCatalog` + `meta in keeper` + `s3 storage` + sanitizer configuration. It was the only 1M-row TopK-QCC test missing the `long` tag. Two independent fixes: * Tag the test `long`, which exempts it from the flaky-check "test runs too long" threshold, matching the sibling `04217_query_condition_cache_topk` family. * Trim the dataset from 1,000,000 to 100,000 rows. With `max_threads = 1` the granule recording is deterministic, so the smaller volume is enough: the QCC still populates, the second read hits the cache, and ~667 of ~1.5k granules are dropped, matching the QCC-off ground truth for all three plans (`ASC LIMIT 5`, `ASC LIMIT 12`, `DESC LIMIT 5`). Verified stable across 10 consecutive runs. The `DESC LIMIT 5` reference values track the row count (`999007..` -> `99007..`); the `ASC` values are row-count-independent. Co-Authored-By: Claude Opus 4.8 <[email protected]>
The `PREWHERE` probe in `filterPartsByQueryConditionCache` is a separate consult path from the WHERE probe and is never TopK-salted, so a TopK read over an existing `PREWHERE` (stamped through the skip index, since dynamic filtering does not apply to reads that already have a `PREWHERE`) could reuse an entry primed by a plain `PREWHERE` query before the read-side gate was added. Extend `04628_query_condition_cache_topk_default_off` with this shape, on both the read side and the write side. Verified against a binary without the gate that the new `04628_pw_topk_after_prime` assertion flips to 1, i.e. the shape pins the leak independently of the skip-index-only WHERE shape. Also mention in the `use_query_condition_cache_for_top_k` description that the gate covers both TopK flavors (dynamic filtering and skip-index based) and that a TopK read neither consults nor populates the cache when it is off. Co-Authored-By: Claude Fable 5 <[email protected]>
…uide The guide did not mention that `ORDER BY ... LIMIT n` (TopK) reads — whether through dynamic filtering or a minmax skip index on the sort column — are excluded from the query condition cache by default and are gated behind `use_query_condition_cache_for_top_k`. Co-Authored-By: Claude Fable 5 <[email protected]>
|
Preview deployment for your docs. Learn more about Mintlify Previews.
|
…m 26.7 to 26.8 The 26.7 release is out and master is now 26.8, so the Upgrade check (https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111492&sha=32b52483ee7f22aa2d2d993582586c423ff4e01d&name_0=PR&name_1=Upgrade%20check%20%28amd_release%29) no longer counts an entry in the 26.7 section as a change for the upgrade. Co-Authored-By: Claude Fable 5 <[email protected]>
|
CI triage for the latest run (commit 32b5248) and the fix pushed in 252a6df:
|
`ReadFromMergeTree::allow_query_condition_cache` only turned the cache off for the reader, while `selectRangesToRead` still called `filterPartsByQueryConditionCache`, so a read with the cache disabled could still skip granules based on entries written by other queries. For a TopK read the consult was gated separately (by `top_k_filter_info` plus `use_query_condition_cache_for_top_k`), so this only surfaced for the pre-plan parallel-replicas estimate, whose analysis has no TopK stamp yet: it consulted plain `SELECT ... WHERE` entries despite being asked not to use the cache. Verified with `04661_query_condition_cache_topk_parallel_replicas_estimate`, which goes from one cache hit to none.
|
🕵 CI triage for PR-caused (fixed). My own new test Root cause: the settings randomization sets Review blocker (fixed).
New test Unrelated reds on
@groeneai, investigate the two failures above — https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111492&sha=c7abdc7416d4ee262cfd874cf2b5d672f3e3eeb2&name_0=PR&name_1=Stateless%20tests%20%28amd_msan%2C%20WasmEdge%2C%20parallel%2C%202%2F2%29 and https://s3.amazonaws.com/clickhouse-test-reports/PRs/111492/c7abdc7416d4ee262cfd874cf2b5d672f3e3eeb2/performance_comparison_arm_release_master_head_4_6/job.log — and provide fixes in separate PRs. If either fix is already in progress, link it here. |
| /// `setTopKColumn` again would fold the part-set salt in twice. | ||
| void copyTopKFilterInfoAndQueryConditionCacheGate(const ReadFromMergeTree & replaced_step) | ||
| { | ||
| top_k_filter_info = replaced_step.top_k_filter_info; |
There was a problem hiding this comment.
copyTopKFilterInfoAndQueryConditionCacheGate fixes the projection/local-rebuild sites, but make_distributed_plan still has another ReadFromMergeTree rebuild that drops the same state. ReadFromMergeTree::serialize does not write either top_k_filter_info or allow_query_condition_cache, and deserialize reconstructs a fresh step through readFromParts(...) with both fields back at their defaults.
That means any distributed fragment containing a TopK-stamped read arrives on the worker as an apparent plain read again: with the default use_query_condition_cache_for_top_k = 0, a TopK query that has an existing PREWHERE can still consult/populate the query condition cache there, and with the setting enabled the worker loses the TopK salt / part-set discriminator entirely. Please either preserve or re-derive this state on the distributed-plan path, or reject make_distributed_plan for TopK reads until the worker can reproduce it.
There was a problem hiding this comment.
Not relevant - the gap is unreachable, so there is nothing to fix.
ReadFromMergeTree::serialize indeed writes neither field, and deserialize rebuilds through readFromParts with top_k_filter_info = nullopt and allow_query_condition_cache = true. But a TopK-stamped read can never reach that serializer, because tryOptimizeTopK refuses to stamp anything when the plan is going to be distributed (optimizeTopK.cpp:30):
if (settings.make_distributed_plan)
return 0;That guard predates this PR and is not something it touched. The ordering makes it airtight: tryOptimizeTopK runs only from the getOptimizations() loop in optimizeTreeFirstPass (optimizeTree.cpp:136), whereas tryMakeDistributedRead runs in optimizeTreeSecondPass (optimizeTree.cpp:363). So the stamp is suppressed strictly before distribution, and it cannot be reintroduced afterwards - the single-stage re-optimization in QueryPlan::convertToDistributed calls only optimizeTreeSecondPass, which never iterates that array.
Measured on merged master, EXPLAIN actions=1 for SELECT a FROM t WHERE b > 5 ORDER BY a LIMIT 3 with use_skip_indexes_for_top_k = 1, use_top_k_dynamic_filtering = 1:
make_distributed_plan = 0->Prewhere filter column: __topKFilter(a)make_distributed_plan = 1->Prewhere filter column: b > 5
Both stated consequences depend on a stamp that does not exist on this path, so neither is reachable: there is no salt or part-set discriminator to lose, and the read the worker rebuilds is a genuinely plain read rather than a TopK read masquerading as one. The allow_query_condition_cache half is the same story from the other direction - deserialize defaulting it to true is correct precisely because no TopK stamp survives to require otherwise, and the remaining disableQueryConditionCache callers (lazy FINAL, vector search, JOIN lookup) are all unrelated to TopK. I checked those too: each either does not apply to a distributed plan (verified by EXPLAIN - the lazy-FINAL and vector-search rewrites are simply absent under make_distributed_plan = 1) or builds its own local step that is never serialized.
The suggested alternative of rejecting make_distributed_plan for TopK reads is also already the effective behaviour, just implemented as "do not apply the optimization" rather than "throw" - which is the better of the two, since the query still runs, only without TopK acceleration.
|
Both investigated. One already has a fix PR open; the other needs one, and its cause is not the one in the triage above. Performance Comparison (arm_release, master_head, 4/6): already fixed in #112786 (@ rienath, open, opened ~4.5h before your comment). It maps Reading the job log, though, the conflict is the last event, not the cause. The job lost all 48 attempts of the retry loop in Stateless tests (amd_msan, WasmEdge, parallel, 2/2), It is not a timeout. The runner reason is That 10000 ms is It is also not only a stderr problem. The stdout diverged too: the The last two The two-prior-hits precedent does not apply. Those rows (on the PR cited above) are I will send the fix as a separate PR: pin |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 167/168 (99.40%) · Uncovered code |
|
The fix PR for It does both halves as described: pins One thing beyond the plan: filtering those rows away removes the only evidence that the remote replica analyzed its own parts rather than silently deferring to the initiator, because the fallback path only logs at warning level and the aggregate counters look the same either way. Each test therefore also asserts No PR is owed for the Performance Comparison failure: #112786 already widens the retry to |
…R BY ... LIMIT n` queries by default
Backport #111492 to 26.7: Disable the query condition cache for `ORDER BY ... LIMIT n` queries by default
…tic placement The test asserts that the first `ORDER BY k ASC LIMIT 5` run under the TopK plan writes a query condition cache entry (`count() > 0`). An entry is only written when at least one chunk is reduced to zero rows at the `WHERE` filter, which depends on where the smallest `w = 7` rows happen to land: placement was `rand()`, so a run could get a `__topKFilter` threshold trajectory under which every chunk kept at least one row and no entry was written (2 of 300 runs in a local loop on a release build). ClickHouse#111492 made this much more likely by shrinking the table from 1M rows (~123 chunks per scan) to 100k (~12 chunks); the same mode had been seen once with 1M rows on a flaky-check job before that. Place the five smallest `w = 7` rows at the front of the part and scatter every other row with a deterministic hash above the first chunk: the threshold tracker arms at its final value (`k = 4007`) right after the first chunk, and every later chunk deterministically empties at the `WHERE` filter and is recorded (1436 of 1564 marks). Verified locally: 30/30 runs pass, plus 10/10 with the failing run's randomized settings; the reference output is unchanged. Failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112958&sha=ab076f814382fccafac0dd27dbe5e152d7204619&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20sequential%2C%202%2F2%29 PR with the failure: ClickHouse#112958 Co-Authored-By: Claude Fable 5 <[email protected]>
…y default `use_query_condition_cache_for_top_k` was introduced by ClickHouse#111492 and defaulted to `false` as a precaution while the soundness of the cache entries written by a TopK read was being established. Those entries are partitioned by the TopK plan parameters and by a snapshot of the set of parts read, so only a query with the same plan over the same parts reuses them; the gate is no longer needed and the default becomes `true`. The setting and all of the gating it drives are kept, so the cache can still be kept out of TopK reads with `use_query_condition_cache_for_top_k = 0`, and the tests covering that configuration are kept as well (they already pinned the setting explicitly). The tests of the feature itself no longer have to enable it. The settings-history entry keeps `previous_value = false`, because the gate was backported to 26.7: `compatibility` with 26.7 or earlier still turns the cache off for TopK reads, while `compatibility = '26.8'` keeps it on. Reverts: ClickHouse#111492 Related: ClickHouse#104478 Related: ClickHouse#110507 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Related: #104478
Related: #110507
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Added the setting
use_query_condition_cache_for_top_k(default disabled) which gates the query condition cache forORDER BY ... LIMIT n(TopK) queries. This turns the feature off by default as a precaution until the soundness of its cache entries is fully established, while keeping it available behind the setting.Documentation entry for user-facing changes
What
Introduce the query-level setting
use_query_condition_cache_for_top_k(Bool, defaultfalse) that enables/disables the query condition cache (QCC) for queries that go through the TopK dynamic-filtering plan (ORDER BY <column> LIMIT n), added in #104478 and extended in #110507. The feature is thus disabled by default without removing it or its tests — it can be turned back on per-query or per-profile withSET use_query_condition_cache_for_top_k = 1.Why
A TopK read can drop granules during execution depending on the running
__topKFilterthreshold, which is derived from the rows of all parts the query reads. QCC entries are keyed by(table_uuid, part_name, condition_hash)and are threshold-oblivious, so a granule-skip decision recorded under one threshold (or one set of parts) could be reused when it no longer holds. The feature salts the cache key with the TopK plan parameters and a part-set snapshot to make this sound; out of caution we keep the feature off by default until that soundness is fully established.How
When the setting is off, the query condition cache does not interact with TopK reads at all — they neither consult nor populate it (stricter than the pre-#104478 behavior, where such reads participated as plain reads); when it is on, the current behavior (salted QCC entries) is used. The gated points are:
updateQueryConditionCache— skip the QCC write for the WHERE filter of a TopK-filtered read.ReadFromMergeTree::setTopKColumn— clear the step'sallow_query_condition_cacheflag, which turns the cache off both for index analysis and for the reader. The flag (unlike the reader settings) is carried over byReadFromMergeTree::clone, andclonealso carries overtop_k_filter_info, so a step cloned after the first optimization pass (materializeQueryPlanReferencesfor a common subplan reference,cloneSubtreefor a parallel-replicas plan fragment) stays gated instead of degrading into an apparently plain read.updateQueryConditionCacheneeds no clone handling: it runs before those clones are made, so its decision is already baked into theFilterStep.ReadFromMergeTree::createLocalParallelReplicasReadingStep— this replaces aReadFromMergeTreestep in place with a freshly constructed one, so it carries overallow_query_condition_cacheandtop_k_filter_infofor the same reasonclonedoes.optimizeUseNormalProjections— this may replace a TopK-stamped read with a freshly constructed projection read, so it carries overallow_query_condition_cacheandtop_k_filter_infoonto the new step, and the replaced read'stop_k_filter_infois threaded through the projection candidate analysis (analyzeProjectionCandidate→estimateNumMarksToRead), whose internalfilterPartsByQueryConditionCacheconsult is where the projection branch actually probes the cache.ReadFromMergeTree::selectRangesToRead— do not record index-analysis QCC exclusions for TopK reads.parallel_replicas_min_number_of_rows_per_replica > 0) — this runs index analysis beforetryOptimizeTopKstamps the read, so it cannot know whether the gate applies to the query. Analyzed as an apparent plain read it would reuse plainSELECT ... WHEREentries (changingrows_to_read, and with itmax_parallel_replicas) and record its own index-analysis exclusions back under the plain condition hash. Both estimate paths now keep the cache out of a query which may still become a TopK read:MergeTreeData::estimateNumberOfRowsToRead(used byInterpreterSelectQuery::adjustParallelReplicasAfterAnalysis) passesuse_query_condition_cache = false, and the analyzer counterpart inbuildQueryPlanForTableExpressionuses the newReadFromMergeTree::estimateRangesToReadWithoutQueryConditionCache, which additionally keeps the throwaway analysis out of the step so the read that executes analyzes again with the gate that matches its final shape. The TopK-candidate check there is a deliberate over-approximation oftryOptimizeTopK's plan pattern (whose sorting and limit steps do not exist yet): a query which turns out not to be a TopK read only loses the cache for the estimate, never for the read that executes.ReadFromMergeTree::allow_query_condition_cachenow also suppresses the consult (filterPartsByQueryConditionCache), not only the reader. The flag means "this read does not use the cache", so it must not skip granules based on entries written by other queries either; for a TopK read the consult was already gated bytop_k_filter_info, so the only behavior this changes is that of reads which disable the cache without a TopK stamp — the estimate above, and the existing lazy-final / vector-search / direct-join-lookup reads that calldisableQueryConditionCache.MergeTreeDataSelectExecutor::filterPartsByQueryConditionCache— skip the QCC consult entirely for TopK reads. This also covers TopK plan shapes with no__topKFilternode folded into the filter DAG (skip-index-only plans and queries with aPREWHERE), whose plain condition hash would otherwise still match entries primed by an ordinarySELECT ... WHERE.For non-TopK reads, none of these code paths differ from current master.
The stateless and performance tests for the feature are kept; each now sets
use_query_condition_cache_for_top_k = 1so it still exercises the feature. A new test04628_query_condition_cache_topk_default_offcovers the default-off contract: with the gate at its default value, a TopK read neither reuses a plain-WHERE-primed entry nor writes any entry into the cache, while plainWHEREqueries keep using it. It includes a skip-index-only TopK shape (dynamic filtering off, minmax index on the sort column) where no__topKFilteris folded into the filter DAG, so the plain condition hash of the TopK read would match the plainWHEREentry without the read-side gate, and an existing-PREWHERETopK shape that pins the (never TopK-salted)PREWHEREconsult path the same way; both shapes were verified to catch the leak against a binary without the gate. The new setting is registered inSettingsChangesHistorywithprevious_value = false, because the gate is going to be backported to 26.7, so nocompatibilityprofile should re-enable the query condition cache for TopK reads. A second new test04631_query_condition_cache_topk_compatibilityasserts that the default is off and that neithercompatibility = '26.7'norcompatibility = '26.8'flips the gate on. A third new test04647_query_condition_cache_topk_cloned_subplanpins the observable contract of the cloned-subplan shape (a correlatedEXISTSdecorrelated withcorrelated_subqueries_use_in_memory_buffer = 0): the cloned read returns the same rows as the plain TopK read and keeps using the cache as a plain read, while the TopK read of the same predicate still writes no entry and does not reuse the entry the cloned-subplan query primed. Note that no reachable plan shape clones a TopK-stamped read today — a plan-based parallel-replicas read has aParallelReplicasSplitStepdirectly aboveReadFromMergeTree, which stopstryOptimizeTopKfrom matching, and a common subplan reference is always materialized below the sorting and limit steps — so theclonehandling is an invariant fix rather than a fix for an observable wrong-results bug. A fourth new test04651_query_condition_cache_topk_parallel_replicas_localpins the observable contract of theparallel_replicas_local_planshape: it returns the same rows as the plain read, a TopK read through it writes no cache entry and does not reuse an entry primed by a plain read, with the plain read reusing its own entry as a positive control. As withclone, neither replacement site sees a TopK-stamped read today (createLocalPlanForParallelReplicasreplaces the reads of a freshly built, unoptimized interpreter plan, and a shipped fragment hasParallelReplicasSplitStepdirectly above the read), so this too is an invariant fix. Both step-rebuild sites also carry overindex_read_tasksfor the same reason:processAndOptimizeTextIndexFunctionsruns beforematerializeQueryPlanReferences, so a rebuilt step can already have a predicate rewritten to__text_index_*virtual columns that only that task map materializes. A fifth new test04658_query_condition_cache_topk_normal_projectionpins the observable half of the normal-projection shape: with the gate off, a TopK query answered through a normal projection writes no cache entry, while the same plain projection read does (positive control). The consult half of that shape has no observable discriminator today — reader-level entries for projection parts are written under a<parent_part>:<projection>key while the analysis-time consult probes the bare projection part name, so a probe cannot hit — and is gated for the invariant only. A sixth new test04661_query_condition_cache_topk_parallel_replicas_estimatepins the pre-plan estimate: withparallel_replicas_min_number_of_rows_per_replicaset above the table size (so the estimate concludes that one replica is enough and the query then runs locally, isolating the estimate from follower-side reads), a gate-off TopK query writes no cache entry and gets no cache hit after a plain read primed one, while the plain read reuses its own entry as a positive control. This shape was verified to be discriminating: before the fix the same test reports one cache hit for the TopK query. The query condition cache guide documents the TopK gate.Version info
26.7.2.59