Skip to content

Parallelize reads from a single Parquet file in StorageFile - #104251

Merged
alexey-milovidov merged 7 commits into
ClickHouse:masterfrom
alexey-milovidov:parquet-single-file-parallelism
May 7, 2026
Merged

alexey-milovidov merged 7 commits into
ClickHouse:masterfrom
alexey-milovidov:parquet-single-file-parallelism

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented May 6, 2026 •

Copy link
Copy Markdown
Member

On ClickBench, single-file Parquet runs are 3–9× slower than the 100-file partitioned runs on the same data (e.g. on c7a.metal-48xl, Q23 is 8.90s vs 0.99s, Q22 1.82s vs 0.41s, Q27 1.21s vs 0.45s). The cause is in StorageFile: when reading a single splittable file it creates exactly one ParquetV3BlockInputFormat source, so the pipeline becomes File 0 → 1 followed by Resize 1 → 96. That fan-out is a serialization point — every chunk has to leave the single source through one read before any of the 96 aggregators can touch it, so most cores sit idle.

The bucket-splitting machinery (ParquetBucketSplitter, setBucketsToRead, FileBucketInfo) already existed for cluster mode but was never wired into StorageFile. This PR wires it in:

  • New IBucketSplitter::splitToBucketsByCount returning roughly N contiguous row-group ranges; Parquet implements it.
  • New FormatFactory::checkFormatHasSplitter so callers can probe without throwing.
  • StorageFile::ReadFromFile::initializePipeline, when reading exactly one local splittable file, asks the splitter for max_num_streams buckets and creates one StorageFileSource per bucket. Each source carries fixed_file_path + file_bucket_info and skips the shared FilesIterator.
  • ParquetV3BlockInputFormat::read honours buckets_to_read in the trivial-count path so each bucket only reports its own row count.
  • The count cache (keyed by file path) is bypassed for bucketed reads — otherwise every bucket would report the file's total and counts would be multiplied by the number of buckets.

Pipeline becomes File × N 0 → 1 straight into the aggregators, matching the partitioned variant.

Results

96-vCPU box, hits.parquet (14 GiB, 226 row groups):

Single (master) Single (this PR) Partitioned
Q21 0.40–0.66s 0.44s 0.34s
Q22 0.93–1.36s 0.48s 0.41s
Q23 1.33–1.45s 0.55s 0.42s
Q26 0.50s 0.35s 0.19s
Q27 1.6s 0.54s 0.45s

CPU utilisation on Q23 jumped from ~6× to ~18× of 96 cores. Aggregate results (count, sum(UserID), sum(length(URL)), Q21, Q23) match the partitioned variant exactly. The remaining ~1.3× gap to partitioned is per-source initialization overhead: each bucket source still reads the 14 GB file's footer separately. Sharing parsed metadata for local files is the obvious next step but a much bigger change.

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 via file() / File engine is now parallelised across multiple sources, each handling a subset of row groups. This eliminates a Resize 1 → N bottleneck in the pipeline and brings single-file ClickBench performance close to the partitioned variant — Q23 goes from ~1.4s to ~0.55s, Q22 from ~0.9s to ~0.48s, Q27 from ~1.6s to ~0.54s on 96 vCPUs.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.5.1.395

When `file('hits.parquet')` reads a splittable format from a local path,
`StorageFile` used to create a single `ParquetV3BlockInputFormat` source.
The pipeline became `File 0 → 1` followed by `Resize 1 → 96`, and that
fan-out was a serialization point: every chunk from the single source
had to flow through one read() before the 96 aggregators could touch it.
On ClickBench (c7a.metal-48xl, hits.parquet), this made the heavy
text-column queries 3–9× slower than the 100-file partitioned variant
even though the data is identical:

* Q21 (`COUNT WHERE URL LIKE '%google%'`): 3.2× slower
* Q22 (`GROUP BY SearchPhrase`): 4.4× slower
* Q23 (LIKE on URL & Title + COUNT(DISTINCT UserID)): 9.0× slower
* Q27 (`AVG(length(URL)) GROUP BY CounterID`): 2.7× slower

The bucket-splitting machinery (`ParquetBucketSplitter`,
`setBucketsToRead`, `FileBucketInfo`) already existed for cluster mode
but was never wired into `StorageFile`. This commit wires it in:

* `IBucketSplitter` gets `splitToBucketsByCount(N, ...)` and Parquet
  implements it as N contiguous row-group ranges.
* `FormatFactory::checkFormatHasSplitter` lets callers probe for the
  capability without throwing.
* `StorageFile::ReadFromFile::initializePipeline` calls the splitter for
  a single splittable local file and creates one source per bucket.
  Each source carries `fixed_file_path` + `file_bucket_info` and skips
  the shared `FilesIterator`.
* `ParquetV3BlockInputFormat::read` honours `buckets_to_read` in the
  trivial-count path so each bucket reports only its own row count.
* The count cache (keyed by file path) is bypassed for bucketed reads,
  otherwise every bucket would report the file total.

Result on a 96-vCPU box, hits.parquet (14 GiB, 226 row groups):

|     | Single (master) | Single (this PR) | Partitioned |
|-----|-----------------|------------------|-------------|
| Q21 | 0.40–0.66s      | 0.44s            | 0.34s       |
| Q22 | 0.93–1.36s      | 0.48s            | 0.41s       |
| Q23 | 1.33–1.45s      | 0.55s            | 0.42s       |
| Q27 | 1.6s            | 0.54s            | 0.45s       |

CPU utilisation on Q23 climbed from ~6× to ~18× of 96 cores. Aggregate
results (`count`, `sum(UserID)`, `sum(length(URL))`, Q21, Q23) match the
partitioned variant exactly.

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

clickhouse-gh Bot commented May 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6e3d4c2]

Summary: ✅


AI Review

Summary

This PR wires single-file Parquet bucket splitting into StorageFile so one large local Parquet file can feed multiple parallel sources instead of a single File 0 → 1 bottleneck, and it correctly propagates bucket assignments into both normal reads and trivial-count mode. I did not find additional high-confidence correctness, safety, or performance issues beyond the already raised bot inline comments.

ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ✅
Compilation time ✅
No large/binary files ✅
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label May 6, 2026
Comment thread src/Storages/StorageFile.cpp Resolved
The Parquet metadata cache (default 512 MiB) was registered in Context
and wired into the object-storage code path, but `StorageFile` was
calling `getInput` (no `object_with_metadata`) — so for `file('foo.parquet')`
the cache was never consulted and every source parsed the footer fresh.
With single-file bucket splitting that meant 96 separate footer parses
per query against `hits.parquet`.

Build a synthetic `RelativePathWithMetadata` with the file's path and
`mtime|size` as the etag, and call `getInputWithMetadata`. The existing
Parquet metadata-aware creator picks up `context->getParquetMetadataCache()`
and the cache is keyed by `(path, mtime+size)`, so an in-place rewrite
invalidates the entry.

Verified with `--send_logs_level=trace`: each query against `hits.parquet`
on a 96-core box now logs 1 cache miss + 95 cache hits (was 96 misses).
On the ClickBench heavy-text queries the wall-time delta is in the
noise on this hardware (cache savings ≈ 1.9 s of CPU work, parallelised
across 96 cores ≈ 20 ms), but the cache is meaningful for smaller
machines and for long-running clickhouse-server where the entry stays
hot across queries.

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

Copy link
Copy Markdown
Member Author

Added a follow-up commit (c019cdb) that wires the existing Parquet metadata cache (parquet_metadata_cache_size, 512 MiB default) into StorageFile for local files.

Until now the cache was only reachable from object storage, because the local-file creator passed nullptr and the cache lookup in ParquetV3BlockInputFormat::getFileMetadata requires object_with_metadata with an etag. With single-file bucket splitting that meant every one of the 96 sources parsed the footer of hits.parquet from scratch.

StorageFile now builds a synthetic RelativePathWithMetadata for local files, using mtime|size as the etag (so an in-place overwrite invalidates the entry), and calls getInputWithMetadata. Verified with --send_logs_level=trace: per Q23 we see 1 cache miss + 95 cache hits (was 96 misses).

Wall-time impact on this 96-core box is in the noise (~1.9 s of CPU work eliminated, but parallelised across 96 cores ≈ 20 ms wall):

Cache off Cache on
Q23 (cold) 0.576 s 0.567 s
Q23 (hot, avg of 7) 0.407 s 0.408 s

The savings are still real and will be visible on smaller machines, in batches of small queries, and for long-running clickhouse-server where the cache entry stays hot across queries on the same file.

alexey-milovidov and others added 3 commits May 6, 2026 18:33
Single-file bucket splitting in `StorageFile` produces multiple sources
that read disjoint row group ranges in parallel, so the rows from the
two sources interleave at the next pipeline step. For Parquet, when
`input_format_parquet_preserve_order=1` is set the user explicitly asks
the read to keep the file's original row order, so splitting the file
into buckets is wrong: it loses the order across bucket boundaries.

`FormatFactory::checkParallelizeOutputAfterReading` already returns
`false` for Parquet under `input_format_parquet_preserve_order=1` (it
guards the existing post-read `Resize`). Reuse it as the gate for
bucket splitting too — same condition, same intent.

Also update `02725_parquet_preserve_order.reference` for the second
`EXPLAIN PIPELINE` (`preserve_order=0`, `parallelize_output_from_storages=1`,
`max_threads=2`): the pipeline is now `File × 2 0 → 1` rather than
`Resize 1 → 2 / File 0 → 1`, because the bucket splitter creates one
source per stream up front and the post-read `Resize` is no longer
needed.

CI report:
ClickHouse#104251

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The single-file split path opened the file directly from
`storage->paths.front()` and gave each per-bucket source a
`fixed_file_path`, bypassing `FilesIterator` entirely. That iterator is
where `_path`/`_file` pruning is applied (`createPathAndFileFilterDAG`
+ `filterByPathOrFile` in its constructor), so a query whose virtual-
column predicate excludes the file would still read it under this code
path, and `need_only_count` queries could even report a non-zero count
for a pruned file.

Switch the split path to read the file list from
`files_iterator->getFiles()`, which is the post-pruning view. If the
predicate excludes the only path the iterator returns an empty list,
the split path is skipped, no source is created, and the query reads
nothing — same as before this PR.

Address review:
ClickHouse#104251 (comment)...

Verified locally: with `_file = 'nonexistent.parquet'` the query now
returns 0 rows; with no predicate or a matching predicate it returns
the correct count.

CI report:
ClickHouse#104251

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Comment thread src/Storages/StorageFile.cpp Resolved
alexey-milovidov and others added 2 commits May 6, 2026 19:01
The split branch was guarded by `num_streams < max_num_streams`, which
is computed from `files_to_read = storage->paths.size()` (the
*unfiltered* path list). When the table is created with many paths but
a `_path` / `_file` predicate prunes them down to a single file at
runtime, `num_streams` ends up equal to `max_num_streams` and the
guard is false — so the optimization is skipped exactly in the case it
was supposed to help.

Drop that derived guard in favour of `max_num_streams > 1`. The split
is then attempted whenever the post-pruning iterator has exactly one
file and we have more than one stream to feed it; if the bucket
splitter fails or returns fewer than two buckets we still fall through
to the unsplit path.

Address review:
ClickHouse#104251 (comment)...

CI report:
ClickHouse#104251

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
When a single Parquet file is split into multiple buckets by `StorageFile`,
each bucket's `ReadManager::init` reported `ParquetReadRowGroups` and
`ParquetPrunedRowGroups` based on the entire file's metadata, so the events
were multiplied by the number of buckets. With 10 row groups split into 10
buckets, the test `03408_parquet_row_group_profile_events` produced `30 70`
instead of the expected `3 7`; with 2 buckets it produced `6 14`.

Count only the row groups that belong to this bucket: read = number of
entries in `reader.row_groups` with `need_to_process = true`; pruned =
`row_groups_to_read->size() - read`. The non-bucket path is unchanged.

CI report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=104251&sha=0eaa873dca36a7d18b78422ec0cdf572b45a3996&name_0=PR

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

clickhouse-gh Bot commented May 7, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 91.10% 91.10% +0.00%
Branches 76.60% 76.60% +0.00%

Changed lines: 99.17% (119/120) | lost baseline coverage: 1 line(s) · Uncovered code

Full report · Diff report

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I've reviewed the code and found everything alright.
The only question is why it didn't work this way in the first place.

@alexey-milovidov alexey-milovidov self-assigned this May 7, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue May 7, 2026
Merged via the queue into ClickHouse:master with commit 47b6163 May 7, 2026
165 checks passed
@alexey-milovidov
alexey-milovidov deleted the parquet-single-file-parallelism branch May 7, 2026 13:34
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label May 7, 2026
pull Bot pushed a commit to AnotherGenZ/ClickHouse that referenced this pull request May 10, 2026
…ring

Two paths produced a `LOGICAL_ERROR` after wiring `getInputWithMetadata`
into `StorageFile`:

1. `INSERT ... FROM INFILE` runs `StorageFile` inside the *client*
   `Context`. The client never calls `setParquetMetadataCache`, so the
   metadata-aware Parquet creator's
   `context->getParquetMetadataCache()` threw "Parquet metadata cache
   was not created yet" — surfacing as failures of
   `02845_parquet_odd_decimals`, `02561_null_as_default_more_formats`,
   etc. on the `arm_binary` configuration.

2. Reads where no per-file size + mtime were available (archive entries,
   `use_table_fd`, or any path where the stat info hadn't been
   populated) were still routed through `getInputWithMetadata` with an
   empty optional, tripping its
   `chassert(object_with_metadata.has_value())`.

Fixes:

* New `Context::tryGetParquetMetadataCache` returns `nullptr` instead
  of throwing when the cache hasn't been initialised. The
  metadata-aware Parquet input creator uses it; `ParquetV3BlockInputFormat`
  already short-circuits when `metadata_cache` is null, so the format
  still works correctly without memoisation.
* In `StorageFileSource::generate`, dispatch between
  `getInputWithMetadata` (when we built an `object_with_metadata`) and
  `getInput` (otherwise — archives, fd, missing stat info). Before, we
  always called the metadata-aware overload, which is a contract
  violation when the optional is empty.

CI report:
ClickHouse#104251

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
alexey-milovidov added a commit that referenced this pull request May 13, 2026
Three gates on the bucketed single-file read path in `StorageFile`,
addressing the `clickbench_parquet_short` regression observed on ARM in
the CI of #104431 (#104431)
and an open review comment.

1. `parallelize_output_from_storages = 0` now disables the split. The
   per-bucket sources are exactly the kind of read parallelism the
   setting's contract is about, but the existing check fired only after
   the sources had been created. Review feedback from
   #104431 (comment).

2. `need_only_count` queries skip the split. They consult only the
   file's metadata, so splitting them across N sources just multiplies
   the metadata-parse cost N-fold without any read-side benefit. This
   was the largest single contributor to the `Q1` (`SELECT COUNT(*)`)
   regression in `clickbench_parquet_short`.

3. The Parquet splitter (`ParquetBucketSplitter::splitToBucketsByCount`)
   now requires each chunk to cover at least 8 row groups. For a file
   with a small number of row groups, parallelising across all available
   threads multiplies per-bucket metadata-parse and prefetcher-setup
   overhead without giving each source enough work to amortise it. Large
   files (many row groups) still get full parallelism.

Updates `02725_parquet_preserve_order.reference`: the 2-row-group test
file falls below the new row-group floor so the pipeline goes back to a
single `File` source followed by `Resize 1 → 2`, matching pre-#104251
behaviour.

CI report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=104431&sha=78ecefef098eedd55ab0a0ce350082364c8c23be&name_0=PR&name_1=Performance%20Comparison%20%28arm_release%2C%20master_head%2C%201%2F6%29
il9ue pushed a commit to il9ue/ClickHouse that referenced this pull request May 20, 2026
…solution in next commit)

---
Original cherry-pick message follows:

Merge pull request ClickHouse#104251 from alexey-milovidov/parquet-single-file-parallelism

Parallelize reads from a single Parquet file in StorageFile

# Conflicts:
#	src/Processors/Formats/Impl/ParquetV3BlockInputFormat.cpp
#	src/Processors/Formats/Impl/ParquetV3BlockInputFormat.h
il9ue pushed a commit to il9ue/ClickHouse that referenced this pull request May 20, 2026
subkanthi pushed a commit to Altinity/ClickHouse that referenced this pull request May 26, 2026
…solution in next commit)

---
Original cherry-pick message follows:

Merge pull request ClickHouse#104251 from alexey-milovidov/parquet-single-file-parallelism

Parallelize reads from a single Parquet file in StorageFile

# Conflicts:
#	src/Processors/Formats/Impl/ParquetV3BlockInputFormat.cpp
#	src/Processors/Formats/Impl/ParquetV3BlockInputFormat.h
subkanthi pushed a commit to Altinity/ClickHouse that referenced this pull request May 26, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Three gates on the bucketed single-file read path in `StorageFile`,
addressing the `clickbench_parquet_short` regression observed on ARM in
the CI of ClickHouse#104431 (ClickHouse#104431)
and an open review comment.

1. `parallelize_output_from_storages = 0` now disables the split. The
   per-bucket sources are exactly the kind of read parallelism the
   setting's contract is about, but the existing check fired only after
   the sources had been created. Review feedback from
   ClickHouse#104431 (comment).

2. `need_only_count` queries skip the split. They consult only the
   file's metadata, so splitting them across N sources just multiplies
   the metadata-parse cost N-fold without any read-side benefit. This
   was the largest single contributor to the `Q1` (`SELECT COUNT(*)`)
   regression in `clickbench_parquet_short`.

3. The Parquet splitter (`ParquetBucketSplitter::splitToBucketsByCount`)
   now requires each chunk to cover at least 8 row groups. For a file
   with a small number of row groups, parallelising across all available
   threads multiplies per-bucket metadata-parse and prefetcher-setup
   overhead without giving each source enough work to amortise it. Large
   files (many row groups) still get full parallelism.

Updates `02725_parquet_preserve_order.reference`: the 2-row-group test
file falls below the new row-group floor so the pipeline goes back to a
single `File` source followed by `Resize 1 → 2`, matching pre-ClickHouse#104251
behaviour.

CI report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=104431&sha=78ecefef098eedd55ab0a0ce350082364c8c23be&name_0=PR&name_1=Performance%20Comparison%20%28arm_release%2C%20master_head%2C%201%2F6%29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants