Skip to content

Read Parquet files in clickhouse-local without copying them out of the memory mapping - #124552

Open
groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:parquet-local-mmap-zero-copy
Open

groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:parquet-local-mmap-zero-copy

Conversation

@groeneai

@groeneai groeneai commented Oct 8, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #124517
Related: #100300

Changelog category (leave one):

  • Performance Improvement

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

clickhouse-local decodes Parquet files directly from the memory-mapped file instead of copying every column chunk first, and asks the kernel in advance to read the byte ranges it is going to decode. Queries on Parquet files that are not in the page cache are up to 2.7 times faster and read much less from disk.

Description

clickhouse-local reads files through mmap, and the Parquet Prefetcher copied every byte range out of the mapping. Cold, each page fault of the copy reads the whole read-ahead window around the page: ClickBench q2 on 100 files read 1.96 GB from disk (6 MiB read-ahead) for 9 MB of ranges.

MMapReadBufferFromFileDescriptor now implements readBigAtRetainCells, returning a region inside the mapping like the userspace page cache (#100300), and the Prefetcher advises each range with POSIX_FADV_WILLNEED before decoding it. One hint makes Linux read at most max(read_ahead_kb, max_sectors_kb) of a range (128 KiB on EBS), so ranges decoded in full and copies are advised in 128 KiB pieces, as proposed in #124517. Data pages that later PREWHERE steps, column index pruning or lazy materialization may decode only in part keep one hint: advising them in full made q24 1.34x slower.

Decoders read up to PADDING_FOR_SIMD bytes outside a range, so producers now report the readable bytes around each region, and a region without that padding (near a file end, or at a page cache cell edge, unchecked since #100300) is copied. Short regions throw.

Release build, max_threads = 8, paired runs, fix/base:

  • 100 files, not cached, NVMe (read_ahead_kb 6144): q2 0.39, q3 0.38, q7 0.37, q8 0.44, q30 0.45, q36 0.70, q39 0.72.
  • Same, EBS (read_ahead_kb 128): q3 0.58, q4 0.82, q24 0.68, q30 0.68, of which the piecewise hints give 0.85-0.95.
  • hits.parquet, cached: q39 0.88, q37 0.95, q1 0.96, others unchanged; max RSS of q24 4.4 -> 2.7 GB. q21 (URL LIKE '%google%') is bimodal, 1.36x slower on average, from zero-copy itself (it uses 12% less CPU). The piecewise hints slow no cached query.
  • All 43 ClickBench queries return the same results.

tests/performance cannot use mmap (clickhouse-server refuses it for files), so the new stateless test compares mmap with pread in clickhouse-local and checks the new ParquetPrefetcherReadZeroCopy event.

🤖 Generated with Claude Code


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

groeneai and others added 2 commits October 8, 2026 05:06
…e mapping

clickhouse-local reads local files through mmap (storage_file_read_method =
'mmap'), and the Parquet Prefetcher copied every byte range out of the mapping
with readBigAt. Warm, that is an extra copy of every column chunk plus page
faults on the new buffer. Cold, the copy's page faults drive the I/O and each
fault reads the whole read-ahead window around the page, so small column chunks
cost many times their size.

MMapReadBufferFromFileDescriptor now implements readBigAtRetainCells: a single
region pointing into the mapping, with an empty handle, which the Prefetcher
already consumes for the userspace page cache. Before returning it asks the
kernel to read exactly that range (posix_fadvise WILLNEED, best effort).
readBigAt issues the same hint when the first page of the range is not cached,
which covers footers and the ranges that are still copied.

Decoders read up to PADDING_FOR_SIMD bytes before and after a range, so the
Prefetcher keeps copying ranges that are closer than that to either end of the
file. It also checks that the returned regions cover the whole range and throws
the same "Unexpected eof" as readSync otherwise, instead of a debug-only
assertion.

A new ParquetPrefetcherReadZeroCopy profile event counts the reads that
reference the read buffer's data instead of copying it. The new test checks it
and compares mmap and pread reads in clickhouse-local; server tests never use
mmap for files.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Merge the two-line zero-copy comment in Prefetcher::runTask into one line.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-issue PR origin: picked up an external GitHub issue labels Oct 8, 2026
@groeneai

groeneai commented Oct 8, 2026

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

Pre-publication review by an independent model (engine: codex; 3 rounds) plus my own review (2 blockers, 3 nits).

# Sev Finding Verdict Evidence / action
1 ❌ adviseWillNeed parameters are unused where POSIX_FADV_WILLNEED does not exist (macOS), which breaks the Darwin builds under -Werror (MMapReadBufferFromFileDescriptor.cpp) AGREE, fixed parameters marked [[maybe_unused]], as in preadNoWait.cpp
2 ❌ char probe; in readBigAt has no initializer, which cppcoreguidelines-init-variables rejects in Build (arm_tidy) AGREE, fixed char probe = 0;, checked with clang-tidy-22 on the touched files
3 ⚠️ The new test does not prove that the zero-copy path runs: a failed mmap falls back to pread, and without retained regions the Prefetcher silently copies, with equal results AGREE, fixed the test asserts CreatedReadBufferMMap and a new ParquetPrefetcherReadZeroCopy event (the existing per-mode events count both branches as RandomRead)
4 💡 Where preadNoWait is unavailable, every readBigAt also issues the hint DISAGREE deliberate: the hint is only advice, and this costs two system calls per copied range (footers, ranges at the file edges)
5 💡 Cached hits.parquet q21 is 1.36x slower on average DISAGREE (disclosed) the same without the hint, and the hint-only variant loses most of the uncached gains; numbers are in the PR description
6 💡 The test uses LIMIT 3 where the plan said LIMIT 5 DISAGREE the lazy-materialization pass runs for any limit

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by the fix round are auto-dropped.

Session id: cron:clickhouse-review-slot-9:20261008-051100

@groeneai

groeneai commented Oct 8, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Not a bug: a performance change. Paired base/fix runs are stable in direction (cold 100-file q2 0.39 [0.34, 0.46], 4 pairs). Mutations below are deterministic.
b Root cause explained? clickhouse-local reads files through mmap; the Parquet Prefetcher copied every range out of the mapping with readBigAt. Cold, each page fault of that copy reads the whole read-ahead window (q2 read 1.96 GB for 9 MB of ranges); warm, it is an extra copy per column chunk.
c Fix matches root cause? Yes: the mapped data is referenced in place through the existing zero-copy branch (#100300), and the kernel is asked to read exactly the requested range.
d Test intent preserved / new tests added? New 05339_parquet_local_mmap_zero_copy.sh compares mmap and pread reads in clickhouse-local (two codecs, 20 row groups, plain/dictionary ints, String, Decimal, Nullable, Array, Map, PREWHERE, page index, lazy materialization, a 1-row file), after asserting that mmap is selected (CreatedReadBufferMMap) and the zero-copy branch ran (ParquetPrefetcherReadZeroCopy), so a silent fallback cannot pass it; existing tests unchanged.
e Both directions demonstrated? Shifting the zero-copy region by one byte makes the new test fail on every query of both multi-row-group files; a short region throws Unexpected eof with the new size check and hits the getRangeData assertion without it. Making supportsReadAtRetainCells() return false fails the test on the zero-copy line. Perf: paired base/fix.
f Fix is general across code paths? Single consumer (Prefetcher); the edge-padding guard and the size check also cover the page cache producer. Footer and schema-inference reads keep copying and get the read hint. MMapReadBufferFromFileWithCache (MergeTree) is a separate class, untouched.
g Fix generalizes across inputs (params/datatypes/wrappers)? Types and codecs listed in (d); ranges near both file edges keep copying; all 43 ClickBench queries over 100 real files return identical results for base, fix with mmap and fix with pread.
h Backward compatible? (maintainer-approved exception only) Yes: no setting or format change; the server never uses mmap for files.
i Invariants and contracts preserved? A span handed to a decoder keeps PADDING_FOR_SIMD readable bytes on both sides (edge guard) and stays valid until decoding stops (the format drains the reader before the read buffer is destroyed); regions not covering the range throw instead of producing an out-of-bounds span.

Session id: cron:clickhouse-impl-slot-4:20261008-004400

@clickhouse-gh

clickhouse-gh Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d3d89cc]

Summary: ❌

job_name test_name status info comment
AST fuzzer (amd_debug, targeted) FAIL
Logical error: Reading from materialized CTE 'A' before its materialization completed - DelayedPortsProcessor gate is missing in the query plan (STID: 2467-34d3) FAIL cidb
Build (arm_tidy, 2/4) ERROR
Build (arm_tidy, 3/4) ERROR
Build (arm_tidy, 4/4) ERROR

AI Review

Summary

This PR lets clickhouse-local decode Parquet directly from memory-mapped files, selects kernel read-ahead hints according to expected consumption, and checks decoder padding for mapped and cached regions. At head d3d89ccfe6ea16aa75dfe2ac8abdf880c75f6223, one existing major finding remains: page splitting loses the partial-read classification and can prefetch substantially more data than a selective query needs. No new inline findings; the redundant-hint finding is fixed.

Findings

⚠️ Majors

  • src/Processors/Formats/Impl/Parquet/Reader.cpp:1606: The partial-read classification must survive splitting a column chunk into page requests. markDataPagesThatMayBeReadPartially marks data_pages_prefetch, but determinePagesToPrefetch replaces that handle through splitRange. Its new RequestState objects default to may_be_read_partially = false, and neither path copies the parent flag to the children. A subsequently scheduled child therefore takes the full piecewise POSIX_FADV_WILLNEED path. For example, a 1 MiB uncompressed plain integer page accessed for a few surviving rows receives eight 128 KiB hints, although decoding only needs the header and selected values. This causes unnecessary disk reads and cache pressure in the selective reads the PR intends to protect. Propagate the flag to split data-page requests or mark them before scheduling; an undeclared dictionary page can retain full-read classification. Existing unresolved thread; no duplicate comment posted.
Tests
  • ⚠️ The new 05339_parquet_local_mmap_zero_copy test passed in the current ARM stateless report, but result equality and ParquetPrefetcherReadZeroCopy do not distinguish single hints from piecewise hints. Add focused evidence for sparse reads of a large uncompressed page with an offset index, checking that split data-page requests retain the partial-read policy. No local build was available to rerun runtime tests.
Final Verdict

⚠️ Request changes — Preserve partial-read classification across page splitting and provide focused regression evidence for hint selection on that path.

@clickhouse-gh

clickhouse-gh Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit d3d89ccfe6ea16aa75dfe2ac8abdf880c75f6223 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

groeneai and others added 2 commits October 8, 2026 07:54
One POSIX_FADV_WILLNEED makes Linux read at most
max(read_ahead_kb, max_sectors_kb) of the range (force_page_cache_ra()
caps the request), so with the default 128 KiB the rest of a large column
chunk was still read one 128 KiB page fault at a time. On an EBS volume
(read_ahead_kb 128, max_sectors_kb 128) one hint for 8 MiB made 128 KiB
resident; the same range advised in 128 KiB pieces became fully resident.

Advise in 128 KiB pieces where the whole range is read: copies (such as
footer reads) and prefetch tasks whose ranges are all decoded in full.
Data pages that a later PREWHERE step, a read of selected rows or column
index pruning may decode only in part keep the single hint: advising those
in full made ClickBench q24 read 32% more and run 1.34x slower.

100-file ClickBench on EBS, data not cached, against the previous commit:
q3 0.90, q4 0.90, q24 0.95, q30 0.85; q2, q11 unchanged. Cached
hits.parquet: unchanged (q1, q2, q4, q21, q22, q23, q24, q39).

Analysis and patch by snelheidai in ClickHouse#124517.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Parquet decoders may read up to PADDING_FOR_SIMD bytes on both sides of a
range (Decoding.h makeDecoder). A userspace page cache cell is allocated
with exactly its size, so a retained region that starts or ends at a cell
edge has no readable bytes on that side, and decoding it in place could
read outside the cell. The previous check only covered the two ends of
the file, which is the whole condition for a memory-mapped file.

Producers now report how many bytes are readable around each region, and
the Prefetcher copies a single region that lacks the padding, as it
already copies a range that spans several cells.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai and others added 2 commits October 8, 2026 11:40
`readBigAtRetainCells` of the mmap buffer always advised the whole range once, so a range the Prefetcher
had already advised in pieces (one that is decoded in full) got a second, redundant `POSIX_FADV_WILLNEED`.
The caller now picks the mode: `adviseWillNeed` advises in pieces or once, and `readBigAtRetainCells`
issues no hint. The pages the second hint covered were already queued by the pieces, so the I/O is the same.

The hint is issued after the zero-copy decision, which reads nothing from the mapping, so a range that is
copied for lack of padding (the first column chunk of a file starts at offset 4) is advised in pieces even
when it may be decoded only in part: the copy reads all of it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
One range that may be decoded only in part made its whole task advised with a single hint, so a large range
decoded in full that had a short partial neighbour coalesced into its task was mostly faulted in
synchronously. A task covers one range plus neighbours of at most `bytes_per_read_task` (32 KiB for local
files) on each side, so taking the mode of most of the task's bytes mis-advises at most those neighbours.

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

clickhouse-gh Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

🟢 AI verdict: improvement — 1 query(s) improved out of 31 analysed

One query is flagged: clickbench Q20 improved by -42.3% (median 220 ms to 127 ms), and CPU time fell from about 2900 ms to 1528 ms. The shift is large and clear, so the hard-trust rule locks the verdict and it stays an improvement. The diff only touches the Parquet prefetcher's zero-copy path for memory-mapped files and the userspace page cache, plus page-cache read-ahead hints for mmap reads. If clickbench reads MergeTree tables through the server's default read method, that path is not exercised, so this PR may not be the cause. Re-run against the exact merge base before claiming the gain; the PR build reports version 26.10.1.1 and the baseline 26.10.1.42151, so the two may not share a base commit.

clickbench

🟢 1 improved

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🟢 20 improvement 220 127 -42.3% <0.0001 cpu: -42.3% (220 ms to 127 ms), and CPU time roughly halves. The diff only changes Parquet reads from mmap and page-cache buffers, so the cause is not confirmed.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: ed2df461-0297-46e2-9f6a-14143a3df60f
  • MIRAI run: 0a4a4e94-5854-4ce6-b8cd-fdf464fa23f0
  • PR check IDs:
    • clickbench_87617_1791939313
    • clickbench_87776_1791939335
    • clickbench_87935_1791939441
    • tpch_adapted_1_official_88041_1791939446
    • tpch_adapted_1_official_88169_1791939537
    • tpch_adapted_1_official_88291_1791939570

|| std::any_of(row_group.columns.begin(), row_group.columns.end(), [](const ColumnChunk & c) { return c.use_column_index; });
for (size_t i = 0; i < primitive_columns.size(); ++i)
if (rows_may_be_narrowed || primitive_columns[i].first_step_to_calculate != first_step)
prefetcher.markMayBeReadPartially(row_group.columns.at(i).data_pages_prefetch);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This only tags the original column.data_pages_prefetch handle. In the offset-index path determinePagesToPrefetch later replaces that handle with page-sized children from splitRange, and those fresh RequestStates start with may_be_read_partially = false. So the child tasks still look "read entirely" and take the piecewise POSIX_FADV_WILLNEED path even for page-pruned / rows_to_read / later-step reads — exactly the case the single-hint policy is trying to protect.

Can we either propagate may_be_read_partially through splitRange or re-mark the child page handles after the split (excluding the undeclared dictionary-page handle if needed)?

@snelheidai

Copy link
Copy Markdown

d3d89ccf no longer merges into master: Prefetcher.h and Prefetcher.cpp conflict, the same way on today's master 64576f9. Master added std::atomic<bool> data_used to RequestState, the ParquetPrefetcherReadBytes/ParquetPrefetcherUsedBytes counters, and a resize_exact + chassert copy loop. Keeping both sides works: both RequestState fields, all three event declarations, and master's copy loop as the PR's non-zero-copy else branch. getRangeData counts used bytes before it checks cached_region, so zero-copy reads keep master's accounting. The other files merge cleanly.

Resolved non-zero-copy branch in Prefetcher::runTask
            else
            {
                /// If the data spans multiple cache blocks or lacks the padding, pre-assemble it into task->buf now
                /// (on the single-threaded producer side) to avoid a data race in getRangeData,
                /// where multiple consumer threads could try to lazily populate task->buf concurrently.
                task->buf.resize_exact(task->length);
                size_t copied = 0;
                for (const auto & region : cached_regions)
                {
                    memcpy(task->buf.data() + copied, region.data, region.size);
                    copied += region.size;
                }
                chassert(copied == task->length);
            }

I measured this merge on master 607c2a3 (Nov 2) as M against that master as B on 16 Graviton3 cores (r7g.4xlarge): the 100-file ClickBench Parquet set (clickhouse-parquet-partitioned create.sql), one new clickhouse local --time process per query, max_threads = max_parsing_threads = 16. Query numbers are lines of queries.sql; Q24 is SELECT * FROM hits WHERE URL LIKE '%google%' ORDER BY EventTime LIMIT 10. Results match between the builds; Q39 and Q40 have ties at OFFSET 1000, so their rows vary from run to run in both.

Data in the page cache, 5 rounds with the builds alternating, M/B as the geometric mean with a Student-t 95% interval:

Query B, ms M, ms M/B [95% CI] Page faults, M/B Max RSS, MiB, B → M
Q24 181 139 0.780 [0.735, 0.827] 0.44 958 → 581
Q22 544 448 0.828 [0.807, 0.849] 0.25 2834 → 1103
Q21 486 411 0.833 [0.803, 0.864] 0.27 2499 → 1052
Q23 779 668 0.856 [0.839, 0.873] 0.26 3879 → 1470
Q28 593 545 0.910 [0.873, 0.948] 0.74 3710 → 2755
Q13 238 231 0.976 [0.960, 0.992] 0.94 1823 → 1697

Q1, Q2, Q20 and Q37–Q40 show no significant difference; every interval contains 1.

Page cache dropped before every run (binary kept cached), 2 rounds, query time in seconds:

Query B M
Q2 0.367, 0.363 0.053, 0.051
Q37 0.495, 0.484 0.255, 0.263
Q24 7.16, 7.17 4.17, 4.23
Q21 20.89, 20.78 20.12, 20.12

Q21 is limited by reading the URL column from disk in both builds.

This branch has not been deployed

No deployments
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. groeneai-origin-issue PR origin: picked up an external GitHub issue pr-performance Pull request with some performance improvements

Projects

None yet

3 participants