Skip to content

Enable query condition cache for ORDER BY ... LIMIT n queries - #104478

Merged
alexey-milovidov merged 47 commits into
masterfrom
qcc-for-topn
Jul 1, 2026
Merged

alexey-milovidov merged 47 commits into
masterfrom
qcc-for-topn

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented May 9, 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):

Enable the query condition cache for queries that go through TopK dynamic filtering (ORDER BY ... LIMIT n). The QCC entry is partitioned by the TopK plan parameters so the same query reuses cached WHERE filter results, while a different LIMIT, sort column, or sort direction produces a fresh entry.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Why

When tryOptimizeTopK picks a ReadFromMergeTree for TopK dynamic filtering, the running threshold can drop granules before they reach the WHERE/PREWHERE filter. Until now updateQueryConditionCache blanket-skipped QCC writes for such reads:

/// ORDER BY ... LIMIT N can drop granules, don't update qcc for the WHERE filter
if (read_from_merge_tree->isSelectedForTopKFilterOptimization())
    return;

The skip was correct but pessimistic — it disables QCC for every query that hits the TopK path, even when a re-run with the same plan and same parts would reuse exactly the same row set.

What changed

  1. TopKFilterInfo::condition_hash — a deterministic hash over the planning-time TopK parameters: (column_name, type_name, num_sort_columns, limit_n, direction). Computed in tryOptimizeTopK when the read is selected for TopK filtering.
  2. ReadFromMergeTree::setTopKColumn — folds a hash of the visible part-set snapshot (the names of all parts the query reads) into condition_hash. A TopK granule-skip decision for one part depends on the __topKFilter threshold, which is derived from the rows of all parts the query reads. Since the QCC key is (table_uuid, part_name, condition_hash), an entry written for an unchanged part would otherwise stay matchable after a different part is dropped or mutated, even though the threshold that justified it is gone. Salting with the part-set snapshot makes any change to the set of parts read (DROP PARTITION, mutation, merge, new INSERT) produce a fresh key, so stale decisions are never reused; a stable part set keeps the same key and still hits.
  3. updateQueryConditionCache — instead of skipping for TopK reads, combine top_k_filter_info->condition_hash into the WHERE filter's condition_hash via boost::hash_combine before storing it on FilterStep.

The QCC writer (FilterTransform::writeIntoQueryConditionCache) and the read-side lookup both go through the same FilterStep::condition, so the combined hash is used consistently on both sides — same plan + same parts → cache hit; different LIMIT n, different sort column, or any change to the visible part set → new key, fresh entry, never reusing a row set computed under different TopK conditions.

Origin

Split out from WIP PR #81944 (commit bec285616a2). The PR's original implementation was on its own TopNFilterParameters infrastructure that didn't survive the rebase onto master; this version keeps the same idea but uses master's TopKFilterInfo / tryOptimizeTopK directly.

Version info

  • Merged into: 26.7.1.316 (included in 26.7 and later)

When `tryOptimizeTopK` selects a `ReadFromMergeTree` for TopK dynamic
filtering, the running threshold can drop granules before they reach the
WHERE/PREWHERE filter. Until now `updateQueryConditionCache` blanket-skipped
QCC writes for such reads, because a WHERE result computed under one TopK
plan would be wrong to reuse under a different one (a different LIMIT
might need granules that were dropped before).

Make the cache key for the WHERE filter depend on the TopK plan, instead
of skipping it entirely:

- Add `condition_hash` to `TopKFilterInfo`, computed deterministically
  from `(column_name, type_name, num_sort_columns, limit_n, direction)`
  in `tryOptimizeTopK`. The hash captures everything in the TopK plan
  that's known at planning time and independent of data.
- In `updateQueryConditionCache`, instead of bailing out for TopK reads,
  combine the TopK `condition_hash` into the WHERE filter's
  `condition_hash` via `boost::hash_combine`. Same query + same part set
  + same TopK plan → QCC entry is reusable; different `LIMIT n`,
  different sort column, or different direction → new key, fresh entry.

The change is symmetric: both the QCC writer
(`FilterTransform::writeIntoQueryConditionCache`) and the read-side
lookup go through the same `FilterStep::condition`, so the new combined
hash is used consistently on both sides without further wiring.

Originally part of WIP PR #81944 (commit `bec285616a2`), adapted to
master's `TopKFilterInfo`/`tryOptimizeTopK` infrastructure.
@clickhouse-gh

clickhouse-gh Bot commented May 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [bb64b83]

Summary: ✅


AI Review

Summary

This PR enables the query condition cache for TopK (ORDER BY ... LIMIT n) reads by salting the cached WHERE decision with the TopK plan and visible part-set snapshot. I rechecked the current code against the prior discussion: the read/write QCC keys now match for the WHERE paths, NULLS FIRST/LAST and COLLATE are included, non-deterministic COLUMN nodes stay rejected, and the part-set invalidation case is covered. I did not find any new correctness, safety, or performance blocker.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label May 9, 2026
`ReadFromMergeTree::setTopKColumn` takes its argument by const
reference, so wrapping the argument in `std::move` is a no-op and
trips the `performance-move-const-arg` clang-tidy check on the
arm_tidy build.

Build report:
https://s3.amazonaws.com/clickhouse-test-reports/PRs/104478/cf70625448dce5be22d92d107504f9ee3efb4baf/build_arm_tidy/build_clickhouse/build_clickhouse.log
PR: #104478
`updateQueryConditionCache` salts the WHERE filter's `condition_hash`
with `top_k_filter_info->condition_hash` before storing it on
`FilterStep::condition` (which `FilterTransform::writeIntoQueryConditionCache`
later uses as the cache key). The read path in
`MergeTreeDataSelectExecutor::filterPartsByQueryConditionCache`,
however, was looking up entries using only `dag->getHash()`, so cache
writes done under a TopK plan would never be hit on subsequent reads.

Pass `top_k_filter_info` through to `filterPartsByQueryConditionCache`
and apply the same `boost::hash_combine` on the read side. Same query
+ same part set + same TopK plan → cache hit; different `LIMIT n`,
sort column, or direction → fresh entry.

Reported by `clickhouse-gh` review on
#104478.
On Apple platforms, `std::size_t` is `unsigned long` while `UInt64` is
`unsigned long long` — different types of the same width — so the
non-const reference parameter of `boost::hash_combine` does not bind to
a `UInt64` lvalue and the build fails with:

    error: no matching function for call to 'hash_combine'
    note: candidate function template not viable: no known conversion
          from 'UInt64' (aka 'unsigned long long') to 'std::size_t &'
          (aka 'unsigned long &') for 1st argument

On x86_64 Linux both aliases happen to resolve to `unsigned long`, which
is why CI Linux builds passed but `Build (amd_darwin)` and
`Build (arm_darwin)` failed.

Switch the local seed variable on both the read path
(`MergeTreeDataSelectExecutor::filterPartsByQueryConditionCache`) and
the write path (`updateQueryConditionCache`) to `size_t`. The implicit
conversions to/from `UInt64` at the cache-API boundary are lossless on
all 64-bit platforms ClickHouse supports.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=104478&sha=4ab18afb9c043a670ca72211ab85494fd956e3b8&name_0=PR&name_1=Build%20%28amd_darwin%29
PR: #104478
alexey-milovidov and others added 2 commits May 10, 2026 17:43
…ition_hash

`updateQueryConditionCache` and `MergeTreeDataSelectExecutor::filterPartsByQueryConditionCache`
already combine `top_k_filter_info->condition_hash` into the QCC key. There is a third site
that writes to the cache: the distributed-index-analysis branch in
`ReadFromMergeTree::selectRangesToRead`, which fills QCC with ranges excluded by index
analysis. Without the same salt the writes there go under `outputs.front()->getHash()`
while reads go under the salted hash, so TopK queries cannot reuse those entries.

Apply `boost::hash_combine(hash, top_k_filter_info->condition_hash)` consistently with
the other two sites.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

@alexey-milovidov alexey-milovidov left a comment

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.

Add functional tests for this optimization.
Add performance tests as well.

@alexey-milovidov
alexey-milovidov marked this pull request as draft May 10, 2026 23:06
@shankar-iyer shankar-iyer self-assigned this May 11, 2026
/// fold the deterministic part of the TopK plan into the cache key. Same query + same
/// part set + same TopK params → cache hit; different LIMIT or sort column → fresh
/// entry, never reusing a row-set computed under different TopK conditions.
if (const auto & top_k_filter_info = read_from_merge_tree->getTopKFilterInfo())

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I will study this in detail - this is where I got stuck in my branch.

alexey-milovidov and others added 2 commits May 11, 2026 15:49
`tryOptimizeTopK` was hard-disabling `reader_settings.use_query_condition_cache`
inside `ReadFromMergeTree::setTopKColumn`, so chunks never carried `MarkRangesInfo`
and `FilterTransform::writeIntoQueryConditionCache` had nothing to flush. With
that flag off, the WHERE-filter QCC entries we now key by `TopKFilterInfo::condition_hash`
were never written, so the read paths in `MergeTreeDataSelectExecutor::filterPartsByQueryConditionCache`
and the index-analysis branch of `selectRangesToRead` always missed.

Drop the unconditional disable in `setTopKColumn`. With the filter pushdown now
pulling `__topKFilter` into `query_info.filter_actions_dag`, the determinism check
in both write paths (`updateQueryConditionCache` and `selectRangesToRead`) would
also bail out, so add `isDeterministicAllowingTopKFilter` (and the matching
exception in `isNodeDeterministic`) to treat `__topKFilter` as deterministic for
QCC purposes: its non-determinism is bounded by the TopK plan parameters that
are already folded into the cache key, and the threshold trajectory only tightens
during execution, so a granule that the outer WHERE zeroes out under
`__topKFilter` is one whose rows could not have reached the final result under
any threshold trajectory.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
A stateless test (`04217_query_condition_cache_topk`) verifies the QCC populates
and partitions entries by the TopK plan parameters: re-running the same
`WHERE ... ORDER BY <col> LIMIT n` reuses the same cache entry, while changing
`LIMIT`, the sort direction, or the sort column writes a fresh entry instead.

A performance test (`query_condition_cache_topk`) compares
`use_query_condition_cache = 1` vs `0` for an `ORDER BY ... LIMIT n` query under
`use_top_k_dynamic_filtering = 1` so the speedup the QCC delivers on
subsequent runs of the same TopK plan is visible in CI perf comparisons.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

There is no visible difference on the newly introduced performance test.

The previous version used `WHERE URL LIKE '%google%' ORDER BY EventTime
LIMIT 10` against `hits_100m_single`, which matches at least one row in
nearly every granule of `hits`, so the QCC had no granules to skip and
the comparison reported essentially the same time with and without the
cache (87.9 ms vs 87.3 ms before, 84.5 ms vs 84.0 ms after — all within
noise).

Switch to a self-contained synthetic table so the granule-level
selectivity of the WHERE filter is controlled:

* 50M rows in a `MergeTree` with `index_granularity = 8192`
  (~6 100 granules per part).
* `v2` is `rand()` per row, so per-part minmax statistics span the full
  `UInt32` range and cannot prune parts on `v2 = constant`.
* Exactly one row is injected with `v2 = 12345`, so the matching row
  sits in a single granule; the other ~6 100 granules have zero matches
  and become skippable in the QCC after the prewarm run.

`optimize_move_to_prewhere` is also explicitly disabled so the WHERE
predicate stays as a separate `FilterStep` above `ReadFromMergeTree`
and the dynamic-filtering branch of `tryOptimizeTopK` applies (it bails
out when `getPrewhereInfo()` is already set), matching the path the
QCC writer in `updateQueryConditionCache` follows.

Local measurement on the new layout (median over 7 runs, after
prewarm):
  * `use_query_condition_cache = 1`:  ~2 ms
  * `use_query_condition_cache = 0`:  ~8 ms

so the speedup attributable to this PR is visible (~4×) in the CI
performance comparison instead of being hidden inside the existing TopK
dynamic-filtering speedup.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Still no significant difference - correct the test so that it will be visible.

…eedup

The previous version used `v1 = number` and `LIMIT 10`, which makes the
TopK threshold settle to the 10th-smallest `v1` value across the whole
table. With a random PK (`id = rand()`) those 10 winning rows are
scattered across ~10 random granules, so `__topKFilter` rejects every
row in the remaining ~6 100 granules and FilterTransform never sees them.
Without FilterTransform input there is no QCC write for those granules,
so the cache only ends up covering a handful of granules per part and
the second-run speedup is small (within the ~5% perf-comparison noise
threshold on CI, e.g. 20.7 ms vs 20.7 ms).

Switch the synthetic schema so QCC has full per-granule coverage:

  * `v1 = number % 1000` instead of `v1 = number`. Each granule of
    8 192 rows now contains ~8 rows with `v1 = 0`. The TopK threshold
    still settles to `0` almost immediately, but `__topKFilter` keeps
    those ~8 rows per granule and they reach the WHERE filter — letting
    QCC record a "no match" entry for every granule on the prewarm run.
  * The single matching row (with `v2 = 12345`) is now also forced to
    `v1 = 0`, so it survives `__topKFilter` and the query still returns
    the planted row (otherwise it would be filtered out by PREWHERE and
    the result would be empty).
  * Doubled to 100M rows / ~12 200 granules so the cold-cache scan time
    is large enough that the speedup is unambiguous.

Local measurement on the new layout (median over 5 runs, after prewarm,
`max_threads=12` to match the perf-comparison default):

  * `use_query_condition_cache = 1`:   ~2 ms
  * `use_query_condition_cache = 0`:  ~45 ms

so the speedup attributable to this PR is ~22× and far above the CI
stat threshold instead of being lost inside the existing TopK
dynamic-filtering speedup.
The salt that partitions QCC entries by TopK plan parameters previously
omitted two ORDER BY clauses with semantic impact: `NULLS FIRST` /
`NULLS LAST` and `COLLATE`. Two queries that differ only by those parts
of the sort description currently collide in the cache, so granule
decisions made under one ordering rule could be reused under another —
which is unsound for Nullable columns or string sorts with different
locales.

Fold `sort_col_desc.nulls_direction` and (when present)
`sort_col_desc.collator->getLocale()` into the `SipHash` seed alongside
the other planning-time parameters so each combination gets its own
entry.

The skip-index path of `tryOptimizeTopK` already rejects Nullable
columns and collated sorts on its `skip_index_type_eligible` guard, but
the dynamic-filtering path does not, so the QCC salt has to carry these
parameters too.

Defensive: no test failures observed; the existing
`04217_query_condition_cache_topk` continues to pass.
The PREWHERE write path in `MergeTreeSelectProcessor::read` uses an unsalted
`output->getHash()`, so salting only the PREWHERE read side made the keys
diverge — for TopK plans with a deterministic PREWHERE (for example, skip-index
TopK plans) the lookup never hit the entry the writer had just stored. Restrict
the TopK salt to the WHERE lookup path, which already pairs with a salted write
in `updateQueryConditionCache` and the secondary write path in
`selectRangesToRead`.
With 100M rows the per-run absolute QCC speedup (~10 ms of WHERE-filter
scan) is below the comparison harness's noise threshold once
~50 ms of unrelated per-query overhead is folded in, so the test
showed no measurable delta between `use_query_condition_cache = 1`
and `= 0`. Scale the fill to 500M rows (~5 GiB on disk) so the
data-scan cost dominates query overhead and the cached-granule
pruning produces a clear, stable improvement in the report.
The previous shape relied on `__topKFilter` keeping ~8 rows per granule for
the WHERE filter to evaluate, but in the comparison harness the actual
granule-skipping savings on subsequent runs were not visible above the
noise floor — both the `use_query_condition_cache = 1` and `= 0` queries
landed at ~280 ms on `amd_release`.

Reshape the benchmark to a `WHERE` that matches no rows in the table
(`payload = 'no_match'` against a `FixedString(8)` filled with random
`%1000` values). With every granule yielding `0/N` after the WHERE filter,
the prewarm run writes a "skip me" entry for every granule of every part,
and every measured run with the QCC enabled returns without reading any
data — which is the speedup the QCC-enabled query is supposed to measure.

The QCC-disabled query keeps paying the full WHERE-filter cost on every
run, giving a clear delta between the two queries in the perf comparison.

@alexey-milovidov alexey-milovidov left a comment

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.

Plausible.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jun 30, 2026
Merged via the queue into master with commit cb507a9 Jul 1, 2026
341 of 344 checks passed
@alexey-milovidov
alexey-milovidov deleted the qcc-for-topn branch July 1, 2026 00:27
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 1, 2026

SELECT '--- After DROP PARTITION: ground truth (QCC off) comes from partition 1';
SELECT k FROM tab WHERE w = 7 ORDER BY k DESC LIMIT 5 SETTINGS use_query_condition_cache = 0;
SELECT '--- QCC on must not reuse granule decisions recorded under the old part set';

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@groeneai could you check the query condition cache is being used by checking the ProfileEvents check on system.query_log?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@groeneai could you also check for negative limits and order by desc?

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.

Done in #110381 (test-only follow-up on 04338):

  • QCC usage now checked via system.query_log ProfileEvents: warm run has QueryConditionCacheHits = 0, cached run has hits, and the run after DROP PARTITION has 0 hits (the part-set salt invalidation, not just a correct result).
  • Negative LIMIT: LIMIT -n becomes a NegativeLimit plan step with no __topKFilter, so the TopK-QCC path never engages. Added a case asserting it returns the correct rows and neither reuses nor poisons the TopK entries.
  • ORDER BY DESC was already covered; also added an ASC case, which must not reuse the DESC entry since condition_hash folds the sort direction (verified via 0 hits).

Verified 20/20 with full randomization.

alexey-milovidov added a commit that referenced this pull request Jul 22, 2026
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 added a commit that referenced this pull request Jul 24, 2026
…condition-cache behavior

The 26.7 stable release (v26.7.1.1315-stable) shipped #104478/#110507 with
TopK (`ORDER BY ... LIMIT n`) reads participating in the query condition
cache unconditionally, so the `SettingsChangesHistory` entry for
`use_query_condition_cache_for_top_k` must record `previous_value = true`:
`SET compatibility = '26.7'` on 26.8+ then re-enables the gate instead of
silently disabling the behavior for pinned compatibility profiles.

Adds `04631_query_condition_cache_topk_compatibility` asserting the default
is off and that `compatibility = '26.7'` flips it on while
`compatibility = '26.8'` keeps it off.

Co-Authored-By: Claude Fable 5 <[email protected]>
YenchangChan pushed a commit to YenchangChan/ClickHouse that referenced this pull request Aug 1, 2026
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 ClickHouse#104478 and extended in
PR ClickHouse#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-ClickHouse#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 ClickHouse#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: ClickHouse#104478
Related: ClickHouse#110507

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
alexey-milovidov added a commit that referenced this pull request Aug 12, 2026
A worker could prepare a merge but never push it: the `/continue-pr` run started
a build in the background and ended its turn waiting for a completion
notification that never arrives in single-shot `claude --print` mode, so the
push step was never reached and the merge stayed local-only (e.g. #104478).

Two changes:

* Append a system prompt to every turn that forbids backgrounding work and tells
  the worker to run builds/tests synchronously and push before ending its turn.
* Run each PR in a bounded resume loop (`run_continue_pr`): the first turn runs
  `/continue-pr` with an explicit `--session-id`, then the same session is
  resumed (`--resume`) until the worker prints a completion marker, the per-PR
  time budget is exhausted, or `--max-continue` (default 4) turns are reached.

`--timeout` is now the total per-PR budget shared across continuation turns. The
finish summary is taken from the final turn.

Co-Authored-By: Claude Opus 4.8 (1M context) <[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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
`ReadFromMergeTree::setTopKColumn` takes its argument by const
reference, so wrapping the argument in `std::move` is a no-op and
trips the `performance-move-const-arg` clang-tidy check on the
arm_tidy build.

Build report:
https://s3.amazonaws.com/clickhouse-test-reports/PRs/104478/cf70625448dce5be22d92d107504f9ee3efb4baf/build_arm_tidy/build_clickhouse/build_clickhouse.log
PR: ClickHouse#104478
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
`updateQueryConditionCache` salts the WHERE filter's `condition_hash`
with `top_k_filter_info->condition_hash` before storing it on
`FilterStep::condition` (which `FilterTransform::writeIntoQueryConditionCache`
later uses as the cache key). The read path in
`MergeTreeDataSelectExecutor::filterPartsByQueryConditionCache`,
however, was looking up entries using only `dag->getHash()`, so cache
writes done under a TopK plan would never be hit on subsequent reads.

Pass `top_k_filter_info` through to `filterPartsByQueryConditionCache`
and apply the same `boost::hash_combine` on the read side. Same query
+ same part set + same TopK plan → cache hit; different `LIMIT n`,
sort column, or direction → fresh entry.

Reported by `clickhouse-gh` review on
ClickHouse#104478.
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
On Apple platforms, `std::size_t` is `unsigned long` while `UInt64` is
`unsigned long long` — different types of the same width — so the
non-const reference parameter of `boost::hash_combine` does not bind to
a `UInt64` lvalue and the build fails with:

    error: no matching function for call to 'hash_combine'
    note: candidate function template not viable: no known conversion
          from 'UInt64' (aka 'unsigned long long') to 'std::size_t &'
          (aka 'unsigned long &') for 1st argument

On x86_64 Linux both aliases happen to resolve to `unsigned long`, which
is why CI Linux builds passed but `Build (amd_darwin)` and
`Build (arm_darwin)` failed.

Switch the local seed variable on both the read path
(`MergeTreeDataSelectExecutor::filterPartsByQueryConditionCache`) and
the write path (`updateQueryConditionCache`) to `size_t`. The implicit
conversions to/from `UInt64` at the cache-API boundary are lossless on
all 64-bit platforms ClickHouse supports.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=104478&sha=4ab18afb9c043a670ca72211ab85494fd956e3b8&name_0=PR&name_1=Build%20%28amd_darwin%29
PR: ClickHouse#104478
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The test built its single part by running a randomized parallel `INSERT`
(`max_insert_threads` is randomized in CI, leaving several parts) and then
collapsing them with `OPTIMIZE TABLE tab FINAL`. With `index_granularity = 64`
a 1M-row part has roughly 15k marks, and merging it under the debug and
sanitizer flaky checks timed out: the run hit the 300-second client timeout on
the `OPTIMIZE` query and the whole test exceeded the 180-second soft limit
(reported as `Test runs too long`).

Produce a single part directly from the insert instead, by pinning
`max_insert_threads = 1` and squashing the whole input into one block
(`max_insert_block_size`, `min_insert_block_size_rows`), and drop the
`OPTIMIZE ... FINAL` merge entirely. The single-thread, single-part read keeps
the `__topKFilter` threshold trajectory and the QCC population deterministic,
so the reference output is unchanged (verified locally), and the test no longer
pays for the expensive merge.

Also renumber the test from `04309` to `04320` to avoid a prefix collision
with `04309_explain_insert_format`, which landed on master in the meantime.

Failures: ClickHouse#104478

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Enable query condition cache for `ORDER BY ... LIMIT n` queries
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants