Skip to content

Read Parquet files with the best top-K statistics first - #124959

Open
groeneai wants to merge 20 commits into
ClickHouse:masterfrom
groeneai:groeneai/parquet-top-k-file-order
Open

groeneai wants to merge 20 commits into
ClickHouse:masterfrom
groeneai:groeneai/parquet-top-k-file-order

Conversation

@groeneai

@groeneai groeneai commented Oct 9, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #124672
Related: #123639

Changelog category (leave one):

  • Performance Improvement

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

ORDER BY ... LIMIT over a glob of local Parquet files read with max_threads up to 4 now opens first the files whose statistics hold the best values of the sort key, so the top-K threshold tightens sooner and more row groups of the other files are skipped.

Description

ReadFromFile hands the files of a glob to its streams in directory order, so for ORDER BY x LIMIT n the first files decoded are arbitrary and the TopN dynamic filter tightens late. Now, before any stream starts, the footers are read (one task per stream, through ParquetMetadataCache, so each footer is read once), each file gets the best row-group bound of the sort key its statistics allow after WHERE pruning, and the files are handed out best bound first.

Limits. The pass runs only when the read has more files than streams and at most 4 streams. With one file per stream the order changes nothing; at 8 streams the footer reads cost +6.3% CPU if the order gains nothing. It is also skipped for compressed files, archives, distributed reads, input_format_allow_seeks = 0, input_format_parquet_preserve_order = 1 and use_parquet_metadata_cache = 0, and skips files that the query condition cache or the statistics cached with their footers (#125528) exclude. Object storage is unchanged. A file whose footer cannot be read (corrupt or mid-rewrite) is left to its reader, as on master. On a File table the pass runs under the table's read lock, so a concurrent INSERT waits instead of failing the read with FILE_CHANGED_DURING_READ.

Measured (100 ClickBench files, release, fresh clickhouse local, max_threads = 4, 60 pairs, process CPU, 95% CI):

  • ORDER BY WatchID LIMIT 10: -17.1% [-19.2, -15.0]; DESC: -14.9%
  • Q24 / Q25 with INT64 -> DateTime statistics (Use statistics of a plain Parquet INT64 column read as DateTime #124863): -26.5% / -11.6%
  • all bounds equal: +0.4% [-1.4, +2.3]; listing already in the best order: -0.8%; no TopN: -0.7%
  • peak memory +31 MiB; with more than 4 streams (8, and the default 100 here): no change

New test 05341_parquet_top_k_file_order (fails on master), concurrent INSERT cases in 05238_file_engine_concurrent_insert_select, cache reuse cases in 05243_query_condition_cache_top_k_parquet and perf test parquet_top_k_file_order.xml.

Found and first patch by @ snelheidai in #124672.

🤖 Generated with Claude Code


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

groeneai and others added 2 commits October 9, 2026 16:29
For `ORDER BY <column> LIMIT n` over a glob of local Parquet files, the
TopN dynamic filter can only skip a row group that starts after the
threshold is set, and the threshold comes from the rows of the first files
the streams open. `ReadFromFile` handed the files out in directory order,
which says nothing about the sort key.

Now, when the filter is armed for plain local Parquet files,
`ReadFromFile::orderFilesByTopKBound` reads the footers first, takes for
each file the smallest row-group minimum (largest maximum for DESC) of the
sort column over the row groups left after the query's filter, and hands
the files out best bound first. Files without a usable bound keep their
relative order after the others. The pass runs only when the read has more
files than streams and at most 4 streams, with one footer task per stream
on the IO pool: with at most one file per stream every file is opened in
the first round whatever the order.

The footers are loaded through `ParquetMetadataCache::getOrSetMetadataCell`
under the key and with the loader the reader of the file uses, so every
footer is still read once. The probe runs only the row-group pruning half
of `Parquet::Reader::prefilterAndInitRowGroups` (split into
`prefilterRowGroups` and `initRowGroups`), so it does not prepare bloom
filters, page filters or prefetches. It uses the header `FormatFactory`
builds the reader with, so the call-once key condition is identical.

The pass reads the footers under the table's read lock, like the sources.
A writer that rewrites a file after the pass releases the lock changes its
version token, so that file's reader misses the cache and reads the new
footer: only the order can be stale, never the result.

The pass is skipped for compressed files, `input_format_allow_seeks = 0`,
`input_format_parquet_preserve_order = 1`, `use_parquet_metadata_cache = 0`,
archives, distributed processing and a deferred `_path`/`_file` filter, and
when there are more files than a quarter of the cache entries (at most
1000). It stops when the footers read so far plus one more of the largest
size per task would exceed a quarter of the cache bytes, when no file of
the first round has a bound, or when the query is killed. A missing, empty
or non-regular file is not opened and is left to its reader; any other
error fails the query with the file name, as the reader would.

Above 4 streams the read is unchanged. Measured with 100 ClickBench files
(release, fresh `clickhouse local`, 60 pairs, process CPU): when every file
has the same bound (`ORDER BY AdvEngineID LIMIT 10`) the pass costs +0.4%
CPU with 4 streams but +6.3% [+3.3%, +9.3%] with 8, while
`ORDER BY WatchID LIMIT 10` gains -17.1% with 4 and -11.5% with 8. The pass
itself (`EXPLAIN PIPELINE`) takes about 20 ms with 4 tasks.

Found and first patch by snelheidai in ClickHouse#124672.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Replace the measurement behind max_streams_to_order with a one-line statement of why the limit exists.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-issue PR origin: picked up an external GitHub issue labels Oct 9, 2026
@groeneai

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (rounds 1-4): 4 fixed, 3 noted
  • ❌ The footer pass read the files before the sources took the table's read lock, so on an ENGINE = File(Parquet) table it could read a file a concurrent truncating INSERT was rewriting and fail with INCORRECT_DATA. AGREE: the pass now holds the read lock while it reads; covered by a race arm and a slow-INSERT arm in 05238_file_engine_concurrent_insert_select.
  • ⚠️ Those two arms did not pin the top-K settings the runner randomizes, so most randomized runs skipped the pass. AGREE: both queries pin use_top_k_dynamic_filtering = 1 and query_plan_max_limit_for_top_k_optimization.
  • ⚠️ No check proved that a file's bound is taken after WHERE pruning: each test file held one contiguous range, so the raw and the pruned order agreed. AGREE: 05341 adds two files whose order flips under WHERE w = 1, checked against a mutation that ignores the filter.
  • 💡 The call-once key condition was first built on an IO-pool thread (an IN (subquery) set would run there). AGREE: it is built on the query thread before the probes start.
  • 💡 EXPLAIN PIPELINE over such a glob now reads the footers. Noted: the pass runs while the pipeline is built, as MergeTree index analysis does.
  • 💡 The cache-budget stop has no test arm. Noted: it bounds cache pressure only, never results.
  • 💡 The pass runs only with at most 4 streams, so reads with more threads see no change. Noted: stated in the description; with 8 streams the footer reads cost more than the order saves.

@clickhouse-gh

clickhouse-gh Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [586a299]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_asan_ubsan, azure, targeted) FAIL
03714_paimon_partition_pruning FAIL cidb
03714_paimon_partition_pruning FAIL cidb
03714_paimon_partition_pruning FAIL cidb
03714_paimon_partition_pruning FAIL cidb
03714_paimon_partition_pruning FAIL cidb
Too many test failures FAIL cidb

AI Review

Summary

The PR reads eligible local Parquet file footers and orders files by the best sort-key bound remaining after predicate pruning, tightening the shared ORDER BY ... LIMIT threshold earlier. Reviewed head 586a299946c12f6710b883eb21812e1b3d4028bd, the complete diff, and all prior PR discussion. The previously reported races and cache regressions are addressed in the current code. No remaining actionable findings.

Missing context / blind spots
  • ⚠️ No local ClickHouse binary or build directory was available, so runtime tests were not rerun. Validation relies on the focused regression tests and before/after measurements supplied in the PR discussion; the full CI run for this head had not completed when inspected.
Final Verdict

Status: ✅ Approve

@clickhouse-gh

clickhouse-gh Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

🟢 AI verdict: improvement — 1 query(s) improved out of 31 analysed

One query was flagged: clickbench Q20 improved by -42.3% (220 ms to 127 ms), and CPU time fell by about half. The delta is large and consistent, so the verdict stays as it is. However, this PR only adds a top-K footer pass that reorders the files a File-engine Parquet read hands out, plus related changes to the Parquet reader and metadata cache, and none of that runs for ClickBench's MergeTree table. The improvement is real but should not be credited to this change: it most likely comes from a difference between the PR build and the master base (other commits or build changes), so the PR's base commit should be checked against the benchmark base before reading anything into it.

clickbench

🟢 1 improved

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🟢 20 improvement 220 127 -42.3% <0.0001 cpu: Q20 is -42.3% with CPU time roughly halved. That is too large to override, but this diff only changes Parquet file ordering in the File engine, which a MergeTree scan never runs.

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: 5a21d6a7-7aa6-4eaa-b7da-62a25430bead
  • MIRAI run: e9932e4e-6a4a-45dd-bceb-73f1a8f18bb4
  • PR check IDs:
    • clickbench_86776_1791939023
    • clickbench_86997_1791939218
    • clickbench_87106_1791939232
    • tpch_adapted_1_official_87218_1791939238
    • tpch_adapted_1_official_87328_1791939244
    • tpch_adapted_1_official_87470_1791939261

CI runs each test of a non-sanitizer build in a cgroup with a 5 GiB
memory limit, so `clickhouse-local` gets a 4.5 GiB limit, and
`max_threads_min_free_memory_per_thread` (1 GiB) lowers `max_threads = 5`
to 4. The read then has 4 streams, the first pass runs, and the
`many 5` line of the test reports 10 footer lookups instead of 0.
Sanitizer builds get a 10 GiB limit, which is why they passed.

Disable the limit in the test, so every check gets the number of streams
it asks for. Reproduced with the CI `amd_binary` build of this PR: the
test fails with `--max_server_memory_usage=4831838208` and passes with
this change at 3, 4.5 and 32 GB, and in 16 concurrent runs at 4.5 GB.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/StorageFile.cpp Resolved
The first pass of `orderFilesByTopKBound` failed the query when it could not read
a footer. Its read lock excluded only writers through the same `StorageFile`, so a
`file(...)` read or a second `File` table on the same path could be rewritten
concurrently, and the pass then failed with `INCORRECT_DATA` on a file the readers
open later, possibly after the writer has finished. It also made `EXPLAIN PIPELINE`
fail on a glob with a corrupt file.

Now a file whose bytes are bad (`INCORRECT_DATA`: wrong magic, short read, bad
metadata) or that is gone gets no bound, and its reader reports the error as on
master if the file is still bad when it opens it. Other errors still fail the
query. This also covers a writer through the same table, so the read lock of the
pass is removed: its readers take the lock as on master. A version-token check
around the read is not enough: a file in the middle of a rewrite keeps its size and
mtime over the short footer read.

Measured with a debug build: an independent `clickhouse local` rewrites one of 6
files (truncating `INSERT INTO FUNCTION file`, 0.3 s between rewrites) while
another runs 300 top-K glob reads with `max_threads = 4` and
`storage_file_read_method = 'pread'`, 3 runs each:
- before: 27 / 20 / 36 failed reads, 14 / 13 / 18 thrown by the pass
- after: 23 / 17 / 22 failed reads, 0 thrown by the pass
- master: 22 / 34 / 32 failed reads, all thrown by the readers

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/StorageFile.cpp Resolved
The TopK key records the version of every file, and the sources take the
table's read lock only when they are created. A truncating INSERT into the
same table that runs between the two rewrites a file the key still
records; once another file's entry has been used, the read of the rewritten
file fails with FILE_CHANGED_DURING_READ. The first pass of the file order
reads the footers in that interval, which widened it from a few stats to a
footer read per file.

Take the read lock before the key is made; the sources take it again under
the same query id.

Measured on a debug build, ENGINE = File(Parquet) with 300 files, a top-K
read raced against a truncating INSERT (300 attempts): master 3 failed,
previous head 114, this commit 0. The new 05238 arm (8 files, 40 attempts
per run) fails 6/6 runs on the previous head; it had no failure in 200
attempts on master and passes 25/25 runs (-j8, random settings) here. Its
last line asserts that the reads hit the cache: with
use_query_condition_cache_for_top_k = 0 it prints 0.

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

clickhouse-gh Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 586a29994 with master d011c6b84 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

6 object files changed (+223.82 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/StorageFile.cpp.o 1.41 MiB 1.59 MiB +190.54 KiB (+13.22%)
src/CMakeFiles/dbms.dir/Processors/Formats/Impl/ParquetV3BlockInputFormat.cpp.o 758.08 KiB 789.09 KiB +31.01 KiB (+4.09%)

711 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

29 translation units recompiled, 420 s compile time in total, 29 of them have a recent master baseline.

Median compile-time ratio to the baselines is ×1.08 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +31.9 s (+8%) in total before that adjustment.

Job report

The arm raced one top-K read against a rewrite of one file, 40 times. In the
ASan flaky check every query takes about 0.6 s, so the arm alone took a median
of 109 s and the whole test 157 s; 5 of 32 runs exceeded the 180 s limit.

Race four reads per attempt instead of one, which lets 8 attempts replace 40,
and create the seven settled files in parallel.

Measured on a debug build against the previous head 1a95618 (no read lock before
the key): an attempt fails with probability 13% with one read and 55% with four
(100 attempts each). With the new arm the test fails 30 of 30 runs there, only
with FILE_CHANGED_DURING_READ, and passes 50 of 50 runs (random settings) on
this head. With use_query_condition_cache_for_top_k = 0 the last line still
prints 0.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/StorageFile.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added comp-table-functions Table functions for temporary read/write to external systems (FROM ... tableFunction()). and removed comp-parquet-reader-v3 Issues related to the native Parquet reader. labels Oct 10, 2026
groeneai and others added 2 commits October 10, 2026 06:43
The key holds the version token of every file, and a file rewritten after the key is made fails
the read with FILE_CHANGED_DURING_READ once an entry of another file has been used. The table's
read lock serializes only writers of this `File` table; a `file(...)` INSERT, a second `File` table
on the same path or any other process can still rewrite a file, and making the key before the
footer pass added the pass to that window.

Measured with a truncating `INSERT INTO FUNCTION file(...)` into one of 300 files of a `File` table
glob, racing a warm top-K read, 100 attempts each: FILE_CHANGED_DURING_READ 51 before, 17 and 12
after (master: 5 and 15, plus 21 and 24 INCORRECT_DATA from reading the file mid-write).

The pass does not use the key: it reads only footers, and the best-value tracking the key enables
matters only to readers of row data.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
perf.py expands every {name} in a performance test as a substitution
parameter, so the literal {_partition_id} of the fill query raised
KeyError and the test never ran. Double the braces so perf.py passes
{_partition_id} through to the server.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/StorageFile.cpp Resolved
Since the key is made after the footer pass, it hashed the files in the
order the pass chose, so a read with the pass (at most 4 streams) and the
same read without it (more streams, or the pass disabled) used different
keys and did not share entries. The entries do not depend on the order in
which the files are read, so hash the files sorted by path.

Measured on an ENGINE = File(Parquet) table of 8 files: before, a read at
max_threads = 8 after one at max_threads = 4 had 0 cache hits and read
7800 rows; after, 8 hits and 100 rows. 05243 (no-parallel, as the cache is
instance-wide) checks the reuse in both sort directions, so that the order
of the directory listing cannot hide it, and that the pass did reorder.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/StorageFile.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added comp-parquet-reader-v3 Issues related to the native Parquet reader. and removed comp-table-functions Table functions for temporary read/write to external systems (FROM ... tableFunction()). labels Oct 10, 2026
# Conflicts:
#	src/Storages/StorageFile.cpp
…p-k-file-order

Resolve conflicts with `readMinMaxFromStatistics` (min/max from Parquet statistics) in `Reader.cpp` and `ReadFromFile::initializePipeline`. Keep master's early return from `prefilterAndInitRowGroups` when `min_max_chunk` is set, now that it is split into `prefilterRowGroups` and `initRowGroups`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/StorageFile.cpp Resolved
…op-K file order pass

A rerun of `ORDER BY ... LIMIT n` over a `File(Parquet)` table finds TopK
query condition cache entries that exclude every row group of most files, and
`StorageFileSource` then skips those files without creating a reader. The pass
still read and analyzed their footers, so the rerun lost the cache's speed-up:
100 files x 100 row groups x 17 columns, `max_threads = 1`, release build:
warm rerun 39 ms with the pass vs 3 ms without it, 93 footer lookups.

The pass now consults the same entries as the reader (the plain predicate key
and the TopK key, built from the same sorted file set and version tokens) and
does not probe a file whose row groups are all excluded. It leaves such files
without a bound, so they go after the others, where their readers skip them.
Measured, two release servers interleaved: warm rerun 39 -> 5 ms (2 footer
lookups), cold read unchanged within noise (90 vs 92 ms, 106 vs 102 ms).

The new line in 05243 reruns the ascending read with the pass after the cache
was filled; it reads only the footer of f_4 (the pass and its reader: 2
lookups) instead of all four (5).

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 1d61eeb

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (arm_asan_ubsan, targeted) not from this PR: the job ran no test. Its test-selection step could not reach the CI database (play.clickhouse.com refused connections, [Errno 111] Connection refused, 09:35-09:38 UTC), so Failed to get previously failed tests required for test selection #125613 (mine, open): it fixes the timeout case of this same lookup and asks the CI owner whether a refused connection should skip the job too; the outcome will be posted here
Stateless tests (amd_asan_ubsan, db disk, distributed plan, targeted) same CI database outage in the test-selection step (09:45-09:48 UTC), no test ran #125613 (mine, open), same as above
Integration tests (amd_asan_ubsan, db disk, targeted) same CI database outage in the test-selection step (09:39-09:42 UTC), no test ran #125613 (mine, open), same as above
Build profile diff not from this PR: the master commits walk got HTTP 503 from the GitHub API at 11:27 UTC (No server is currently available to service your request) and does not retry it; #125328 failed the same way 4 minutes earlier a fix task is created (investigating at full effort, fixing-PR link to follow here)
Mergeable Check, PR praktika rollups of the rows above #125613 (mine, open) and the fix task above

The 75 DROPPED jobs of this run did not start after the targeted errors. This PR's own tests 05243_query_condition_cache_top_k_parquet, 05341_parquet_top_k_file_order and 05238_file_engine_concurrent_insert_select passed in all five flaky checks and in every other job that ran them.

Session id: cron:our-pr-ci-monitor:20261014-130007

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Build profile diff GitHub 503 failure: #125807

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the targeted-job test-selection Connection refused errors in the CI ledger above: #125613. A refused connection to the CI database is now retried for up to 3 minutes, then the targeted job skips instead of erroring.

alexey-milovidov pushed a commit to tripleaceme/ClickHouse that referenced this pull request Oct 19, 2026
…ter walk

`_list_commits_page` ran one `gh api repos/ClickHouse/ClickHouse/commits`
call and raised on the first non-zero exit or timeout, and the per-TU
master first-parent walk makes ~20 such calls per job. GitHub fails single
requests (HTTP 503 and 504, a body cut short so `--jq` reports `unexpected
end of JSON input`, a stalled body) while the requests around them succeed,
so one blip errored the whole check: 9 jobs on 9 PRs between 2026-10-03 and
2026-10-14, the failing anchors 11-15 days deep in walks whose earlier
fetches had just succeeded, and the same commits passing on other runs.

Retry the listing up to 3 times (after 5 s, then 10 s), keeping the 120 s
per-call timeout. A timeout, an HTTP 5xx or 429, or a failure whose stderr
names no HTTP status is retried; any other 4xx (unknown sha, permissions)
fails at once, since `gh` reports an HTTP error as `gh: <message> (HTTP
<status>)`. After the last attempt the error propagates as before, so the
walk stays fail-close as the `extend_master_shas` docstring requires. The
praktika `GH` helpers retry but pass no subprocess timeout, which ClickHouse#115201
kept on this call site on purpose.

CI reports:
- https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=124959&sha=1d61eebf3fe5ed809d4811ea947169074a3e1712&name_0=PR&name_1=Build%20profile%20diff
  (ClickHouse#124959)
- https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=125328&sha=ab772cc3b97c2e6777f2ef60723bcbeb5a5f29e3&name_0=PR&name_1=Build%20profile%20diff
  (ClickHouse#125328)
- https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=122585&sha=bf8b2d2470663e1b5703c2014b7887fe2d5dd239&name_0=PR&name_1=Build%20profile%20diff
  (ClickHouse#122585)
- https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119371&sha=88edddd16dcd4250ac56e1642f964a03763097f4&name_0=PR&name_1=Build%20profile%20diff
  (ClickHouse#119371)

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

Copy link
Copy Markdown

@groeneai is a rebase planned? The PR now conflicts with master (among other changes, #125528 changed the Parquet metadata cache it uses), and the best-bound-first order still has clear headroom on current master.

Official master build 2898c54, ARM 4 vCPU (default max_threads = 4), ClickBench's 100-file Parquet layout (hits_0..99.parquet, 325 row groups), ClickBench protocol (fresh clickhouse local per run), 3 rounds:

Query Row groups read (top-K skipped the rest) Floor Hot time
Q25 SELECT SearchPhrase FROM hits WHERE SearchPhrase <> '' ORDER BY EventTime LIMIT 10 50–51 29 0.112–0.115 s
Q27 ... ORDER BY EventTime, SearchPhrase LIMIT 10 50–52 29 0.114–0.115 s

The floor is the number of row groups whose minimum EventTime is at or below the 10th result's EventTime; any other row group can be skipped once the threshold reaches that value. These 29 row groups sit in 20 of the 100 files, so reading those files first could cut Q25/Q27 from about 50 row-group reads to as few as 29 (−42%). With #124195's equal-bound skip, Q25's floor drops to 21. Q24 (SELECT * ... WHERE URL LIKE '%google%' ORDER BY EventTime LIMIT 10) also reads more row groups than its floor of 50.

The other open top-K PRs don't close this: with #124195, #124899 and #128290 applied (x86, 4 vCPU, in a build with other pending Parquet changes), Q25 still read 52 row groups.

…p-k-file-order

Resolves the conflicts with the Parquet footer cache changes on master
(ClickHouse#125528 and the lazy column chunks):
- `getOrSetMetadata` now returns the cache cell, so the footer probe uses it
  and `getOrSetMetadataCell` is dropped;
- the probe reads the footer with `readFileFooter` and `setFileFooter`;
- `keep_filter_column_statistics` is set before the file order pass;
- the includes master now has in `StorageFile.cpp` are not repeated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai and others added 2 commits November 1, 2026 15:02
…file order pass

Since ClickHouse#125528 a reader skips a local Parquet file without opening it when the
statistics kept with its cached footer exclude the filter. The file order pass
ran before that check and still analysed the footer of every such file, so a
repeated query whose filter excludes most files paid for footers it never
reads. The pass now uses the same `ParquetCachedStatisticsFilter` check and
leaves such files without a bound, as it already does for the files the query
condition cache excludes.

Measured (debug build, 100 files x 100 row groups x 17 columns, the cached
statistics exclude 99 files, warm, pass on vs off by
`input_format_parquet_preserve_order`, 40 interleaved pairs, median wall):
1 thread 12.96 -> 9.34 ms (off: 7.6 ms), 4 threads 9.27 -> 8.47 ms (off: 7.5-8.0 ms).
05341 checks that the second read analyses only the footer of the file the
statistics do not exclude.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…p-k-file-order

Resolves the conflict with ClickHouse#128336 in `Reader.h`.

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

groeneai commented Nov 1, 2026

Copy link
Copy Markdown
Collaborator Author

Yes: master is merged in 2bf669f (a merge, as the branch already carries master merges), with the footer pass adapted to the new metadata cache and, in 14edfe2, skipping the files that the statistics cached by #125528 exclude.

The pass skips the footer of a file whose cached verdicts exclude every
row group, but it looked the verdicts up only under the storage UUID. A
`file` table function or a `File` table in an `Ordinary` database has no
UUID, and its readers keep their entries under the synthetic id from
`QueryConditionCache::getTableIdForFileEntries`, so for these sources the
pass still read the footers of files their readers skip.

The id is now computed once before the pass and passed to it. It is also
computed when there is a top-K filter but no condition hash: the key is
built only after the pass, and without either no reader consults the
cache, so the id is unused then.

Warm rerun of `ORDER BY k LIMIT 3` over 100 files x 100 row groups through
`file` (debug build, max_threads = 1): 101 -> 2 footer lookups, median
15.5 -> 6.5 ms, the same 100 cache hits, rows and result.

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

Copy link
Copy Markdown

Measured the rebased PR against the master it was built on: CI's build of 2bf669f merged into master 3c4f8ea vs CI's performance-reference build of 3c4f8ea, which uses the same build flags. (The later 3ffdd26 only changes the query condition cache lookups, and that cache is empty in a fresh process.) Setup as in my earlier comment: ARM 4 vCPU (default max_threads = 4), ClickBench's 100-file Parquet layout, fresh clickhouse local per run. Hot time is the median of best-of-two warm runs; Δ is the paired geometric-mean change with a bootstrap 95% CI over 30 interleaved rounds (10 for Q24, Q2 and Q3).

Query Row groups read, master → PR (floor) Hot time, master → PR Δ time Δ CPU
Q24 87 → 49 (50) 0.426 → 0.318 s −24.5% [−26.9, −22.0] −33.3% [−35.5, −31.2]
Q25 50 → 44 (29) 0.113 → 0.106 s −6.3% [−7.8, −5.0] +0.2% [−0.5, +0.9]
Q27 51 → 44 (29) 0.114 → 0.107 s −6.4% [−8.1, −4.7] −0.1% [−0.8, +0.7]
Q26 … ORDER BY SearchPhrase LIMIT 10: the pass runs, nothing to reorder 325 → 325 0.450 → 0.455 s +1.3% [−0.4, +3.1] +0.8% [+0.7, +1.0]
Q2 (no ORDER BY … LIMIT) 237 → 237 0.055 → 0.056 s +1.5% [−1.7, +4.3] −0.5% [−1.7, +0.7]
Q3 (no ORDER BY … LIMIT) 325 → 325 0.131 → 0.131 s 0.0% [−1.1, +1.2] −0.2% [−1.1, +0.7]

Q24 now reaches its floor. Q25 and Q27 skip 6–7 more row groups, about 30% of their gap to the floor. With max_threads = 1 the PR still reads 38 row groups for Q25 (master: 52), so most of the remaining gap does not come from the parallel streams. Peak memory: +18 MiB on Q24 (140 → 158 MiB), the others within ±4 MiB.

Results are identical. Q25's output varies between runs on master too, because 8 rows tie at its 10th EventTime; every output of both builds holds the same 4 rows below it plus 6 of the 8 tied rows.

`orderFilesByTopKBound` uses `query_condition_cache_table_id` only under
`USE_PARQUET`, so builds without it (Fast test, `ENABLE_LIBRARIES=0`)
failed with `-Werror,-Wunused-parameter`.

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

Copy link
Copy Markdown
Contributor

Should we / do we do this for MergeTree? I recall specially without WHERE then we will pick the top K candidate parts but AFAIK we don't do any sensible reverse-reading or reading backward by partition if the ORDER BY LIMIT column is backward of the ordering key (even if not directly as a prefix of the key, e.g. toDate(ts) in partition key, or (a, b, ..., ts) in parts).

@groeneai

groeneai commented Nov 1, 2026

Copy link
Copy Markdown
Collaborator Author

It depends on whether the ORDER BY column is a prefix of the sorting key. Measured on master c189bd9 with max_threads = 1: 2M rows in 20 parts over 10 daily partitions (PARTITION BY toDate(ts)), query ... WHERE v % 10 = 1 ORDER BY ts [DESC] LIMIT 10, rows read (SelectedRows):

Table ASC DESC
ORDER BY ts 1,143 866 (16,631 with read_in_order_use_virtual_row = 0)
ORDER BY (a, ts) 236,978 908,708
ORDER BY v, INDEX ts TYPE minmax 131,190 1,668,599
same, partition order reversed 2,000,087 88,925
  • ORDER BY on a sorting-key prefix, or on a monotonic function of one: read in order handles both directions, and read_in_order_use_virtual_row (on by default since 26.8) lets the merge read only the parts whose first key value in the sparse index can still reach the result (plus a small read-ahead window). That is the MergeTree counterpart of this PR.
  • Otherwise there is no read in order. Without a WHERE, a minmax skip index on a numeric or date column lets index analysis keep only the granules that can hold the top N (use_skip_indexes_for_top_k; 10 marks here in both directions). With a WHERE, or without that index, the use_top_k_dynamic_filtering threshold skips granules using the skip index, or the primary key when the column is in it. But the read order comes from the part list (ascending partition ID in this run), not from the parts' bounds. Neither the partition minmax_idx (which holds min/max of ts for toDate(ts)) nor the skip index orders the reads, so the cost depends on where the best values sit, as the last row shows.

So yes, MergeTree has the same gap in that last case. Closing it would mean sorting the parts (or read tasks) by such a bound in ReadFromMergeTree before they are spread over the streams. This PR does not touch MergeTree.

groeneai and others added 2 commits November 1, 2026 19:09
…tring sorts

A statistics-only top-K read (a `String` sort column with
`use_top_k_dynamic_filtering_for_variable_length_types = 0`) uses the
query condition cache like a read without top-K, whatever
`use_query_condition_cache_for_top_k` says, and its reader skips the files
that the predicate's entries exclude. The footer pass consulted those
entries only while that setting was on, so with it off a warm rerun read
the footers of files that are then skipped. The pass now takes the plain
predicate key under the same condition as the reader.

Warm rerun of `SELECT k, s ... WHERE cityHash64(k) = cityHash64(toUInt64(0))
ORDER BY s LIMIT 3` over an Atomic `File(Parquet)` table of 100 files x 100
row groups x 17 columns (debug build, max_threads = 1,
use_query_condition_cache_for_top_k = 0): 101 -> 2 footer lookups, median
15 -> 5 ms (4 ms with the pass off), the same 100 cache hits, rows and result.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The `string_asc_pass_rerun` arm failed in the flaky checks (`0 8` instead
of `4 2`) whenever the runner drew `optimize_move_to_prewhere = 0`
(5% of runs; all three failures had it). Without PREWHERE the Parquet
reader does not evaluate the predicate, so every row group counts as
matched, the first read records no query condition cache entry, and the
rerun's readers and footer pass both read every file. The readers and the
pass stay consistent, so only the test was wrong.

Pin `optimize_move_to_prewhere = 1` (and the obsolete
`query_plan_optimize_prewhere = 1`, as the rest of the file does) in the
arm's settings. Locally: the old test reds 5/5 randomized runs with that
draw forced, the new one passes 20/20 with it forced and 40/40 randomized,
and the binary before the String sort fix still gives `4 5`.

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

Copy link
Copy Markdown

At 16 threads, as on ClickBench's c6a.4xlarge and c8g.4xlarge machines, this PR does not change Q24, Q25 or Q27: orderFilesByTopKBound returns when num_streams > max_streams_to_order (4). The order has the most to gain there: on master, Q25 reads 48, 57 and 71 row groups at 4, 8 and 16 threads (floor 29). With the cap raised to 64, Q24, Q25 and Q27 get 8–14% faster, but Q26 gets up to 6% slower and a 29 ms ORDER BY EventDate LIMIT 10 11–19% (3–6 ms) slower.

Setup: ARM, 16 Graviton3 cores, the 100-file layout of my earlier comment in the page cache, fresh clickhouse local per run, max_threads = max_parsing_threads = 16. Master 607c2a3 against this PR's head cda0fc1 merged into it, as is and with max_streams_to_order = 64. Δ is the paired geometric-mean change in query time (--time) and process CPU time over 10 rotated rounds, with the Student-t 95% CI; n.s. means the CI includes 0.

This PR as is: Q24 −0.6%, Q25 +3.0%, Q27 −4.2%, all n.s.

With max_streams_to_order = 64:

Query Row groups read, master → cap 64 (floor) Δ time Δ CPU Δ time in two more runs
Q24 93 → 63 (50) −13.7% [−16.5, −10.8] −22.7% −13%, −12%
Q25 71 → 43 (29) −13.0% [−16.9, −8.8] −14.2% −9%, −9%
Q27 71 → 43 (29) −7.6% [−13.8, −1.0] −15.5% −11%, −14%
Q26 +6.3% [+2.9, +9.8] +1.2% +2%, +3% (both n.s.)
SELECT EventDate FROM hits ORDER BY EventDate LIMIT 10 (29 ms) +18.7% [+7.8, +30.6] +10.4% +11% (n.s.), +12%
SELECT WatchID FROM hits ORDER BY WatchID LIMIT 10 (40 ms) −2.2% (n.s.) −9.5% −3%, +1% (both n.s.)

The time cost is waiting, not footer work. The pass runs to completion in initializePipeline before the sources start, so in two traces of the EventDate query the first top-K threshold is set 12.8–13.5 ms after the query starts instead of 6.7–6.9 ms. Reading the footers with 4 tasks instead of 16 removes the extra CPU (+1% instead of +11%) but makes the pass longer and the EventDate query slower (+15% instead of +12%). Stopping after the first round when all its bounds are equal recovers Q26 (−3.3% against cap 64), but not the EventDate query, whose bounds differ.

So lifting the cap seems to need the pass to overlap the first reads, for example by reading the footers on the sources' own threads, or by letting the sources start on the best files found so far instead of waiting for all footers. Outputs are identical to master's, except that Q25's choice among the rows tied at its 10th EventTime varies between runs, on master as well.

@groeneai if you change the pass along these lines, should I rerun this 16-thread set on that head?

@snelheidai

Copy link
Copy Markdown

The 11–19% that max_streams_to_order = 64 cost the ORDER BY EventDate LIMIT 10 query in my previous comment came from the waits for the file descriptor table to grow, reported in #129891. With the table pre-sized for both builds, cap 64 no longer slows that query measurably, and Q24, Q25 and Q27 get 14–18% faster at 16 threads:

Query Δ time, cap 64 vs master, both pre-sized [95% CI]
Q24 −14.5% [−16.5, −12.5]
Q25 −16.0% [−20.8, −10.9]
Q27 −17.6% [−20.8, −14.1]
Q26 +3.2% [+1.7, +4.7]
SELECT EventDate FROM hits ORDER BY EventDate LIMIT 10 (20.5 ms on master) +2.9% [−0.7, +6.6], n.s.

So the pass does not need to overlap the first reads. The first option I suggested, reading the footers on the sources' own threads, did not help: without the pre-size it slowed the EventDate query as much as this PR's pass (+13–26% against +15–24% in the same three runs), and with it both were equally fast. Once #129891 is fixed, the cap can be raised; until then, a fresh clickhouse local keeps the trade-off of my previous comment. For the remaining Q26 cost, the early stop described there recovered 3.3%.

Setup as in my previous comment, except: master de8acb3 against this PR's cda0fc1 applied to it; every run started with descriptor 300 open (300</dev/null), which pre-sizes the table like the #129891 patch; 12 rotated rounds. Outputs are identical apart from Q25's ties. Query numbers count from 1, as in my earlier comments; #129891 counts from 0.

…p-k-file-order

Resolves the conflicts with the split of a single file into buckets
(`trySplitSingleFile`) in `StorageFile`, and with the `RowGroupSelection`
argument and the dictionary top-K bound in `Parquet/Reader`:
`prefilterRowGroups` now takes a `RowGroupSelection`, as
`prefilterAndInitRowGroups` does.

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

@clickhouse-gh clickhouse-gh Bot left a comment

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.

AI review approves this commit, see the AI Review comment.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 586a299

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (arm_asan_ubsan, azure, targeted) / 03714_paimon_partition_pruning flaky, not from this PR: the first run of the test in this job passes and the repeated runs fail, because the query condition cache from the first run skips data files and the files-read counts drop (17 PRs in 30 days, same diff). This run started at 15:34Z, before the fix merged at 18:45Z #131696 (mine, merged)
Stateless tests (arm_asan_ubsan, azure, targeted) / Too many test failures the job stopped at its --max-failures limit after the row above #131696 (mine, merged)
PR praktika rollup of the rows above #131696 (mine, merged)

Session id: cron:our-pr-ci-monitor:20261116-193019

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-parquet-reader-v3 Issues related to the native Parquet reader. groeneai-origin-issue PR origin: picked up an external GitHub issue pr-performance Pull request with some performance improvements

Projects

None yet

4 participants