Repository navigation
Conversation
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]>
Internal second-model review (rounds 1-4): 4 fixed, 3 noted
|
|
Workflow [PR], commit [586a299] Summary: ❌
AI ReviewSummaryThe PR reads eligible local Parquet file footers and orders files by the best sort-key bound remaining after predicate pruning, tightening the shared Missing context / blind spots
Final VerdictStatus: ✅ Approve |
|
📊 Cloud Performance Report 🟢 AI verdict: 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)
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
|
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]>
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]>
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]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes6 object files changed (+223.82 KiB total), 0 added.
711 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units29 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 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]>
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]>
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]>
# 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]>
…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]>
CI finish ledger - 1d61eebEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
The 75 Session id: cron:our-pr-ci-monitor:20261014-130007 |
|
Fixing PR for the Build profile diff GitHub 503 failure: #125807 |
|
Fixing PR for the targeted-job test-selection |
…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]>
|
@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
The floor is the number of row groups whose minimum 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]>
…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]>
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]>
|
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
Q24 now reaches its floor. Q25 and Q27 skip 6–7 more row groups, about 30% of their gap to the floor. With Results are identical. Q25's output varies between runs on master too, because 8 rows tie at its 10th |
`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]>
|
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). |
|
It depends on whether the
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 |
…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]>
|
At 16 threads, as on ClickBench's c6a.4xlarge and c8g.4xlarge machines, this PR does not change Q24, Q25 or Q27: Setup: ARM, 16 Graviton3 cores, the 100-file layout of my earlier comment in the page cache, fresh This PR as is: Q24 −0.6%, Q25 +3.0%, Q27 −4.2%, all n.s. With
The time cost is waiting, not footer work. The pass runs to completion in 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 @groeneai if you change the pass along these lines, should I rerun this 16-thread set on that head? |
|
The 11–19% that
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 Setup as in my previous comment, except: master de8acb3 against this PR's cda0fc1 applied to it; every run started with descriptor 300 open ( |
…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]>
CI finish ledger - 586a299Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20261116-193019 |
Closes: #124672
Related: #123639
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
ORDER BY ... LIMITover a glob of local Parquet files read withmax_threadsup 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
ReadFromFilehands the files of a glob to its streams in directory order, so forORDER BY x LIMIT nthe 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, throughParquetMetadataCache, so each footer is read once), each file gets the best row-group bound of the sort key its statistics allow afterWHEREpruning, 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 = 1anduse_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 aFiletable the pass runs under the table's read lock, so a concurrentINSERTwaits instead of failing the read withFILE_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%INT64->DateTimestatistics (Use statistics of a plain ParquetINT64column read asDateTime#124863): -26.5% / -11.6%New test
05341_parquet_top_k_file_order(fails on master), concurrentINSERTcases in05238_file_engine_concurrent_insert_select, cache reuse cases in05243_query_condition_cache_top_k_parquetand perf testparquet_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]