Skip to content

Disable the query condition cache for ORDER BY ... LIMIT n queries by default - #111492

Merged
alexey-milovidov merged 30 commits into
masterfrom
disable-qcc-for-topk
Aug 1, 2026
Merged

alexey-milovidov merged 30 commits into
masterfrom
disable-qcc-for-topk

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jul 22, 2026 •

Copy link
Copy Markdown
Member

Related: #104478
Related: #110507

Changelog category (leave one):

  • Improvement

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 for ORDER 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

  • Documentation is written (mandatory for new features)

What

Introduce the query-level setting use_query_condition_cache_for_top_k (Bool, default false) 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 with SET use_query_condition_cache_for_top_k = 1.

Why

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) 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's allow_query_condition_cache flag, which turns the cache off both for index analysis and for the reader. The flag (unlike the reader settings) is carried over by ReadFromMergeTree::clone, and clone also carries over top_k_filter_info, so a step cloned after the first optimization pass (materializeQueryPlanReferences for a common subplan reference, cloneSubtree for a parallel-replicas plan fragment) stays gated instead of degrading into an apparently plain read. updateQueryConditionCache needs no clone handling: it runs before those clones are made, so its decision is already baked into the FilterStep.
  • ReadFromMergeTree::createLocalParallelReplicasReadingStep — this replaces a ReadFromMergeTree step in place with a freshly constructed one, so it carries over allow_query_condition_cache and top_k_filter_info for the same reason clone does.
  • optimizeUseNormalProjections — this may replace a TopK-stamped read with a freshly constructed projection read, so it carries over allow_query_condition_cache and top_k_filter_info onto the new step, and the replaced read's top_k_filter_info is threaded through the projection candidate analysis (analyzeProjectionCandidate → estimateNumMarksToRead), whose internal filterPartsByQueryConditionCache consult is where the projection branch actually probes the cache.
  • ReadFromMergeTree::selectRangesToRead — do not record index-analysis QCC exclusions for TopK reads.
  • The pre-plan estimate that sizes automatic parallel replicas (parallel_replicas_min_number_of_rows_per_replica > 0) — this runs index analysis before tryOptimizeTopK stamps the read, so it cannot know whether the gate applies to the query. Analyzed as an apparent plain read it would reuse plain SELECT ... WHERE entries (changing rows_to_read, and with it max_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 by InterpreterSelectQuery::adjustParallelReplicasAfterAnalysis) passes use_query_condition_cache = false, and the analyzer counterpart in buildQueryPlanForTableExpression uses the new ReadFromMergeTree::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 of tryOptimizeTopK'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_cache now 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 by top_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 call disableQueryConditionCache.
  • MergeTreeDataSelectExecutor::filterPartsByQueryConditionCache — skip the QCC consult entirely for TopK reads. This also covers TopK plan shapes with no __topKFilter node folded into the filter DAG (skip-index-only plans and queries with a PREWHERE), whose plain condition hash would otherwise still match entries primed by an ordinary SELECT ... 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 = 1 so it still exercises the feature. A new test 04628_query_condition_cache_topk_default_off covers 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 plain WHERE queries keep using it. It includes a skip-index-only TopK shape (dynamic filtering off, minmax index on the sort column) where no __topKFilter is folded into the filter DAG, so the plain condition hash of the TopK read would match the plain WHERE entry without the read-side gate, and an existing-PREWHERE TopK shape that pins the (never TopK-salted) PREWHERE consult path the same way; both shapes were verified to catch the leak against a binary without the gate. The new setting is registered in SettingsChangesHistory with previous_value = false, because the gate is going to be backported to 26.7, so no compatibility profile should re-enable the query condition cache for TopK reads. A second new test 04631_query_condition_cache_topk_compatibility asserts that the default is off and that neither compatibility = '26.7' nor compatibility = '26.8' flips the gate on. A third new test 04647_query_condition_cache_topk_cloned_subplan pins the observable contract of the cloned-subplan shape (a correlated EXISTS decorrelated with correlated_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 a ParallelReplicasSplitStep directly above ReadFromMergeTree, which stops tryOptimizeTopK from matching, and a common subplan reference is always materialized below the sorting and limit steps — so the clone handling is an invariant fix rather than a fix for an observable wrong-results bug. A fourth new test 04651_query_condition_cache_topk_parallel_replicas_local pins the observable contract of the parallel_replicas_local_plan shape: 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 with clone, neither replacement site sees a TopK-stamped read today (createLocalPlanForParallelReplicas replaces the reads of a freshly built, unoptimized interpreter plan, and a shipped fragment has ParallelReplicasSplitStep directly above the read), so this too is an invariant fix. Both step-rebuild sites also carry over index_read_tasks for the same reason: processAndOptimizeTextIndexFunctions runs before materializeQueryPlanReferences, so a rebuilt step can already have a predicate rewritten to __text_index_* virtual columns that only that task map materializes. A fifth new test 04658_query_condition_cache_topk_normal_projection pins 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 test 04661_query_condition_cache_topk_parallel_replicas_estimate pins the pre-plan estimate: with parallel_replicas_min_number_of_rows_per_replica set 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

  • Backported to: 26.7.2.59

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

clickhouse-gh Bot commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [233573e]

Summary: ✅


AI Review

Summary

This PR adds use_query_condition_cache_for_top_k and does a broad sweep to keep TopK reads out of the query condition cache by default while preserving the opt-in path. The local rebuild sites that were previously discussed are fixed, but one distributed-plan rebuild path still reconstructs a TopK read as a plain read, so the contract is still incomplete.

Findings

❌ Blockers

  • [src/Processors/QueryPlan/ReadFromMergeTree.h:468] The TopK/QCC gate is now carried across clone, local parallel-replicas rebuilding, and normal-projection rebuilding, but distributed-plan deserialization still drops the same state. ReadFromMergeTree::serialize does not include top_k_filter_info or allow_query_condition_cache, and deserialize rebuilds a fresh step through readFromParts(...) with both fields reset. A make_distributed_plan worker therefore treats a TopK read as plain again: with use_query_condition_cache_for_top_k = 0, PREWHERE-based TopK shapes can still consult or populate the query condition cache there, and with the setting enabled the worker loses the TopK salt / part-set discriminator for QCC keys. Either serialize or re-derive that state on the worker, or reject distributed plans for TopK reads until they can reproduce it safely.
Final Verdict

Changes requested.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jul 22, 2026
@alexey-milovidov
alexey-milovidov marked this pull request as draft July 22, 2026 23:12
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]>
@alexey-milovidov alexey-milovidov changed the title Disable the query condition cache for ORDER BY ... LIMIT n queries Disable the query condition cache for ORDER BY ... LIMIT n queries by default Jul 22, 2026
@alexey-milovidov
alexey-milovidov marked this pull request as ready for review July 22, 2026 23:47
@alexey-milovidov

Copy link
Copy Markdown
Member Author

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):

  • 03742_nested_loop_join_long (Stateless amd_asan_ubsan, distributed plan, parallel): MEMORY_LIMIT_EXCEEDED in JoiningTransform — flaky on this check across many PRs and on master itself (two master runs failed the same day, 2026-07-22/23).
  • Stress test (arm_tsan) Logical error: Cannot determine row level filter (STID: 4390-4e70): stack is entirely in ReadFromMerge::RowPolicyData (StorageMerge.cpp); a known master bug with an open fix: Fix logical error on Merge table with a bare-column row policy #109843.
  • AST fuzzer (amd_msan) use-of-uninitialized-value: the crashing query is INNER JOIN ... STREAM with join_algorithm = 'direct', and the fuzzed run had use_query_condition_cache = 0, use_top_k_dynamic_filtering = 0, use_skip_indexes_for_top_k = 0 — the code this PR touches cannot be on the failing path. The MSan report lost its stack (nested bug, broken pipe), so it is hard to track further.

@groeneai, investigate the failures: 03742_nested_loop_join_long (https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111492&sha=1f9f9e0c14bca355fd9cf558efcb722aca37f1b9&name_0=PR&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20distributed%20plan%2C%20parallel%29) and the AST fuzzer MSan crash in JOIN ... STREAM with direct join (https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111492&sha=1f9f9e0c14bca355fd9cf558efcb722aca37f1b9&name_0=PR&name_1=AST%20fuzzer%20%28amd_msan%29) and provide fixes in separate PRs. If fixes are already in progress, link them here.

…_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]>
@groeneai

Copy link
Copy Markdown
Collaborator

@alexey-milovidov Acknowledged, investigating both; separate fix PRs will follow here.

  1. 03742_nested_loop_join_long (MEMORY_LIMIT_EXCEEDED in JoiningTransform): this is the residual of the distributed-plan sanitizer OOM you fixed in Fix distributed-plan sanitizer OOM: re-apply 0.7 memory ratio + cut concurrency #110574. That merge cut the 2026-07-15 spike (25 fails/day) down to ~1-4/day, but it still fires, including two master runs since (07-22, 07-23); 39 of 41 hits over 30d are on the amd_asan_ubsan, distributed plan, parallel variant. I will take the residual.
  2. AST fuzzer (amd_msan) use-of-uninitialized-value in JOIN ... STREAM direct join: the CI report lost its stack (broken pipe / nested bug), so I will recover a stack and a deterministic reproducer before proposing a fix. No fix PR exists yet.

@groeneai

Copy link
Copy Markdown
Collaborator

The AST-fuzzer amd_msan use-of-uninitialized-value (the INNER JOIN ... STREAM with join_algorithm='direct' failure) is a pre-existing direct-join bug, unrelated to this PR. Reproduced it locally on an MSan build and opened a fix: #111622. Root cause: the strip-parts optimization in ReadFromMergeTree::initializePipeline mutated a StorageSnapshot shared across the cloned direct-join lookup plans, so an overlapping pipeline rebuild read a destroyed SnapshotData.

@groeneai

Copy link
Copy Markdown
Collaborator

Fix for 03742_nested_loop_join_long (first failure): #111644.

Root cause is not this PR. It is a server-wide OvercommitTracker rejection on Stateless tests (amd_asan_ubsan, distributed plan, parallel): the aggregate RSS of the heavy tests co-scheduled on one memory-capped sanitizer server (ratio cut in #110574) overruns the cap, and the tracker stops a query mid-JoiningTransform. The stopped query only needs 0.6-5.5 GiB; the server is already at ~44.8 GiB. Evidence it is aggregate pressure: the same build's parallel, 2/2 split variant (half the tests per server) has 0 failures over 30 days, the unsplit variant has 40.

03742 is one of the heaviest contributors: its INNER events JOIN attributes fans a small left table against attributes (800K/300K rows per key) into a 37.1M-row result the direct join materializes as one ~1.2 GiB chunk. #111644 shrinks only the left row count (numbers(100) -> numbers(12)), cutting the fan-out to 4.4M and the peak to ~400 MiB (~3x), keeping the direct-join algorithm, all four strictnesses, and the large attributes/events2 cases. #110574 already cut this shard's concurrency to its floor, and the direct join does not split its output by max_block_size, so lowering the test's own peak is the remaining lever. Note ~11 other tests are OvercommitTracker victims on this same shard; this addresses 03742's share.

The second failure (AST fuzzer amd_msan use-of-uninit in the direct join via JOIN ... STREAM) is being handled separately.

… 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]>
Comment thread src/Core/Settings.cpp Resolved
alexey-milovidov and others added 3 commits July 23, 2026 19:39
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]>
@mintlify

mintlify Bot commented Jul 23, 2026

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated (UTC)
ClickHouse-docs 🟢 Ready View Preview Jul 23, 2026, 11:21 PM

@alexey-milovidov

Copy link
Copy Markdown
Member Author

CI triage for the latest run (commit 32b5248) and the fix pushed in 252a6df:

Comment thread src/Core/SettingsChangesHistory.cpp Resolved
`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.
@alexey-milovidov
alexey-milovidov requested a review from a team as a code owner July 31, 2026 22:45
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 CI triage for c7abdc7416d, and the review blocker on the parallel-replicas estimate is fixed and pushed in d62c47cc3db + 233573eb641.

PR-caused (fixed). My own new test 04658_query_condition_cache_topk_normal_projection failed in 6 checks (all 4 flaky checks and amd_msan, WasmEdge, sequential), always with the "projection was used" column at 0:

-04658_topk_write_1	0	1
+04658_topk_write_1	0	0
-04658_plain_prime	1
+04658_plain_prime	0

Root cause: the settings randomization sets optimize_use_projections = False, and force_optimize_projection is only checked (and the rewrite only runs) when projections are allowed at all — so the projection shape the test covers never ran. Fixed by pinning SET optimize_use_projections = 1 in the test.

Review blocker (fixed). MergeTreeData::estimateNumberOfRowsToRead passing std::nullopt was correctly flagged. Closing it needed two changes, both pushed:

  1. Both pre-plan parallel-replicas estimate paths now keep the cache out of a query which may still become a TopK read — the estimate runs before tryOptimizeTopK, so it cannot know whether the gate applies. The analyzer counterpart in buildQueryPlanForTableExpression uses the new ReadFromMergeTree::estimateRangesToReadWithoutQueryConditionCache, which also keeps the throwaway analysis out of the step, so a query which turns out not to be TopK still gets the cache for the read that executes.
  2. ReadFromMergeTree::allow_query_condition_cache did not actually gate the consult — it only turned the cache off for the reader, while selectRangesToRead called filterPartsByQueryConditionCache regardless (for a TopK read the consult was gated separately, by top_k_filter_info). So (1) alone did not stop the estimate from hitting plain entries; verified from the trace log. The flag now suppresses the consult too, which is what it already claimed to mean.

New test 04661_query_condition_cache_topk_parallel_replicas_estimate pins this; it is discriminating (one QueryConditionCacheHits before the fix, zero after).

Unrelated reds on c7abdc7416d:

  • Stateless tests (amd_msan, WasmEdge, parallel, 2/2), 03622_distributed_index_analysis_applies_skip_indexes: Timeout, i.e. the test exceeded its time limit under MSan. Per CIDB it also timed out twice on the unrelated More settings to randomize #106734 in the last two weeks, and it is not near anything this PR changes (the query condition cache is off by default, so the branch's code paths are inert for it). No tracking issue found.
  • Performance Comparison (arm_release, master_head, 4/6): job ERROR before any test ran — botocore.exceptions.ClientError: An error occurred (ConditionalRequestConflict) when calling the PutObject operation from praktika's versioned result upload (ci/praktika/s3.py:648), i.e. two shards racing on the same S3 result object. Infrastructure, not a query regression. No tracking issue found.

@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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@groeneai, if this is relevant, please fix.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator

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 ConditionalRequestConflict onto the same retry path PreconditionFailed already takes, in both the boto3 branch (s3.py:673, the one that raised here) and the AWS-CLI branch (s3.py:278). That is exactly the raise site in this traceback.

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 result.py:1474 and the 48th happened to be rejected as an in-flight conflict rather than a stale read: 41 attempts died on the local version check, 7 on PreconditionFailed, 3 saw the conflict. Between attempt 1 and attempt 48 the object went from version 99 to 187, so 88 competing writes committed while this job committed none, in 88 seconds. MAX_ATTEMPTS = 50 with a flat random.uniform(0, 2) backoff does not converge under that write rate, and each attempt re-downloads result_pr.json first, so the loser is slower than every winner. #112786 stops the uncaught exception, and after it a starved job will exhaust 50 attempts and report no_strict instead. Worth deciding separately whether starvation should also be fixed (a bounded exponential backoff, or batching the per-shard updates); I can send that as its own PR if you want it.

Stateless tests (amd_msan, WasmEdge, parallel, 2/2), 03622_distributed_index_analysis_applies_skip_indexes: no fix PR exists, I am opening one. Two corrections to the triage.

It is not a timeout. The runner reason is having stderror:, which is FailureReason.STDERR in tests/clickhouse-test:1300, a different branch from FailureReason.TIMEOUT. The test ran in 52.7s against a 600s per-test budget, and the long tag it carries exempts it from the 180s TEST_MAX_RUN_TIME_IN_SECONDS cap anyway. The word Timeout in the report is inside the message, not the verdict: the single stderr line is

<Warning> DistributedIndexAnalysis: Cannot connect to 127.0.0.2:9000. It will not participate in
distributed index analysis: Code: 209 ... Timeout exceeded while reading from socket ... 10000 ms

That 10000 ms is handshake_timeout_ms (Connection.cpp:264), so the second replica did not complete the handshake. The stateless runner passes --send_logs_level=warning by default, the warning is logged at LogsLevel::warning (distributedIndexAnalysis.cpp:456), so it reaches the client's stderr and any non-empty stderr fails the test.

It is also not only a stderr problem. The stdout diverged too: the distributed_index_analysis=1 plan printed an empty Address: with Parts send: 0, then 127.0.0.1:9000 with Parts send: 100 / received: 20, where the reference pins 127.0.0.2:9000 with 44/12 and 127.0.0.1:9000 with 56/8. Correct behaviour under a dead replica, but the reference hardcodes the two-replica split, so suppressing the warning alone would only move the failure to a result diff.

The last two --send_logs_level=warning bits are worth noting on their own: 11 of the 16 .sql tests in this family already pin send_logs_level='error' for precisely this, and 03622_distributed_index_analysis_fallback_to_localhost.sql:12 carries the comment "Ignore Cannot analyze parts on {} replica". This test and 4 siblings (03622_..._additional_table_filters, 03623_..._merge_tree_settings, 04004_dist_index_analysis_poisons_query_condition_cache, 04054_..._partition_pruning) do not, so the same handshake miss reddens any of them.

The two-prior-hits precedent does not apply. Those rows (on the PR cited above) are result differs, not this signature, and their diff is a Min-Max step appearing under Indexes: from randomized auto_statistics_types, which is the family this test's own comment about use_statistics_for_part_pruning refers to. Keyed on this warning, CIDB has one hit in 45 days, no master hits, so it is new surface.

I will send the fix as a separate PR: pin send_logs_level='error' and make the assertion tolerate a replica that fails to connect, so the test asserts the split it cares about without pinning a per-address row that a dead replica erases. I will post the link here.

@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 167/168 (99.40%) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator

The fix PR for 03622_distributed_index_analysis_applies_skip_indexes is #112879.

It does both halves as described: pins send_logs_level='error', and replaces the per-replica assertion with select * from (explain indexes=1 ...) where explain not like '%Address:%' and ... so the aggregate Parts:/Granules: are asserted without pinning an address a dead replica erases. 03622_distributed_index_analysis_additional_table_filters has the identical defect and is fixed in the same PR, since those two are the only reference files pinning per-replica rows in plain-text EXPLAIN output for a two-replica cluster.

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 DistributedIndexAnalysisReplicaFallback and DistributedIndexAnalysisMissingParts from system.query_log; both are incremented only after a replica connects, so they are unaffected by whether 127.0.0.2 is up. A mutation that forces the remote analysis to throw with both replicas up reddens that assertion alone.

No PR is owed for the Performance Comparison failure: #112786 already widens the retry to ConditionalRequestConflict at the call site that raised.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 1, 2026
Merged via the queue into master with commit 4b1ef7f Aug 1, 2026
179 checks passed
@alexey-milovidov
alexey-milovidov deleted the disable-qcc-for-topk branch August 1, 2026 14:41
@robot-ch-test-poll robot-ch-test-poll added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Aug 1, 2026
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Aug 1, 2026
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 1, 2026
clickhouse-gh Bot pushed a commit that referenced this pull request Aug 2, 2026
clickhouse-gh Bot added a commit that referenced this pull request Aug 2, 2026
Backport #111492 to 26.7: Disable the query condition cache for `ORDER BY ... LIMIT n` queries by default
pull Bot pushed a commit to AKJUS/ClickHouse that referenced this pull request Aug 10, 2026
…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]>
anandheritage pushed a commit to anandheritage/ClickHouse that referenced this pull request Aug 13, 2026
…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]>

This branch was successfully deployed

1 active deployment
staging - docs — 233573eb Deployed Jul 31, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-improvement Pull request with some product improvements pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.7-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants