Skip to content

Read a single local Parquet file by several sources in parallel - #125738

Merged
alexey-milovidov merged 38 commits into
masterfrom
parquet-single-file-parallel-read
Nov 10, 2026
Merged

alexey-milovidov merged 38 commits into
masterfrom
parquet-single-file-parallel-read

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Oct 14, 2026 •

Copy link
Copy Markdown
Member

Related: #104431

A single large Parquet file read through file or the File engine was read by one source, and the pipeline started with Resize 1 → N. The reader decodes in its own thread pool, but its central scheduling keeps only a fraction of the cores busy (measured on 96 cores: bursts of ~30 busy threads, ~10 on average, vs ~95 for the same data split into 100 files). On ClickBench, single-file clickhouse-parquet is 2–4x slower than clickhouse-parquet-partitioned on the heaviest queries.

This is a redesign of #104431 (which is not needed with this PR):

  • ReadFromFile splits a single local Parquet file into up to max_threads buckets, and every bucket is read by its own source — the same shape as a partitioned dataset. There are no size thresholds: the number of sources is limited only by the number of row groups.
  • Row groups are interleaved between the buckets rather than assigned in contiguous ranges, so the row groups surviving min/max pruning (e.g. CounterID = 62 in ClickBench) are spread across all readers.
  • The footer is parsed once at planning (through ParquetMetadataCache) and shared by all readers; the cache now hands out a shared pointer instead of a deep copy on every read.
  • When each source would get at most one parsing thread, the readers decode in the pipeline threads instead of a separate pool.
  • The query condition cache is consulted once for the whole file; its entry is written after all buckets are read, so a row group of another bucket is never recorded as unmatched. Every source checks that it reads the version of the file that was split and fails with FILE_CHANGED_DURING_READ otherwise. Count-only reads, min/max from statistics, TopN reads, lazy materialization, input_format_parquet_preserve_order and parallelize_output_from_storages = 0 keep the old path.

Things that made many readers of one file slow, fixed along the way:

  • a reader of a bucket put all row groups of the file through the stages of reading (statistics, bloom/dictionary filters, page index) only to skip the ones of other buckets at the end — with 96 buckets that was 96x the work;
  • the hot paths of ReadManager looked up their logger under a global mutex;
  • every log macro (including disabled ones) copied the thread's ThreadGroupPtr to check whether it is attached, making all threads of a query contend on its reference counter.

ClickBench hits.parquet via clickhouse local (as in ClickBench), 96-core aarch64, best of 5, interleaved runs; geomean over 43 queries:

  • single file, this PR / master: 0.91
  • single file, this PR / partitioned (master): 0.96
  • e.g. Q20 0.40 → 0.25 s, Q21 0.80 → 0.29 s, Q22 1.31 → 0.39 s, Q27 0.77 → 0.41 s (partitioned: 0.34, 0.38, 0.45, 0.41 s).

Changelog category (leave one):

  • Performance Improvement

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

Reading a single large local Parquet file through the file table function or the File table engine is now parallelized across all threads: the file is split into buckets of row groups, each read by its own source, with the file metadata parsed only once. On ClickBench, reading a single hits.parquet file is now as fast as reading the same data split into 100 files, and up to 3x faster than before on the heaviest queries.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.1852-master (included in 26.11 and later)

A single large Parquet file read through `file` or the `File` engine was read
by one source, and the pipeline started with `Resize 1 -> N`. The reader decodes
in a thread pool, but its central scheduling keeps only a fraction of the cores
busy: on ClickBench, single-file Parquet was 2-3x slower than the same data split
into 100 files on the heaviest queries.

Now `ReadFromFile` splits such a file into up to `max_threads` buckets of
interleaved row groups, and every bucket is read by its own source, like a file
of a partitioned dataset. The footer is parsed once at planning (through the
Parquet metadata cache) and shared by all readers. The query condition cache is
consulted once for the whole file, and its entry is written after all buckets
are read. Every source checks that it reads the version of the file that was
split, and fails with `FILE_CHANGED_DURING_READ` otherwise.

Things that made many readers of one file slow, fixed along the way:
- a reader of a bucket put all row groups of the file through the stages of
  reading (statistics, bloom and dictionary filters, page index), only to skip
  the ones of other buckets at the end;
- the hot paths of `ReadManager` looked up their logger under a global mutex;
- every log macro (including disabled ones) copied the `ThreadGroupPtr` of the
  thread to check whether it is attached, making all threads of a query contend
  on its reference counter;
- `ParquetMetadataCache` returned a deep copy of the footer on every read.

Related: #104431
Related: https://benchmark.clickhouse.com/#system=+curp|Hoaus&type=-&machine=-ca4e|6t|ca2|ae-|6ax|g4e|6ale|3al&cluster_size=-&opensource=-&hardware=+c&tuned=+n&storage=-&metric=combined&queries=-

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

clickhouse-gh Bot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2abee4d]

Summary: ✅


AI Review

Summary

This PR parallelizes a single local Parquet file across sources, shares parsed metadata, and combines query condition cache results across buckets. Reviewed the current diff and code at 2abee4d2e21edbff60b57b4cfdc13439ecf264cc, including all prior discussion. The previous findings are addressed; no new actionable findings remain. Regression tests and before/after performance measurements are provided. No local build or tests were run during this review.

Final Verdict

Status: ✅ Approve.

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements comp-parquet-reader-v3 Issues related to the native Parquet reader. labels Oct 14, 2026
Comment thread src/Storages/StorageFile.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=125738&sha=a274028648018a2aeb5d833035ab513fe5a8c840&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%2C%20old_compatibility%29 (Logical error: Expected the argument №2 ('key' of type Int64) to have 1 rows, but it has 0 on SELECT count() FROM url(..., Parquet, 'key Int64, v Int64') WHERE 1 <=> key, STID 2959-3490; it also appears in PRs #98670, #125131, #125619, #117012, #123788) and provide a fix in a separate PR. If the fix is already in progress, link it here.

@groeneai

Copy link
Copy Markdown
Collaborator

Fix: #125024 (mine, open, awaiting review). It is the same bug as on #123788 and the other PRs you listed.

The fuzzer turned the 05325 URL into concat('(?i)', '/05325/key=9/data.parquet', currentDatabase()). url takes the Hive columns from the whole URI string, but the _path/_file pre-filter evaluates on Poco::URI::getPath(), which is just ( here (the rest is the query string), so key gets 0 rows in a 1-row block.

Checked with clickhouse local: master d245b786 aborts with this exact message; the #125024 CI build (48961116) returns INCORRECT_DATA ("Expected to find hive partitioning column key in the path ("). Unrelated to this PR: the failure is in StorageURL, which it does not touch.

alexey-milovidov and others added 3 commits October 15, 2026 03:02
`ReadFromFile::trySplitSingleFile` read the Parquet footer before any
`StorageFileSource` was constructed, i.e. without the storage's read lock. A
concurrent `INSERT` into the same `File(Parquet)` table, which holds the write
lock until the footer is written, could then make the split fail with
`INCORRECT_DATA` on the unfinished file instead of waiting for the insert.

Take the read lock before the initial `stat` and keep it in
`ReadFromFile::initializePipeline` until the sources, which take their own
read locks, are constructed.

Addresses review: #125738 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- `ParquetBucketSplitter::splitForParallelReading` no longer splits a file
  when `input_format_allow_seeks = 0`: in that mode every reader's
  `Prefetcher` copies the whole file into its own buffer, so `N` buckets
  would read the file `N` times and hold up to `N` copies of it in memory.
  Addresses review: #125738 (comment)

- `ParquetPrunedRowGroups` again counts the row groups outside of the bucket
  as pruned, unless the bucket is one of the buckets of a split file (whose
  other row groups are read by other readers of the same query). The buckets
  that come from the query condition cache (e.g. for `IcebergLocal`) leave
  out the row groups known to have no matching rows, and those were counted
  as pruned before. This fixes `04512_parquet_geo_pruning_iceberg_renamed_column`,
  `04513_parquet_geo_pruning_iceberg_renamed_bbox_column` and
  `04514_parquet_geo_pruning_geostats_fallback`.

- `05394_parquet_single_file_parallel_read`: the check that there are not more
  sources than row groups used `max_threads = 1000` on a file with ~100 row
  groups, but the server lowers `max_threads` according to the available
  memory (to 84 in CI: `Lower number of threads for query to 84 (1000
  requested)`). Use a small file with 8 row groups and `max_threads = 32`.
  Also check that a file is not split with `input_format_allow_seeks = 0`.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=125738&sha=a274028648018a2aeb5d833035ab513fe5a8c840&name_0=PR&name_1=Stateless%20tests%20%28arm_asan_ubsan%2C%20targeted%29
PR: #125738

Co-Authored-By: Claude Opus 5.5 <[email protected]>
With `input_format_parquet_preserve_order = 0` and
`parallelize_output_from_storages = 1`, the file with two row groups is now
read by two sources (`File × 2`) instead of one source followed by
`Resize 1 → 2`. This is the intended behavior of the change.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=125738&sha=a274028648018a2aeb5d833035ab513fe5a8c840&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20parallel%29
PR: #125738

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

clickhouse-gh Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 2abee4d2e with master f4435fcbb (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

26 object files changed (+70.76 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/Formats/Impl/ParquetV3BlockInputFormat.cpp.o 643.43 KiB 687.50 KiB +44.08 KiB (+6.85%)
src/CMakeFiles/dbms.dir/Storages/StorageFile.cpp.o 1.26 MiB 1.30 MiB +36.52 KiB (+2.83%)

719 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.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.95 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 7.5 s 16.3 s +9.2 s (+129%)
Compile time of recompiled translation units

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

Job report

# Conflicts:
#	src/Storages/StorageFile.cpp
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The only red check on 01cc571c is 05345_text_index_prewhere_read_step_order in Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) (report). It is a flaky MergeTree text-index test under parallel replicas (1 of 51 reruns failed) and has nothing to do with this PR. The fix is in progress in #125892. I merged master (resolved a conflict in StorageFile.cpp: addNumRowsToCache now takes the archive entry cache key, and I kept this PR's !split_file guard). The tree builds, and 05394_parquet_single_file_parallel_read and 02725_parquet_preserve_order pass locally.

Resolve a conflict in `StorageFile.cpp`: master renamed `isFileCacheVersionSettled`
to `isFileCacheVersionTokenSettled`; keep the split-file version check and use the
new name at all call sites. The merge also brings the fix for
`test_custom_s3_disk_remote_url_allow_hosts` (#126289).

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

Copy link
Copy Markdown

The ReadManager logger change in this PR also helps without the split. I measured it alone (the cached getRawLogger in ReadManager.cpp, same as getLog() here, without the hasGroup change or the split) on the 100-file ClickBench layout:

hits_0..99.parquet, warm server, 4-core Graviton3 master + logger change Change [95% CI]
Q2 SELECT COUNT(*) FROM hits WHERE AdvEngineID <> 0 51.0 ms 45.0 ms −12.1% [−13.8%, −10.5%]
Q8 SELECT AdvEngineID, COUNT(*) ... GROUP BY AdvEngineID 54.0 ms 48.0 ms −10.1% [−13.1%, −7.0%]
Q3, Q4, Q30 (more decoding per scheduling step) −2.1% to −3.0%
Q2, 4 concurrent clients 22.4 QPS 26.5 QPS +18%
Q8, 4 concurrent clients 21.0 QPS 24.5 QPS +16%

In a fresh clickhouse local per query (ClickBench protocol), Q2 was −6.8% [−12.5%, −0.6%] and Q8 −8.3% [−10.8%, −5.7%]. No measured query was significantly slower (20 on the server, 11 in clickhouse local); long scans such as Q21 did not change. Results were identical, apart from LIMIT queries with ties, which vary between runs of either build.

Measured on master 8aa4659 (Oct 16): Release build without LTO, clang 21, aarch64, both binaries from the same build directory. Latency: medians of 12 alternating rounds on two warm servers (10 for clickhouse local); the change is the geometric mean of the paired ratios. Concurrency: clickhouse benchmark -c 4, mean of 4 alternating rounds, whose ranges did not overlap. x86 and many-core hosts were not measured.

alexey-milovidov and others added 2 commits October 21, 2026 08:56
…-parallel-read

Resolve conflicts with the lazy parsing of Parquet column chunks: `Reader`
now holds a shared `FileFooter`, and `ParquetMetadataCache` hands out shared
cells. `ParquetFileBucketInfo` carries the parsed `FileFooter` and the cached
column chunks instead of a `FileMetaData`; with the metadata cache enabled,
bucket readers go through the cache (seeded with the footer of the split), so
column chunks parsed by one reader are reused by the others.

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

`ParquetBucketSplitter::splitForParallelReading` used the global metadata
cache regardless of the setting. Use it only if `use_parquet_metadata_cache`
is enabled, like the input format does; otherwise the footer parsed at planning
is still shared by the readers of all buckets.

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

Copy link
Copy Markdown
Member Author

🕵 Merged master (e189b7c). The conflicts came from the lazy parsing of Parquet column chunks (#124364). Reader now holds a shared FileFooter, and ParquetMetadataCache hands out shared cells, so this PR's own change to share cached metadata is now covered by master. ParquetFileBucketInfo now carries the parsed FileFooter and the cached column chunks. With the cache enabled, bucket readers go through the cache, which is seeded with the footer of the split, so column chunks parsed by one reader are reused by the others. The skip of other buckets' row groups in prefilterAndInitRowGroups is kept. 05394_parquet_single_file_parallel_read, 02725_parquet_preserve_order, the new 05441 test and the Parquet columns cache and query condition cache tests pass locally.

The perf failures on 6177ce61 look unrelated:

@snelheidai, thanks for measuring the ReadManager logger change on its own; good to know it helps the partitioned layout too.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=125738&sha=6177ce61b1cab3896c4bfe64545f3683d991f664&name_0=PR&name_1=Performance%20Comparison%20%28amd_release%2C%20master_head%2C%204%2F6%29 (limit_by #0 flagged as a confirmed regression; the test is unstable on master and slower on many unrelated PRs in the last 10 days) and provide a fix in a separate PR. If the fix is already in progress, link it here.

@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged. I'm investigating limit_by #0; I'll follow up here with a PR (or my findings) shortly.

First data point (CIDB, last 14 days): it is not slower on any of ~1120 master runs (new/old > 1.12: 0 of them), the 3 other PRs where it is slower all touch LimitByTransform or the hash tables it uses, and all 3 amd builds of this PR are slower (up to +30%) while the arm builds are not. So I'm starting from this PR's amd binary (the per-row loop of LimitByTransform) rather than from the test.

@groeneai

Copy link
Copy Markdown
Collaborator

The fix is #127172.

limit_by #0 (and optimize_limit_by_keys #0/#1, which run the same function) is slower in this PR's own amd binaries, not unstable on master: 0 of ~560 amd master runs in 14 days were slower, all 3 amd builds of this PR are 1.13-1.29x slower, and the 26 other amd builds of the last 12 days are not.

The per-row loop of LimitByTransform::consumeImpl contained a test-only LOG_TEST. ThinLTO inlines currentThreadHasGroup() into it, this PR's hasGroup() makes that block about 94 bytes smaller, and the loop moves 0x60 bytes earlier with identical instructions. #127172 removes that dead logging and the failpoints next to it (their only test was already removed), so the function is byte-identical with and without this PR's CurrentThread change. In a local ThinLTO A/B (a different CPU than CI) it is also 5-7% faster on these queries; its own amd Performance Comparison will show the CI side.

@groeneai

Copy link
Copy Markdown
Collaborator

Correction to my comment above: #127172 is not a fix, so I'm closing it.

Its own arm run made two-key LIMIT BY over millions of groups about 2x slower: limit_by_misc #3 0.61 -> 1.36 s (report) and limit_by_in_pk_order #1 0.59 -> 0.98 s (report). In both CPU profiles the extra time is in LimitByTransform::consumeImpl for 8-byte keys (326 -> 800 and 377 -> 655 samples). That loop runs the same instructions as on master apart from the removed row_idx == 5 compare and some alignment padding; only its layout changed. Of about 24,700 arm builds in the last 90 days, the only others that ran both queries this slowly were two builds of a compiler-upgrade PR.

So the speed of this loop depends on code layout on both architectures, and removing the cold code moves the problem instead of fixing it. The limit_by #0 red here is the same kind of effect in this PR's amd binary, not a regression in this PR's code. I don't have a layout-independent fix to offer.

alexey-milovidov and others added 2 commits October 23, 2026 08:47
…per query

With `use_parquet_metadata_cache = 0` (or with a cold cache), the reader of
every bucket of a file split by `ParquetBucketSplitter::splitForParallelReading`
parsed the selected columns' chunks of all row groups on its own, so `N`
sources kept `N` copies of the projected column metadata.

The buckets of one split now share a `Parquet::SharedFileColumnChunks`: a
reader takes the column chunks parsed by another reader of the same file and
publishes the ones it parses. The parsing happens under its mutex, so readers
that initialize at the same time wait for one of them instead of parsing the
same columns again. This works with and without the metadata cache.

Locally, summing 300 columns of a file with 5000 row groups with
`max_threads = 32` and the cache disabled: 3.59 GiB peak memory when split,
vs 4.34 GiB for the single-source read (`input_format_parquet_preserve_order = 1`).

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

Copy link
Copy Markdown
Member Author

🕵 Pushed d66508e: shared parsing of column chunks between the bucket readers of a split file (review item from clickhouse-gh, resolved), plus a merge of the latest master. Local runs of 05394_parquet_single_file_parallel_read, 05441_parquet_split_file_metadata_cache_setting, 02725_parquet_preserve_order and 04207_parquet_metadata_cache_local_file pass.

The only red on the previous commit was in the amd Performance Comparison: limit_by #0 and optimize_limit_by_keys #0/#1, which groeneai traced above to a code-layout effect in LimitByTransform::consumeImpl rather than to code this PR changes, and string_bytes_functions #0 (+555%), which runs no code this PR touches. Both will be re-measured on the new commit.

@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=125738&sha=e189b7c385325cb07857f05ee4cf50c87f41d067&name_0=PR&name_1=Performance%20Comparison%20%28amd_release%2C%20master_head%2C%206%2F6%29 (string_bytes_functions #0) and provide a fix in a separate PR. If the fix is already in progress, link it here.

Merged via the queue into master with commit 895e8ce Nov 10, 2026
188 checks passed
@alexey-milovidov
alexey-milovidov deleted the parquet-single-file-parallel-read branch November 10, 2026 12:58
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 10, 2026
@snelheidai

Copy link
Copy Markdown

On x86 at 16 threads, this PR makes the CPU-bound full scans of the single hits.parquet 2–6% slower, while the same queries over the 100-file layout are unchanged (Q18 1.004, Q28 1.002, Q32 0.993). The cause is the round-robin split: the file has 226 row groups of 151,669 to 819,200 rows, so with row group i in bucket i % 16 the largest bucket gets 7.40M rows against a mean of 6.25M (1.185x). User+system CPU time stays the same (0.98–1.01x), so the extra time is idle cores waiting for that bucket's reader. On a copy rewritten with more uniform row groups, where the largest bucket has 1.029x the mean rows, these losses disappear and the gains remain:

Query hits.parquet, master → PR, ms PR/master [95% CI] Uniform copy, PR/master [95% CI]
Q18 708 → 748.5 1.057 [1.051, 1.064] 0.989 [0.983, 0.995]
Q28 1104.5 → 1169 1.059 [1.053, 1.064] 0.993 [0.988, 0.997]
Q32 572 → 590 1.032 [1.027, 1.037] 0.995 [0.985, 1.005]
Q8 258.5 → 265 1.029 [1.013, 1.044] 0.939 [0.929, 0.949]
Q16 476 → 488 1.022 [1.011, 1.033] 0.986 [0.981, 0.990]
Q1 (control) 28 → 15 0.538 [0.522, 0.554] 0.563 [0.549, 0.577]
Q20 (control) 721 → 387.5 0.542 [0.530, 0.554] 0.527 [0.509, 0.546]

Official master builds 1dc3262 (before this PR) and 804ee9b (after) on an r6i.8xlarge pinned to 16 cores, a fresh clickhouse local --tmp --time per query with max_threads = max_parsing_threads = 16, files in the page cache, 10 alternating rounds (20 for the 100 files) after a dropped first; ratios are geometric means of the paired PR/master times. The copy was written by ClickHouse with output_format_parquet_row_group_size = 446418 (220 row groups). It is re-encoded, so compare ratios within a column, not times across files. Query numbers are 0-based.

The buckets of a file can be checked with:

SELECT n % 16 AS bucket, sum(rows) FROM (SELECT rowNumberInAllBlocks() AS n, r.num_rows AS rows FROM file('hits.parquet', ParquetMetadata) ARRAY JOIN row_groups AS r) GROUP BY bucket ORDER BY bucket

By the same arithmetic, the largest bucket has 1.26x the mean rows at 32 threads, 1.6x at 64 and 2.5x at 192, where the largest row group alone is 1.57x the mean.

@alexey-milovidov, for the planned rebalancing follow-up: assigning row groups largest first to the bucket with the fewest rows would bring the largest bucket to 1.013x the mean here (1.10x at 64 threads), and readers that take the next row group from a shared queue in that order would also adapt to row groups that differ in cost per row or are skipped by filters.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

@snelheidai, thanks, this is a good idea! @groeneai, let's do this follow-up.

@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged. I'm investigating a size-balanced assignment of row groups to the single-file buckets (largest row group first into the bucket with the fewest rows, instead of i % N), keeping the spread of the row groups that survive min/max pruning; I'll follow up here with a PR (or my findings) shortly.

@snelheidai

Copy link
Copy Markdown

@groeneai, I measured the static split you described: it speeds up the row-bound queries by 2.5–5% but makes the URL queries slower.

Query (0-based) i % 16, ms largest first by rows, ms ratio [95% CI]
Q20 452 476.5 1.048 [1.021, 1.076]
Q21 504.5 573.5 1.115 [1.093, 1.136]
Q27 491 509 1.053 [1.035, 1.072]
Q18 595.5 563.5 0.948 [0.942, 0.955]
Q28 1021 982 0.961 [0.955, 0.967]
Q32 501.5 480.5 0.956 [0.947, 0.965]
Q8 242 230 0.952 [0.939, 0.965]
Q16 414 402.5 0.975 [0.963, 0.988]
Q22 800.5 756.5 0.957 [0.941, 0.974]

User+system CPU time is the same in both (ratios 0.99–1.00), so the differences are idle time waiting for the slowest bucket. In hits.parquet the smaller row groups have longer URLs: 157 bytes per row in the smallest quarter of row groups, 64 in the largest. Balancing the rows of the 16 buckets (largest bucket 1.185x → 1.013x the mean) therefore unbalances their URL bytes (1.20x → 1.48x).

In a simulation, a static split weighted by the uncompressed or compressed size of the row group only moves the problem, leaving rows or URL bytes at 1.2x the mean or more. Readers that take the next row group from a shared queue in largest-first order stay at or below 1.06x for both, because the queue follows the actual cost. The queue would also spread the row groups that survive min/max pruning without a fixed interleaving.

Setup: official master build 804ee9b on a 16-core Graviton3 (r7g.4xlarge), the ClickBench File(Parquet) table, a fresh clickhouse local --tmp --time per query with max_threads = max_parsing_threads = 16, page cache warm, 20 alternating rounds after a dropped first; ratios are geometric means of the paired times. To get the exact largest-first buckets without a build, I reordered the row groups in the footer of a copy of hits.parquet so that i % 16 produces them. The column chunks and their offsets are unchanged; data checksums and query results match (Q32 up to ties).

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 11, 2026
…file

Since ClickHouse#125738 a single local Parquet file is read by one source per bucket, so
the last query of the test reads its file by two streams for two threads. With
as many streams as threads, the output of the read is now rebalanced, so the
pipeline has `Overflow`, `Resize` and `Concat` above the two `File` sources.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 11, 2026
Since ClickHouse#125738, a single local Parquet file read with several threads is
split between sources that each read some of its row groups. They
consult the query condition cache once, in `ReadFromFile::trySplitSingleFile`,
and write the row group entry once all buckets are read, in
`StorageFileSource::finishReadingSplitFileBucket`; the row block entry
was read and written only on the per-source path, so such reads got no
row blocks at all (05331 at 4 threads: the rerun filtered 1000001 rows
instead of 82497).

Read the row block entry together with the row group one before
splitting, pass it to every source, and merge the matched row blocks of
all buckets with OR: a reader reports the row groups of other buckets as
not matching, and a row block may span row groups of several buckets.
Write the entry only if every bucket reported its row blocks and the
same gates as for the row group entry hold. A file with no matching row
block is not split, so its only source skips it by the same entry.

05331 now runs the `File` case with `max_threads = 1` and adds a case
with `max_threads = 4` that reads the file as a split file.

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

Copy link
Copy Markdown
Collaborator

I opened #130740 for this follow-up. A static largest-first split slows down the URL queries (measured above: rows and bytes per row group are anti-correlated in hits.parquet), so the PR uses a shared queue instead: the file is split into up to 4 * max_threads round-robin buckets ordered largest first, and each source takes the next bucket from a shared counter. Round-robin buckets keep the row groups that survive min/max pruning spread. Two changes make the queue pay off with mmap (the clickhouse-local default): a source keeps the file open across its buckets, and MMappedFileDescriptor::finish calls madvise(MADV_DONTNEED) before munmap. Without that, the balanced sources drop their whole-file mappings at the same time and the concurrent munmap calls serialize (25-50 ms after the last reader at 16 threads, 5-6 ms with it).

x86, clickhouse local, hits.parquet, max_threads = max_parsing_threads = 16, 10 alternating rounds, paired geomean PR / master: Q8 0.962, Q16 0.968, Q18 0.962, Q28 0.960, Q32 0.942; Q20 0.901, Q21 0.879, Q27 0.909; all 43 queries 0.969. CounterID = 62 queries (Q36-Q42): 0.998-1.042 at 16 threads; Q39 is 1.07 at 96 threads. At 64 threads Q20 / Q21 / Q22 are 0.684 / 0.695 / 0.669. Q10 is 1.13 at 16 threads because one thread's aggregation table crosses adaptive_aggregator_freeze_threshold_bytes (0.953 with it set to 0). I have no aarch64 machine to measure on.

@snelheidai

Copy link
Copy Markdown

The Q39 slowdown of a split file (my comment above) comes from a missing Resize, and a two-line change fixes it: at 32 threads Q39 becomes 1.9x faster, and the CPU-bound scans 4–7% faster.

ReadFromFile::initializePipeline adds a Resize only when there are fewer sources than threads. A split file has as many buckets as threads, so each bucket stays bound to its own chain of transforms, and when most rows that pass the filter are in one row group, one thread aggregates them. At 32 threads, 29 of the 32 aggregating threads of Q39 get no rows, and one aggregates 467,687 of the 722,688 matching rows (traced on the same buckets read through s3(), #130785). The patch below adds the Resize after the sources of a split file even when there are as many sources as threads.

Query (0-based) master, ms master + patch, ms patch / master [95% CI]
Q39 203 108 0.529 [0.507, 0.552]
Q36 95 73 0.725 [0.669, 0.786]
Q37 58 46 0.805 [0.788, 0.823]
Q40 36 31 0.877 [0.829, 0.927]
Q34 837 769 0.927 [0.904, 0.951]
Q28 1019 951 0.936 [0.925, 0.947]
Q33 819 763 0.936 [0.926, 0.945]
Q18 630 596 0.947 [0.937, 0.957]
Q16 417 395 0.949 [0.942, 0.956]
Q8 232 221 0.955 [0.932, 0.979]
Q1 (cost) 17 18 1.059 (+1 ms in every pair)
Q7 (cost) 19 20 1.052 [1.007, 1.099]

Q20–Q22 are unchanged (1.048, not significant; 1.001; 0.985). The geometric mean of all 43 queries is 0.955.

Setup: local Release builds of master a62d3fd (includes this PR) and of master + the patch; 32 vCPU Xeon 8375C; hits.parquet through the File(Parquet) table of ClickBench's create.sql; a fresh clickhouse local --time per query with default settings (max_threads = 32); page cache warm; 6 rounds with the arms alternating and the first round dropped; medians of 5, ratios are geometric means of the paired times. I have not rerun it on the 4-core Graviton3 of my first comment. Results are the same as master (for the 9 queries with ties at LIMIT, the ORDER BY columns match). In a CI-like run of 812 Parquet and object-storage stateless tests, only 02725_parquet_preserve_order differs: its EXPLAIN PIPELINE now shows Resize 2 → 2 above the split sources, and the patch updates the reference.

#130740 keeps this condition, so there too the rows of a bucket stay with the source that read it. The patch applies cleanly on top of #130740 (not measured together). @groeneai, would you fold it into #130740 or open a separate PR?

Patch against master a62d3fd
diff --git a/src/Storages/StorageFile.cpp b/src/Storages/StorageFile.cpp
index 7cae04653fa..2530846de01 100644
--- a/src/Storages/StorageFile.cpp
+++ b/src/Storages/StorageFile.cpp
@@ -3328,7 +3328,11 @@ void ReadFromFile::initializePipeline(QueryPipelineBuilder & pipeline, const Bui
     const bool parallelize_output = ctx->getSettingsRef()[Setting::parallelize_output_from_storages];
     /// `max_num_streams` is a read-parallelism request, not a thread budget.
     const size_t resize_to = std::min(max_num_streams, build_settings.max_threads);
-    if (parallelize_output && storage->parallelizeOutputAfterReading(ctx) && output_ports > 0 && output_ports < resize_to)
+    /// The buckets of a split file are given to the sources in advance, and one bucket can have much more rows
+    /// to process than the others, e.g. when most rows passing the filter are in one row group. Resize even if
+    /// there are as many sources as threads, so that the rows of any bucket can be processed by any thread.
+    if (parallelize_output && storage->parallelizeOutputAfterReading(ctx) && output_ports > 0
+        && (output_ports < resize_to || (split_file && output_ports > 1)))
         pipe.resize(resize_to);
 
     if (pipe.empty())
diff --git a/tests/queries/0_stateless/02725_parquet_preserve_order.reference b/tests/queries/0_stateless/02725_parquet_preserve_order.reference
index ce91c5aed9e..480471c0e06 100644
--- a/tests/queries/0_stateless/02725_parquet_preserve_order.reference
+++ b/tests/queries/0_stateless/02725_parquet_preserve_order.reference
@@ -8,4 +8,5 @@ ExpressionTransform
 (Expression)
 ExpressionTransform × 2
   (ReadFromFile)
-  File × 2 0 → 1
+  Resize 2 → 2
+    File × 2 0 → 1

@alexey-milovidov

Copy link
Copy Markdown
Member Author

@groeneai, the first PR is already in the merge queue, so you can send a follow-up.

@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged. I will send the split-file Resize change in ReadFromFile::initializePipeline as a separate follow-up PR (on top of #130740, measured there); I'll follow up here with the PR link (or my findings) shortly.

velom pushed a commit to velom/ClickHouse that referenced this pull request Nov 11, 2026
`05141_parquet_time_stats_pruning` and
`05361_parquet_geometry_logical_type_interop` grep row group counters from
`clickhouse-local --print-profile-events` and expect one line per counter
with its total.

Since ClickHouse#125738 a single local Parquet file is split into buckets read by
separate sources, and each bucket's `ReadManager::init` adds its own share
of `ParquetReadRowGroups` / `ParquetPrunedRowGroups`. `LocalConnection`
sends a ProfileEvents packet with the deltas every `interactive_delay`
(100 ms), and with the default `--profile-events-delay-ms=0` the client
prints every packet separately. When the sources initialize on both sides
of a packet (sanitizer builds, loaded runners), a counter is printed as
partial lines, e.g. `ParquetPrunedRowGroups: 1` and `: 2` instead of `: 3`.
The totals are correct.

`--profile-events-delay-ms=-1` makes the client sum all packets and print
each counter once at the end, which is what the tests assert. The
references are unchanged.

Forcing a packet every 1 ms (`--interactive_delay=1000`) with the CI
amd_binary builds: the 05141 query splits the counter in 0/50 runs before
ClickHouse#125738, 17/50 at its merge commit, 32/50 at the base of this change and
0/50 with `-1`; 05141 fails 5/20 and 05361 20/20 without the change and
both pass 50/50 with it.

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

Copy link
Copy Markdown
Collaborator

The follow-up is #131140: the split-file Resize patch from the comment above, as a separate PR on top of #130740.

Measured on one hits.parquet (x86, release, 10 paired rounds, fix/base): Q39 0.56 at 16 threads, 0.53 at 32, 0.68 at 96; geomean over the 43 queries at 16 threads 0.973. The extra Resize costs about 2 ms per query, so short queries (Q1, Q7) are slightly slower at 32-96 threads. #125275 replaces the same condition with a sticky Resize that keeps most of the gain with smaller costs.

@snelheidai

Copy link
Copy Markdown

At 32 threads the extra millisecond goes into thread switching, and it grows with the number of streams that can take a source's chunks. With one Resize 32 → 32, any of the 32 streams can take them. Q1 then has 4.6 times as many context switches per query and uses 19% more CPU. Resize × 4 8 → 8 removes most of that. Pipe::resize makes such groups from min_outstreams_per_resize_after_split, but ReadFromFile does not pass the setting, and its default of 24 would not split 32 streams anyway. #125275's routing removes nearly all of it, because a stream's own consumer takes its chunks while it can.

Q1 and Q7, each run 200 times in one clickhouse local at 32 threads, per query:

Variant Q1, ms Q1 context switches Q7, ms Q7 context switches
master 8.02 490 10.00 568
#131140 (Resize 32 → 32) 9.08 2,270 11.05 2,045
groups of 8 (Resize × 4 8 → 8) 8.29 794 10.14 795
#125275 routing 8.07 549 10.05 629

Both variants keep the Q39 gain. Groups of 8 keep about the same gains as #131140, but a fresh process still pays most of the Q1 cost. #125275's routing keeps less of the Q37 and Q40 gains. One clickhouse local per query, ratio to master [95% CI]:

Query (0-based) master, ms #131140 groups of 8 #125275 routing
Q1 17 1.078 [1.056, 1.101] 1.060 [1.031, 1.090] 1.018 [0.997, 1.040]
Q2 26 1.015 [1.001, 1.030] 1.012 [0.998, 1.025] 1.023 [1.004, 1.042]
Q7 19 1.053 (+1 ms in every pair) 1.016 [0.998, 1.034] 1.016 [0.998, 1.034]
Q27 497.5 1.020 [1.004, 1.036] 1.016 [1.001, 1.031] 1.001 [0.984, 1.018]
Q36 92 0.794 [0.760, 0.828] 0.762 [0.739, 0.786] 0.783 [0.742, 0.826]
Q37 58.5 0.800 [0.765, 0.836] 0.818 [0.794, 0.842] 0.832 [0.814, 0.851]
Q39 180.5 0.585 [0.564, 0.606] 0.609 [0.583, 0.637] 0.618 [0.599, 0.637]
Q40 37 0.877 [0.865, 0.890] 0.872 [0.843, 0.901] 0.946 [0.914, 0.978]

The groups-of-8 variant, as measured (only the split-file case changes):

    if (parallelize_output && storage->parallelizeOutputAfterReading(ctx) && output_ports > 0 && output_ports < resize_to)
        pipe.resize(resize_to);
    else if (parallelize_output && storage->parallelizeOutputAfterReading(ctx) && split_file && output_ports > 1)
        pipe.resize(resize_to, /*strict=*/ false, /*min_outstreams_per_resize_after_split=*/ 8);
Setup

Release build of master 7a987ba (includes #130740; later master commits do not touch this path) on a 32 vCPU Xeon 8375C (r6i.8xlarge), max_threads = 32, one hits.parquet (226 row groups) in the page cache. One binary switches at run time between master, #131140's Resize, the grouped Resize, and #125275's a0ac001 Overflow/Concat/StickyResize with its resizeOutputAfterReading applied to the split file (#125275 is not rebased onto #130740).

Per-query table: a fresh clickhouse local --time per query, 11 rounds rotating the variants, first round dropped (n = 10), geometric means of the paired ratios with 95% t-intervals. Two earlier runs without the grouped variant agree (n = 20: Q1 1.081 for #131140 and 1.018 for #125275's routing, Q39 0.584 and 0.587). Context switches: perf stat totals of one process, divided by the number of queries.

Results are identical across variants for 8 checking queries at 1 to 64 threads. Q39 and Q40 differ only in the order of ties at their OFFSET, as they do between master runs. Not measured: 96 threads, aarch64.

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 13, 2026
One `Resize` over all streams lets any thread take a source's chunks, so
short queries switch threads several times as often. ClickBench on one
`hits.parquet`, x86 release, one binary switching the variants, paired
rounds, ratio to master (95% CI):

- Q1 at 32 threads, x200 in one process: one `Resize 32 -> 32` 1.64
  [1.56, 1.73] (3284 context switches per query, master 693), groups of
  8 1.12 [1.06, 1.18] (1269). Q7: 1.36 vs 1.04.
- Q1/Q7 at 32 threads, fresh process: 1.12/1.11 vs 1.01/1.01.
- Gains kept at 16/32/96 threads: Q39 0.60/0.56-0.60/0.62 (one Resize:
  0.60/0.57-0.60/0.61), Q36 0.83/0.80-0.84/0.83, Q40 0.86/0.85/0.85.
- Results identical for 8 checking queries at 16, 32 and 96 threads.

The group size is capped by `min_outstreams_per_resize_after_split`, so
0 still disables the split; its default (24) alone would not split the
`Resize` below 48 streams. Below 16 streams it stays one `Resize`.

Suggested and measured first by snelheidai:
ClickHouse#125738 (comment)

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

Copy link
Copy Markdown
Collaborator

Adopted the grouped Resize in #131140 (5970ba3): at 32 threads Q1 over 200 runs in one process is now 1.12x of master instead of 1.64x, and Q39 stays at 0.56-0.60.

@snelheidai

Copy link
Copy Markdown

Most of the remaining cost comes from every chunk of a group passing through one Resize. #125275's StickyResizeProcessor used on its own, in groups of 4 streams, keeps #131140's gains at about half the Q1 cost.

First, a correction: the warm table in my previous comment averaged --time values, which are rounded to milliseconds and hid most of the difference. With microsecond timestamps around the 200 runs (32 threads, 4 processes per variant), Q1 takes 8.03 ms on master, 8.59 ms (+7%) with groups of 8, 8.43 ms (+5%) with #125275's routing and 9.50 ms (+18%) with one Resize 32 → 32. That is the same direction as your 1.12x and 1.64x.

Each Resize 8 → 8 still takes every chunk of its 8 streams. Every port update locks that node's status_mutex in ExecutingGraph::updateNode, and prepare runs under it, so the 8 threads wait for each other. In 60 runs of Q1, 11,962 of the executor threads' 27,557 context switches were sleeps on such a mutex (master: 1 of 11,319). The Resize also gives each chunk to whichever of the 8 consumers has waited longest. Spinning on that mutex before sleeping removed most of the extra switches but only a fifth of the extra time, so the cost is mostly the shared node itself (threads waiting for it, and chunks moving between cores), not the sleeps. #125275's routing keeps chunks on their streams, but its 65 extra processors cost about 0.47 ms per query even when every row group is skipped (3.19 instead of 2.72 ms), which is most of its Q1 cost.

StickyResizeProcessor keeps each chunk with its own stream's consumer until that stream's source has finished; then the stream takes the chunks waiting at the other inputs of its group. One clickhouse local per query, ratio to master [95% CI]:

Query (0-based) master, ms groups of 8 (#131140) #125275 routing StickyResize, groups of 4
Q1 17.4 1.056 [1.025, 1.087] 1.044 [1.029, 1.059] 1.025 [1.008, 1.042]
Q2 26.7 1.034 [1.019, 1.049] 1.027 [1.012, 1.042] 1.008 [0.996, 1.019]
Q7 19.8 1.040 [1.024, 1.056] 1.028 [0.998, 1.058] 0.999 [0.975, 1.023]
Q27 502 1.012 [1.003, 1.021] 0.996 [0.990, 1.003] 0.995 [0.987, 1.003]
Q36 91.5 0.811 [0.765, 0.858] 0.791 [0.753, 0.831] 0.827 [0.784, 0.873]
Q37 60.0 0.802 [0.770, 0.835] 0.843 [0.808, 0.879] 0.793 [0.765, 0.823]
Q39 183 0.630 [0.614, 0.647] 0.594 [0.573, 0.616] 0.624 [0.607, 0.641]
Q40 38.2 0.861 [0.837, 0.886] 0.942 [0.907, 0.979] 0.853 [0.830, 0.877]

Q1 over 200 runs in one process takes 8.29 ms (+3%) with StickyResize in groups of 4, with 585 context switches per query (master 494, groups of 8 797). At 16 threads it gives Q1 1.022 [1.004, 1.041] and Q39 0.609 (groups of 8: 0.608). In groups of 8, StickyResize keeps a little more of Q39 (0.589) but costs Q1 1.038; in groups of 2 it loses part of Q39 (0.723); one StickyResize 32 → 32 is much slower (Q1 11.06 ms over 200 runs).

The measured split-file branch, keeping #131140's Resize when the stream counts differ; StickyResizeProcessor is #125275's (a0ac001), unchanged:

    else if (parallelize_output && storage->parallelizeOutputAfterReading(ctx) && split_file && output_ports > 1)
    {
        if (output_ports != resize_to)
            pipe.resize(resize_to, /*strict=*/ false, std::min<UInt64>(build_settings.min_outstreams_per_resize_after_split, 8));
        else
        {
            /// A stream keeps its own chunks until its source has finished, then takes the chunks waiting in its group of 4.
            const size_t groups = std::max<size_t>(1, output_ports / 4);
            pipe.transform([&](const OutputPortRawPtrs & ports)
            {
                const auto & header = pipe.getSharedHeader();
                Processors resizes;
                for (size_t g = 0, next = 0; g < groups; ++g)
                {
                    const size_t group_size = output_ports / groups + (g < output_ports % groups ? 1 : 0);
                    auto resize = std::make_shared<StickyResizeProcessor>(header, group_size);
                    for (auto & input : resize->getInputs())
                        connect(*ports[next++], input);
                    resizes.emplace_back(std::move(resize));
                }
                return resizes;
            });
        }
    }
Setup

Release build of master 7a987ba (includes #130740; later master commits do not touch these paths) on a 32 vCPU Xeon 8375C (r6i.8xlarge), one hits.parquet (226 row groups) in the page cache, max_threads = 32 unless stated. One binary switches at run time between master, #131140's groups of 8, #125275's a0ac001 routing (applied to the split file) and StickyResize groups.

Per-query table: a fresh clickhouse local per query, timed with now64(6) right before and after the query, 11 rounds rotating the variants, first round dropped (n = 10; n = 7 at 16 threads and for groups of 2), geometric means of the paired ratios with 95% t-intervals. Warm figures: now64(6) around 200 runs in one process, mean of 4 processes per variant. Fixed cost: SELECT count() FROM hits WHERE CounterID = 999999999, which skips every row group (master 2.72 ms, groups of 8 2.82 ms, StickyResize groups of 4 2.85 ms, #125275's routing 3.19 ms). Context switches: perf record -e sched:sched_switch call stacks of one process running Q1 60 times; with StickyResize in groups of 4, 2,977 of 16,447 switches were sleeps on a node mutex.

Results are identical to master for 9 checking queries (including LIMIT and ORDER BY ... LIMIT) at 2 to 64 threads and in the timed runs; Q39 and Q40 differ only in the order of ties at their OFFSET, as between master runs. Not measured: 96 threads, aarch64.

PedroTadim pushed a commit to hsusul/ClickHouse that referenced this pull request Nov 13, 2026
… threads

`ReadFromFile::initializePipeline` added a `Resize` only when there were
fewer sources than threads. A split single file has as many sources as
threads, so the rows read from a bucket stayed on the chain of transforms
of the source that read it. When the rows passing a filter sit in a few
row groups (e.g. `CounterID = 62` in ClickBench), a few threads did all
the aggregation while the others idled.

Analysis and patch by @ snelheidai in
ClickHouse#125738 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-parquet-reader-v3 Issues related to the native Parquet reader. 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.

4 participants