Skip to content

Query condition cache for TopK reads of Parquet files - #122064

Merged
alexey-milovidov merged 15 commits into
masterfrom
parquet-top-k-query-condition-cache
Oct 8, 2026
Merged

alexey-milovidov merged 15 commits into
masterfrom
parquet-top-k-query-condition-cache

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 24, 2026 •

Copy link
Copy Markdown
Member

Implements the query condition cache for TopN (ORDER BY <column> LIMIT n) reads of Parquet files through the File engine. So far such reads could only consult entries written by plain reads with the same predicate, and never wrote any themselves, because which row groups the TopN filter lets through depends on the running threshold.

A TopN read now records the row groups which hold no row of its result, and a rerun of the same query skips them - also without any WHERE, e.g. SELECT * FROM hits ORDER BY EventTime LIMIT 10.

  • What is recorded. The Parquet reader remembers, for each row group, the best value of the sort column among the rows it returned (only when requested via FormatTopKFilterInfo::track_row_group_best_values). A row group that returned no row, or whose best value sorts strictly beyond the threshold, holds no row of the result: the threshold only ever tightens towards the final one, and __topKFilter keeps rows equal to it. Relying only on "no row returned" is not enough - with parallel reading, the reader returns most row groups before the first threshold is published.
  • When it is recorded. StorageFileSource writes the entries when it is destroyed, not when it finishes a file: at that point the rows of the file may still be waiting for the sorting transforms. For the threshold to be exact by then, the final MergingSortedTransform now publishes the value in the last row within the limit. Before, only the per-stream sorting transforms published their own, much looser, thresholds. A cancelled read writes nothing (for the plain entries too), as the row groups it did not reach report no matching rows either.
  • Under which key. The threshold comes from the rows of every file the query reads, so a separate key covers the TopK plan (sort column and type, LIMIT, direction, NULLS, collation - the same hash the MergeTree path uses, now shared), the predicate if any, and the version tokens of all files of the table. The key is made only when every token has settled and the query has no row policy, and a file whose token changed after the key was made does not use it. The plain predicate key keeps getting only threshold-oblivious entries. A TopN read consults both keys; a row group is skipped if either verdict excludes it. use_query_condition_cache_for_top_k = 0 keeps TopN reads out of the cache entirely, as before.

On a 20M-row file with 153 row groups (random order of the sort key), with default settings:

query without the cache rerun with the cache
SELECT * FROM t ORDER BY k LIMIT 10 55 ms, 115 MiB 17 ms, 7.6 MiB (10 row groups)
SELECT * FROM t WHERE n % 7 = 1 ORDER BY k DESC LIMIT 10 35 ms, 130 MiB 14 ms, 11 MiB

The test covers both shapes, a different LIMIT / direction / plain read not reusing the entries, the setting, and a rewrite of one file of a glob: the stale entries of the unchanged file must not be reused, since the result now lies in the row group they recorded as holding none. Without the file versions in the key the test returns 9, 9, 9 instead of 100999, 100998, 100997 (checked by building with them removed).

Closes: #121876
Related: #115798

Changelog category (leave one):

  • Performance Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

The query condition cache now also works for ORDER BY ... LIMIT n queries over Parquet files of File tables, with or without a WHERE clause: a repeated query reads only the row groups which can hold rows of its result.

🤖 Generated with Claude Code


Workflow [PR]
Sync PR [sync-upstream/pr/122064]

Version info

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

alexey-milovidov and others added 2 commits September 24, 2026 16:17
A TopN (`ORDER BY ... LIMIT n`) read of Parquet files through the `File`
engine now writes query condition cache entries for the row groups that held
no row of the result, and a rerun of the same query skips them. The entries
depend on the running TopK threshold, which comes from the rows of every file
the query reads, so they are stored under a key that covers the TopK plan,
the predicate (a read without one is cached too), and the version tokens of
all the files; the key is made only when every token has settled. The plain
predicate key keeps getting only threshold-oblivious entries.

A cancelled read no longer writes entries, as the row groups it did not read
report no matching rows either.

Closes: #121876
Related: #115798

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…mpty ones

With parallel reading, the Parquet reader returns most row groups before the
first threshold is published, so hardly any row group ends up without a
returned row, and the TopK entries recorded almost nothing. Now the reader
remembers the best returned value of the sort column in each row group, and
`StorageFileSource` writes the entries only when it is destroyed, dropping the
row groups whose best value sorts strictly beyond the threshold at that time.
The threshold only ever tightens, so this is sound at any point, and the final
`MergingSortedTransform` now publishes the exact final threshold, which the
per-stream sorting transforms never did.

On a 20M-row file with 153 row groups, a rerun of
`SELECT * ... ORDER BY k LIMIT 10` now reads 10 row groups (7.6 MiB instead
of 115 MiB, 17 ms instead of 55 ms).

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@alexey-milovidov alexey-milovidov added the pr-performance Pull request with some performance improvements label Sep 24, 2026
@mintlify

mintlify Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

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

Project Status Preview Updated
ClickHouse-docs 🟢 Ready View Preview Oct 8, 2026, 6:25 AM

@clickhouse-gh

clickhouse-gh Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5b5a17d]

Summary: ✅


AI Review

Summary

This PR extends the query condition cache to ORDER BY ... LIMIT n reads of Parquet File tables and teaches the sorting pipeline to publish the exact TopK threshold so repeated reads can skip row groups. The main design looks reasonable, but the last simplification around the shared TopK cache key reopened a stale-result window: a settled file can still read and write a key whose threshold also depends on another contributing file whose version token has not settled yet.

Findings
  • ❌ [src/Storages/StorageFile.cpp:2132, src/Storages/StorageFile.cpp:2430, src/Storages/StorageFile.cpp:2806] The shared TopKQueryConditionCacheKey is built from every contributing file token, but the settle-window guard is applied only to the current file when consulting or writing entries. A settled b.parquet can therefore reuse or populate a {A0,B0} TopK entry while a.parquet is freshly written and still inside the same mtime tick. If a.parquet is rewritten again with the same inode and size before its token becomes rewrite-proof, that stale b.parquet entry can suppress rows that now belong to the result because the global threshold is coming from different rows. Suggested fix: refuse to build or use the shared TopK key unless every file in the snapshot has a settled generation token (or switch the key to a generation source that is stable immediately for all contributing files).
Final Verdict
  • Status: ❌ Block
  • Reintroduce a query-wide settle guard for the shared TopK key. The current per-file gate is enough for the plain file-local cache, but not for a key whose threshold depends on all files in the query.

LLVM Coverage Report

Measured on commit 5b5a17d.

Metric Baseline Current Δ
Lines 88.30% 88.30% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 332/348 (95.40%) · Uncovered code

Full report · Diff report

Comment thread src/Storages/StorageFile.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-formats Input/output formats (CSV/JSON/Parquet/ORC/Arrow/Protobuf/etc.). label Sep 24, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 5b5a17d10885e00200c5486d446a9bcc83b10f7b was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception; stopped retrying after the 1250 s read budget).

See the job log for details.

@clickhouse-gh

clickhouse-gh Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 32 queries analysed

This PR adds query condition cache entries for TopK (ORDER BY col LIMIT n) reads of Parquet files through the File engine. It also publishes the exact TopK threshold from the sort and merge transforms, but only when a threshold tracker exists. None of the four flagged improvements run that code. ClickBench Q33/Q34 order by an aggregate after GROUP BY, and TPC-H Q1/Q7 have no LIMIT. All four are downgraded to not sure. The ClickBench pair does show consistent CPU drops of about 12%, which more likely comes from a build or base difference than from this diff. The TPC-H deltas come from base medians at or above master's recent range.

clickbench

⚠️ 2 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 33 not_sure 1153 1035 -10.2% <0.0001 aggregation: This query is a large GROUP BY ordered by an aggregate with LIMIT, so there is no TopK filter on a source column and none of the new code runs. The -10.2% change and lower CPU most likely come from a build or base difference, not this diff.
⚠️ 34 not_sure 1164 1038 -10.8% <0.0001 aggregation: This is the twin of Q33: the same GROUP BY with ORDER BY on an aggregate, so no TopK threshold tracker is created on the read path. The -10.8% change and CPU drop are not explained by this diff.

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

⚠️ 2 inconclusive

Flagged queries (2 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 1 not_sure 65 53 -18.5% <0.0001 aggregation: TPC-H Q1 aggregates MergeTree data and sorts without a LIMIT, so the TopK and File-engine cache code never runs. The PR median of 53 ms is inside master's recent 50-64 ms band, and this query has a noisy history.
⚠️ 7 not_sure 81 60 -25.9% <0.0001 join_operator: TPC-H Q7 is a multi-join with ORDER BY and no LIMIT, so no TopK threshold is published. The -25.9% change comes from a base median of 81 ms sitting above master's recent 60-78 ms band.

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.

Debug info
  • StressHouse run: f685296e-5b9a-4376-8977-8f632a82553f
  • MIRAI run: 72df13e5-a269-4ca5-b56a-f5a20ad489bb
  • PR check IDs:
    • clickbench_357192_1791465142
    • clickbench_357205_1791465142
    • clickbench_357211_1791465142
    • tpch_adapted_1_official_357217_1791465142
    • tpch_adapted_1_official_357248_1791465142
    • tpch_adapted_1_official_357262_1791465142

alexey-milovidov and others added 2 commits September 25, 2026 02:50
The TopK query condition cache key covers the versions of all files, but
each file only checked its own token. With several streams, one file could
already skip row groups by an entry while another file of the glob was
rewritten before being opened, and the threshold then came from rows the
entry never described. Now the first file read in another version (at
open, or rewritten while read) invalidates the key for the whole query:
nothing is consulted or written under it afterwards. If an entry has
already been used by then, the query fails with `FILE_CHANGED_DURING_READ`
rather than return what the stale entry left of the result; the pair of
sequentially consistent flags makes sure one of the two sides notices.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Comment thread src/Storages/StorageFile.cpp Resolved
The `engine_file_empty_if_not_exists` and `engine_file_skip_empty_files`
paths skipped a file without the check that invalidates the TopK query
condition cache key, although a file that disappeared or was emptied after
the key was made changes the threshold just as a rewrite does.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Comment thread src/Storages/StorageFile.cpp Resolved
…e stream

The TopK key covered every path of the table, although a `_path` / `_file`
filter can leave the query only some of them: a change of a file it never
reads (or one not settled yet) cost it the cache. The key now covers the
files the iterator returns when they are known up front.

With a single stream there is no final `MergingSortedTransform`, and the
exact threshold was only published if `remerge` happened to run.
`MergeSortingTransform` now publishes the value at the limit when it
generates the sorted result: exact with one stream, never tighter than the
final one with several.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
With external sorting the sorted result of a stream comes out of
`external_merging_sorted` rather than `generate`, so give that merge the
tracker as well.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Comment thread src/Storages/StorageFile.cpp Resolved
With the `invalidated` and `consulted` flags, a lookup that raced with an
invalidation set `consulted` and then dropped its entry, and the next
failed check of a file then threw `FILE_CHANGED_DURING_READ` although no
entry had been used. One atomic state (`Valid`, `Used`, `Invalidated`) makes
the two sides linearizable: a lookup uses its entry only if it moves the
state to `Used` (or finds it there), and an invalidation fails the query
only if it replaces `Used`.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Comment thread src/Storages/StorageFile.cpp Resolved
A TopK entry that excludes no row group beyond the verdict of the predicate
alone changed nothing, yet it moved the key to `Used`, and a later change
of a file then failed the query with `FILE_CHANGED_DURING_READ`. Such an
entry is now not used at all, so a later change only invalidates the key.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
A file whose last row groups reach the sorting one row at a time, so that
only `MergeSortingTransform::generate` publishes the exact threshold with
`max_threads = 1`. Without that publication the entry is not written.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…-condition-cache

Resolved conflicts in `StorageFile`: keep the TopK cache write before the
now exception-guarded `beforeDestroy`, and read the paths for the TopK cache
key from `paths_snapshot`, since `StorageFile::paths` is now guarded by
`paths_mutex` on master.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=122064&sha=416cf15dc5cc433b307b145617f6c6ed1bd25fa6&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29 (Logical error: 'Equal values are not contiguous within the range assumed to be sorted', STID: 2508-348f; query: SELECT DISTINCT a, b FROM (... ORDER BY a WITH FILL STEP 2 STALENESS 65537, b DESC COLLATE 'en-u-ks-level2')) and provide a fix in a separate PR. If the fix is already in progress, link it here. It is unrelated to this PR (no Parquet, no LIMIT/TopK); possibly related to #118077.

@alexey-milovidov alexey-milovidov self-assigned this Oct 7, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 7, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to a conflict with the base branch Oct 7, 2026
alexey-milovidov and others added 3 commits October 8, 2026 05:26
# Conflicts:
#	src/Processors/Formats/AggregateFunctionStatesFromValuesInputFormat.h
#	src/Processors/Formats/IInputFormat.h
#	src/Processors/Formats/Impl/ParquetV3BlockInputFormat.cpp
#	src/Processors/Formats/Impl/ParquetV3BlockInputFormat.h
…ThresholdTracker`

Master turned `TopKThresholdTracker` into the `ITopKThresholdTracker` interface.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Let an exception from `writePendingTopKQueryConditionCacheEntries` propagate
to the existing handler in `~StorageFileSource` instead of catching it in the
function. It runs after `beforeDestroy`, so a failure does not skip the
rename of the processed files.

Drop the settle-window requirement from the TopK key: the version tokens have
sub-second precision, a file whose token has not settled neither reads nor
writes entries anyway, and a file rewritten while it is read is caught by the
re-stat at the end of its read. This removes `isFileCacheVersionTokenSettled`.

Address review: #122064 (comment)
Address review: #122064 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickgapai

Copy link
Copy Markdown
Contributor

@alexey-milovidov — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

alexey-milovidov added a commit to groeneai/ClickHouse that referenced this pull request Oct 22, 2026
A TopN (`ORDER BY ... LIMIT n`) read of a data lake table (`Iceberg`, `DeltaLake`, `Paimon`) with
Parquet data files now records in the query condition cache the row groups which hold no row of the
result, and a rerun of the same query skips them, also without a `WHERE`. The entries are keyed by
the TopK plan, the predicate, and the snapshot of the table: the snapshot identifies the set of data
files (and deletes), which are never modified in place, and the threshold of the TopN filter comes
from the rows of all of them.

The same was done for the `File` engine in ClickHouse#122064.

Related: ClickHouse#124785

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov added a commit to groeneai/ClickHouse that referenced this pull request Oct 24, 2026
The query condition cache skipped every table without a UUID, which is
the table behind a table function (`file`, `s3`, `icebergS3`, ...). For
file-backed data the table is not needed: the entries are keyed by the
location of the file together with its version (the local version token
or the ETag), or by the location alone for immutable data lake files.
Such tables now keep their entries under a fixed table id
(`QueryConditionCache::getTableIdForFileEntries`), and object storage
qualifies the path with the storage it is in (endpoint, bucket), which
the table UUID used to provide.

Related: ClickHouse#122064

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

This branch was successfully deployed

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

Labels

comp-formats Input/output formats (CSV/JSON/Parquet/ORC/Arrow/Protobuf/etc.). 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.

Now we should implement Query Condition Cache for TopK in Parquet.

4 participants