Repository navigation
Read a single local Parquet file by several sources in parallel - #125738
Conversation
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]>
|
Workflow [PR], commit [2abee4d] Summary: ✅
AI ReviewSummaryThis 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 Final VerdictStatus: ✅ Approve. |
|
🕵 @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 ( |
|
Fix: #125024 (mine, open, awaiting review). It is the same bug as on #123788 and the other PRs you listed. The fuzzer turned the Checked with |
`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]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes26 object files changed (+70.76 KiB total), 0 added.
719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Slowest function optimization changes (ThinLTO)Median per-function time ratio to the master baseline:
Compile time of recompiled translation units625 translation units recompiled, 4730 s compile time in total, 625 of them have a recent master baseline. |
# Conflicts: # src/Storages/StorageFile.cpp
|
🕵 The only red check on |
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]>
|
The
In a fresh 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 |
…-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]>
|
🕵 Merged The perf failures on
@snelheidai, thanks for measuring the |
|
🕵 @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 ( |
|
Acknowledged. I'm investigating 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 |
|
The fix is #127172.
The per-row loop of |
|
Correction to my comment above: #127172 is not a fix, so I'm closing it. Its own arm run made two-key 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 |
…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]>
|
🕵 Pushed d66508e: shared parsing of column chunks between the bucket readers of a split file (review item from The only red on the previous commit was in the amd Performance Comparison: @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 ( |
|
On x86 at 16 threads, this PR makes the CPU-bound full scans of the single
Official master builds 1dc3262 (before this PR) and 804ee9b (after) on an r6i.8xlarge pinned to 16 cores, a fresh 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 bucketBy 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. |
|
@snelheidai, thanks, this is a good idea! @groeneai, let's do this follow-up. |
|
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 |
|
@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.
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 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 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]>
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]>
|
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 x86, |
|
The Q39 slowdown of a split file (my comment above) comes from a missing
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; #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 a62d3fddiff --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 |
|
@groeneai, the first PR is already in the merge queue, so you can send a follow-up. |
|
Acknowledged. I will send the split-file |
`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]>
|
The follow-up is #131140: the split-file Measured on one |
|
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 Q1 and Q7, each run 200 times in one
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
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);SetupRelease build of master 7a987ba (includes #130740; later master commits do not touch this path) on a 32 vCPU Xeon 8375C (r6i.8xlarge), Per-query table: a fresh 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 |
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]>
|
Most of the remaining cost comes from every chunk of a group passing through one First, a correction: the warm table in my previous comment averaged Each
Q1 over 200 runs in one process takes 8.29 ms (+3%) with The measured split-file branch, keeping #131140's 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;
});
}
}SetupRelease build of master 7a987ba (includes #130740; later master commits do not touch these paths) on a 32 vCPU Xeon 8375C (r6i.8xlarge), one Per-query table: a fresh Results are identical to master for 9 checking queries (including |
… 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]>
Related: #104431
A single large Parquet file read through
fileor theFileengine was read by one source, and the pipeline started withResize 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-fileclickhouse-parquetis 2–4x slower thanclickhouse-parquet-partitionedon the heaviest queries.This is a redesign of #104431 (which is not needed with this PR):
ReadFromFilesplits a single local Parquet file into up tomax_threadsbuckets, 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.CounterID = 62in ClickBench) are spread across all readers.ParquetMetadataCache) and shared by all readers; the cache now hands out a shared pointer instead of a deep copy on every read.FILE_CHANGED_DURING_READotherwise. Count-only reads, min/max from statistics, TopN reads, lazy materialization,input_format_parquet_preserve_orderandparallelize_output_from_storages = 0keep the old path.Things that made many readers of one file slow, fixed along the way:
ReadManagerlooked up their logger under a global mutex;ThreadGroupPtrto check whether it is attached, making all threads of a query contend on its reference counter.ClickBench
hits.parquetviaclickhouse local(as in ClickBench), 96-core aarch64, best of 5, interleaved runs; geomean over 43 queries:Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Reading a single large local Parquet file through the
filetable function or theFiletable 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 singlehits.parquetfile 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
26.11.1.1852-master(included in26.11and later)