Skip to content

Balance the buckets of a single Parquet file read by several sources in parallel - #130740

Merged
alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
groeneai:parquet-split-file-bucket-queue
Nov 11, 2026
Merged

alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
groeneai:parquet-split-file-bucket-queue

Conversation

@groeneai

@groeneai groeneai commented Nov 11, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #125738

Changelog category (leave one):

  • Performance Improvement

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

Faster parallel reading of a single local Parquet file whose row groups differ in size: the readers take the next part of the file from a shared queue, largest first, instead of each reading a fixed round-robin share of the row groups. Threads that finish reading memory-mapped files at the same time (e.g. in clickhouse-local, which reads files with mmap by default) no longer wait for each other to release the mappings.

Description

Follow-up to #125738, as asked in #125738 (comment). There, row group i of the file goes to bucket i % N, one bucket per source, so with row groups of different sizes the heaviest bucket is the wall time (hits.parquet: 1.19x the mean rows at 16 streams, 1.6x at 64), and CPU-bound scans got 2-6% slower (measurement).

  • The file is split into up to 4 * max_threads round-robin buckets, ordered largest first, and the sources take the next bucket from a shared counter. A static largest-first assignment was measured to slow down the URL queries, because rows and bytes per row group are anti-correlated. Round-robin buckets keep the row groups that survive min/max pruning spread.
  • A source keeps the file open across its buckets; the file version is still checked for every bucket.
  • MMappedFileDescriptor::finish calls madvise(MADV_DONTNEED) before munmap. The balanced sources drop their whole-file mappings at the same time, and concurrent munmap calls tear down the page tables one after another (16 threads: 36-59 ms; with MADV_DONTNEED first: 4-6 ms).

Validation: clickhouse local on x86, hits.parquet, max_threads = max_parsing_threads = T, ClickBench queries (0-based), paired geomean of PR / master. T=16 (10 rounds): 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. T=64: Q20 0.684, Q21 0.695, Q22 0.669. Q10 is 1.13 at T=16 because one thread's aggregation table crosses adaptive_aggregator_freeze_threshold_bytes (with it set to 0: 0.953). Q39 (CounterID = 62) is 1.07-1.09 at T=96. Results are identical (mmap and pread). The new performance test: 0.75 / 0.69 at max_threads = 8.


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

Version info

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

groeneai and others added 5 commits November 11, 2026 03:51
A single local Parquet file is split into up to 4 * max_num_streams round-robin
buckets, returned largest first (by the larger of the row share and the
uncompressed-byte share), and the sources take the next bucket from an atomic
counter in SplitFile instead of reading one fixed bucket each, like they take
the next file of a multi-file read.

WIP for the follow-up to ClickHouse#125738 (row groups of different sizes leave the
source with the heaviest static bucket finishing last). Benchmarks show the
4x factor costs short scans at high thread counts (serialized per-bucket
startup latency), so the design goes back to planning.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A source that takes several buckets of a split Parquet file re-opened the file
for every bucket. In clickhouse-local, where storage_file_read_method = mmap by
default, that is an mmap + munmap of the whole file per bucket, and these
serialize on the process mmap_lock with each other and with the page faults of
all query threads: with 4 buckets per stream, short scans of hits.parquet got
slower with the thread count (Q1 1.28x at 96 threads), while with pread the
same build was neutral or faster.

The source now creates its read buffer for the first bucket it takes and keeps
it until the queue is empty. The exists / stat / version-token checks still run
for every bucket, so a file removed or modified during the read still fails
with FILE_CHANGED_DURING_READ. The Parquet reader of a bucket reads the buffer
only by offset (readBigAt, or seek before every read), and the formats of the
previous bucket are destroyed before the next one is created.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The row groups alternate 1.5M and 0.5M rows, so with round-robin buckets every
bucket of an even index gets only the large row groups. Measured with
clickhouse-local (fresh process, 3 runs): the queue makes both queries
0.75x / 0.76x at max_threads = 8 and 0.66x / 0.70x at max_threads = 12.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Tearing down the page tables of a mapping costs time per page touched, and the
munmap calls of one process run one after another (each takes the process
memory map lock exclusively), while MADV_DONTNEED of different mappings runs in
parallel. With the sources of a split Parquet file balanced by the queue, all
of them finish at the same time in clickhouse-local (storage_file_read_method =
mmap by default), and their teardowns of the whole-file mapping queue up at the
end of the query.

Microbenchmark on the page-cached hits.parquet (N threads copy disjoint 1 MiB
chunks, then all drop their mapping at once), ms:

| threads, touched | own munmap each | MADV_DONTNEED, then munmap |
|---|---|---|
| 16, 1.7 GB | 36-59 | 4-6 |
| 16, 6 GB | 180-190 | 13 |
| 64, 1.7 GB | 63-67 | 11-15 |
| 96, 1.7 GB | 63-74 | 17-18 |

ClickBench Q21 on hits.parquet, 16 threads, bpftrace of the whole-file
mappings: the query waited 25-50 ms after the last source stopped reading
(sum of munmap durations 207-401 ms); with this change 5-6 ms (17 madvise
calls in parallel, munmap < 1 ms in total).

The mappings are PROT_READ and MAP_PRIVATE and are never written, so they have
no private pages; the result of madvise is ignored, munmap still does the
teardown if it fails.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop three comments that restate the code below them, shorten one to a line, and keep the existing IBucketSplitter doc's wrapping.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 2 findings) plus my own review.

# Sev Finding Verdict Evidence / action
1 ⚠️ EngineFileLikeReadFiles counts a split file once per bucket DISAGREE Object storage counts one per reader of a bucket too (StorageObjectStorageSource::createReader), and master already counts one per bucket here; counting once only for File would make the two paths differ.
2 ⚠️ The perf test cannot tell the queue from a static fine-grained split DISAGREE Perf CI compares with master, where the test is 0.75 / 0.69 at max_threads 8 and 0.63 / 0.62 at 12.
3 ⚠️ The claim order does not know which buckets survive min/max pruning, so CounterID = 62 queries can be slower at high thread counts noted, not blocking Measured: Q36-Q42 1.00-1.04 at 16 threads, Q39 1.07-1.09 at 96 (stated in the description); the same with one bucket per stream, so not the 4x factor.
4 💡 Changelog entry named the mechanism instead of the effect AGREE, fixed Entry reworded.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-9:20261111-095100

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? The bucket imbalance is a property of the footer (hits.parquet: heaviest round-robin bucket 1.185x the mean rows at 16 streams); its cost is measured by paired, alternating master/PR runs. The munmap tail is shown per run by a bpftrace timeline of the whole-file mappings.
b Root cause explained? Static round-robin buckets of unequal row groups make the heaviest bucket the wall time. A shared queue fixes that but needs more buckets than streams; re-opening the file per bucket mapped it again each time, and with one mapping per source all mappings were dropped together at the end, where concurrent munmap calls serialize.
c Fix matches root cause? Yes: the queue (largest first) balances the sources, a source keeps the file open across its buckets, and MADV_DONTNEED before munmap drops the pages in parallel. No setting, no tuned threshold.
d Test intent preserved / new tests added? New performance test parquet_single_file_unequal_row_groups; the tests of #125738 are unchanged and pass.
e Both directions demonstrated? Master vs PR on ClickBench at T = 16/32/64/96 (e.g. T=16 Q21 0.879, T=64 Q22 0.669) and on the perf test (0.75 / 0.69); the munmap tail after the last reader 25-50 ms without the madvise, 5-6 ms with it.
f Fix is general across code paths? The madvise is in MMappedFileDescriptor, so every drop of a mapping gets it: multi-file File reads (16-file copy: no query slower, Q22 0.935) and MergeTree min_bytes_to_use_mmap_io reads. Only the native Parquet reader splits a single file.
g Fix generalizes across inputs (params/datatypes/wrappers)? Identical results with mmap and pread at T = 16 and 96 (read and io_uring too, which make no mapping), over all 105 columns with four filters (full scan, min/max-pruned CounterID = 62, LIKE, PREWHERE).
h Backward compatible? (maintainer-approved exception only) Yes: no setting, format or protocol change.
i Invariants and contracts preserved? The query condition cache entry is still written once after all buckets are read; FILE_CHANGED_DURING_READ is still checked for every bucket; the mappings are PROT_READ and MAP_PRIVATE, so MADV_DONTNEED drops no private data, and a failed madvise leaves the teardown to munmap as before.

Session id: cron:clickhouse-impl-slot-40:20261111-085000

@clickhouse-gh

clickhouse-gh Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ad6aaf2]

Summary: ✅


AI Review

Summary

Reviewed #130740 at ad6aaf26040fde87eafd3942db79598ea221bd0d. The change balances single-file Parquet reads through a shared bucket queue, retains each source's read buffer between buckets, and uses MADV_DONTNEED before unmapping files. No actionable findings.

Missing context / blind spots
  • ⚠️ No local build or tests were run, and current-head CI was still running at review time. Runtime evidence comes from the author's reported regression runs and before/after benchmarks; completed current-head functional CI would close this validation gap.
Final Verdict

✅ Approve.

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements can be tested Allows running workflows for external contributors comp-parquet-reader-v3 Issues related to the native Parquet reader. labels Nov 11, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 11, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing ad6aaf260 with master f35452c83 (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.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.61, programs/clickhouse-keeper ×0.62 (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&) 5.8 s 13.2 s +9.7 s (+274%)
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.5 s 7.5 s +5.4 s (+256%)
Compile time of recompiled translation units

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

Job report

@snelheidai

Copy link
Copy Markdown

On aarch64 (4-core Graviton3, 4 threads), this PR makes several full scans of the single hits.parquet 2–3% faster and Q23 2% slower; Q10 and Q39 are unchanged:

Query (0-based) master, ms PR, ms PR/master [95% CI]
Q18 1874.5 1827 0.966 [0.946, 0.986]
Q13 757 739 0.975 [0.969, 0.981]
Q21 1589.5 1556 0.975 [0.965, 0.985]
Q8 684 671.5 0.981 [0.974, 0.988]
Q23 556.5 564.5 1.020 [1.002, 1.039]
Q10 179.5 174.5 0.983 [0.964, 1.002]
Q39 190 188.5 0.993 [0.968, 1.017]
All 43, geomean 0.989 [0.984, 0.994]

Of the other queries over 100 ms, only Q25 is slower (1.007 [1.001, 1.014]). Queries under 100 ms move by 1–5 ms in both directions: Q1 1.067, Q7 1.080 and Q36 1.050 are slower; Q19 0.921 and Q42 0.951 are faster (all significant). The CounterID = 62 queries (Q36–Q42), which skip most row groups, use 2–6% more user+system CPU; on the long scans CPU is unchanged (0.99–1.01x). With 4 threads the round-robin split of master is already nearly balanced (the largest of 4 buckets has 1.05x the mean rows, against 1.19x of 16 at 16 threads), which leaves less to gain. Over the 100-file layout, where only the MADV_DONTNEED change applies, no query is slower (all 43: 0.999 [0.991, 1.008]).

Setup: Release builds with identical flags (clang 21, no LTO) of ad6aaf2 and its merge base c3124c7, 4-core Graviton3 with 30 GiB and Linux 7.0, a fresh clickhouse local --tmp --time per query, max_threads = max_parsing_threads = 4, warm page cache, 10 alternating rounds after a warm-up (6 for the 100 files); ratios are geometric means of the paired --time query times (whole-process wall time gives 0.994 [0.989, 1.000] for all 43). Results match: the 7 queries whose LIMIT output differs differ only among ties, and checksums of their full results without LIMIT are equal.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM

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

Labels

can be tested Allows running workflows for external contributors comp-parquet-reader-v3 Issues related to the native Parquet reader. 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