Skip to content

Record TopK-filtered granules in the query condition cache - #114659

Merged
fm4v merged 49 commits into
masterfrom
topn-threshold-pushdown
Sep 27, 2026
Merged

fm4v merged 49 commits into
masterfrom
topn-threshold-pushdown

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 13, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Performance Improvement

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 __topKFilter threshold into the MergeTree read 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 in MergeTreeSelectProcessor::read rejects non-deterministic conditions, and __topKFilter is one. Only the downstream WHERE FilterTransform wrote 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, commit 2e2f594308f4 plus 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, NULLS direction, 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 in updateQueryConditionCache.cpp and ReadFromMergeTree.cpp) moved into VirtualColumnUtils.
  • The TopK salt is plumbed to the reader via MergeTreeReaderSettings::query_condition_cache_top_k_salt.
  • The PREWHERE write path accepts a __topKFilter-bearing condition when the salt is present, folding the salt into the cache key. Any other non-deterministic condition is still never cached.
  • The PREWHERE consult path (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_topk and 04242_query_condition_cache_topk_collate pin exact cache entry counts, which double (each TopK plan now writes a WHERE entry and a PREWHERE entry per part).
  • New test 04891_query_condition_cache_topk_prewhere_granules isolates 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.
  • New performance test topk_query_condition_cache.xml with the ClickBench Q24/Q26 shapes over hits_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

  • Merged into: 26.10.1.831-master (included in 26.10 and later)

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

clickhouse-gh Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1b218cd]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_asan_ubsan, targeted) FAIL
04891_distributed_plan_limit_early_stop FAIL cidb IGNORED
Performance Comparison (amd_release, master_head, 5/6) FAIL Performance dashboard
bit_positions_to_array_big_int #1 FAIL dashboard IGNORED
Performance Comparison (amd_release, master_head, 6/6) FAIL Performance dashboard
enum #4 FAIL dashboard IGNORED

AI Review

Summary

This PR extends the query condition cache so TopK reads can record granules dropped by the dynamic __topKFilter PREWHERE, threads the cache gate through projection analysis, and hardens the ReadFromMergeTree serialization path. The remaining blocker is that the new read-side TopK reuse still ignores SAMPLE, so a sampled TopK query can reuse unsampled cache entries and skip marks that contain its own sampled top-N rows.

Findings

❌ Blockers

  • [src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp:1701] Sampled TopK reads still consult TopK query-condition-cache entries written by unsampled reads. The write side already disables QCC once sampling is active, but the consult path never mirrors that gate, and the new PREWHERE TopK entries make even ORDER BY ... LIMIT queries without a WHERE vulnerable. A warm unsampled SELECT ... ORDER BY k LIMIT 5 can therefore make SELECT ... SAMPLE ... ORDER BY k LIMIT 5 skip granules before its sample-specific threshold is recomputed. Suggested fix: thread result.sampling.use_sampling (or an equivalent effective-sampling flag) into filterPartsByQueryConditionCache and bypass TopK QCC consults when sampling is active, symmetrically to the write-side guard.
Final Verdict

Changes requested.

LLVM Coverage Report

Measured on commit 1b218cd.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.70% 91.80% +0.10%
Branches 79.50% 79.50% +0.00%

Changed lines: Changed C/C++ lines covered: 336/356 (94.38%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Aug 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

⚠️ AI verdict: not_sure — 1 query(s) improved out of 37 analysed

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 ORDER BY <column> ... LIMIT n (TopK) reads in the query condition cache, so its intended wins are on the ClickBench Q24/Q26 shapes (SELECT SearchPhrase FROM hits WHERE SearchPhrase <> '' ORDER BY EventTime LIMIT 10). None of the four flagged queries here exercise that path: Q16, Q18, and Q32 are aggregate-then-LIMIT queries with no sort-column TopK scan, and Q23 sorts by an aggregated count. The three flagged regressions (Q16 +17.2%, Q18 +18.0%, Q32 +11.8%) all land inside master's current variance band and two of the three queries are intrinsically noisy, so these read as run-to-run variance rather than PR effects; the Q23 improvement likewise reflects a very noisy baseline rather than this change. The deterministic envelope suppressions look consistent with the diff — the changed code is off these queries' execution paths.

clickbench

🟢 1 improved · ⚠️ 3 inconclusive

Flagged queries (4 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🟢 23 improvement 83 50 -39.8% <0.0001 cpu: Q23 (Title/URL LIKE + GROUP BY ... ORDER BY c LIMIT 10) does not use the TopK sort-column read this PR optimizes, so the -39.8% is not plausibly a PR effect; the baseline was very noisy (wide spread) while the PR runs were tight.
⚠️ 16 not_sure 532 624 +17.2% <0.0001 cpu: Q16 (GROUP BY UserID ORDER BY COUNT(*) DESC LIMIT 10) has no ORDER BY-on-a-column TopK read, so this QCC/TopK-cache PR does not touch its path; the +17.2% sits inside master's current variance band on a query flagged noisy.
⚠️ 18 not_sure 878 1036 +18.0% <0.0001 cpu: Q18 (GROUP BY UserID, SearchPhrase LIMIT 10) is a plain aggregate LIMIT, not a sort-column TopK read the PR changes; the +18.0% stays within master's band and the query is intrinsically noisy.
⚠️ 32 not_sure 721 806 +11.8% 0.0023 aggregation: Q32 (GROUP BY WatchID, ClientIP ORDER BY c LIMIT 10) is an aggregate-then-sort, not a sort-column TopK scan the PR touches; the +11.8% sits inside master's band with no history to anchor it.

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
  • StressHouse run: f46afeb3-e89c-4a99-be19-b12e14876426
  • MIRAI run: 3153d4bf-6580-46e7-8644-418180246837
  • PR check IDs:
    • clickbench_560066_1789641143
    • clickbench_560079_1789641143
    • clickbench_560085_1789641143
    • tpch_adapted_1_official_560091_1789641143
    • tpch_adapted_1_official_560123_1789641143
    • tpch_adapted_1_official_560137_1789641143

@clickhouse-gh

clickhouse-gh Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 1b218cd4ac4d17f0052a5da375990a896f31fbf6 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

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
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pass of 2026-09-26.

  • Merged master: the branch was 2314 commits behind. The merge was clean.
  • Fixed the Fast test red, which was caused by this PR: 05233_qcc_where_writer_row_policy_skip_index, report. Commit e1f91c76054e had disabled the residual WHERE writer and its consult under a row policy, on the premise that the policy is not in the cache key. It is: optimizePrimaryKeyConditionAndLimit ANDs the row-level filter into filter_actions_dag. Master now checks exactly that ("the restricted read ... did write an entry"). I dropped the guard on the WHERE path. The PREWHERE writer keeps its guard, because that key covers only the query PREWHERE. The row-policy cases of 04891 still pass.
  • Addressed the bot thread: isDeterministicAllowingTopKFilter now also walks folded lambda carriers. This is defense in depth; details in the thread. Added 05258_query_condition_cache_topk_folded_lambda_nondeterministic.

Local run on a fresh build: 10/10 pass (05233, 05258, 04891, 05053, both 05045, 04658, 04242, 04217, 03229).

…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)
middas-0706 pushed a commit to middas-0706/ClickHouse that referenced this pull request Sep 26, 2026
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]>
middas-0706 pushed a commit to middas-0706/ClickHouse that referenced this pull request Sep 26, 2026
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)

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.

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.

@fm4v fm4v self-assigned this Sep 27, 2026
@fm4v
fm4v added this pull request to the merge queue Sep 27, 2026
Merged via the queue into master with commit 589d85b Sep 27, 2026
168 of 172 checks passed
@fm4v
fm4v deleted the topn-threshold-pushdown branch September 27, 2026 15:56
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 27, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 29, 2026
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]>
pull Bot pushed a commit to Spencerx/ClickHouse that referenced this pull request Sep 29, 2026
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)
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 6, 2026
…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]>
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 pr-synced-to-cloud The PR is synced to the cloud repo submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Push dynamic TopN thresholds into MergeTree reads for ORDER BY ... LIMIT (2-3x on ClickBench Q24/Q26)

4 participants