Skip to content

Stop Parquet background reads before releasing the format's read buffer - #114668

Merged
alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
groeneai:fix-parquet-prefetcher-buffer-lifetime
Aug 14, 2026
Merged

alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
groeneai:fix-parquet-prefetcher-buffer-lifetime

Conversation

@groeneai

@groeneai groeneai commented Aug 13, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed heap memory corruption when reading Parquet through an input format that owns its read buffer, for example a dictionary with SOURCE(FILE(... format 'Parquet')). Background prefetch and decode tasks could still read and write through the buffer after the pipeline released it, which could abort the server.

Description

Closes #114612, reported by @ PedroTadim, who asked me to go ahead in #114612 (comment).

A ReadBuffer handed to an input format via addBuffer() lives in the format's owned_buffers. ISource::work() calls onFinish() on both the clean and the exception path, reaching IInputFormat::resetReadBuffer(), which clears owned_buffers and destroys the buffer. ParquetV3BlockInputFormat did not override that hook, and Parquet::Prefetcher holds a non-owning SeekableReadBuffer * to the same buffer, so background tasks kept using a destroyed object. It is not only a bad read: the report on the issue is a 1 MiB write into freed heap through ReadBuffer::next(), silent on a release build. ~Prefetcher() does the right handshake, but only at format destruction, later than onFinish(); that window is the bug.

The fix overrides resetReadBuffer() to drain background tasks before the base class releases the buffers, mirroring ParallelParsingInputFormat::onFinish(). Three details are forced by the surrounding code: the hook is resetReadBuffer(), not onFinish(), since it frees the buffers and has a second caller in StreamingFormatExecutor; the reader is drained but kept alive, because getMatchedBuckets() reads row group metadata after exhaustion; and ReadManager is drained before Prefetcher, because decode tasks re-enter readSync inline via getRangeData().

Sibling teardown paths: resetParser() already destroys the reader before delegating, onCancel() cancels it, and the reuse route through StreamingFormatExecutor calls resetParser() on every exit, so a drained reader is never reused.

No fuzzer needed: ReadBufferFromFile leaves use_pread false, so a local file takes SeekAndRead, and any CREATE DICTIONARY ... SOURCE(FILE(... format 'Parquet')) whose load throws reaches it.

Validated on ASAN: the added test fails 7/7 unfixed, passes 11/11 fixed; a standalone reproducer 31/33 unfixed, 0/35 fixed; a negative control with only the override reverted reddens at the unfixed rate. Parquet and polygon-dictionary suites gave an identical failing set on both binaries (187 each); 50 randomized-settings repeats passed clean.

Version info

  • Backported to: 26.7.4.42, 26.6.3.56, 26.5.7.56, 26.3.18.30, 25.8.31.6

groeneai and others added 4 commits August 13, 2026 07:29
A dictionary that reads Parquet from a local file hands its ReadBuffer to the
input format via IInputFormat::addBuffer(), so the format owns it in
owned_buffers. When the pipeline finishes, ISource::work() calls onFinish() on
both the clean (ISource.cpp:133) and the exception (ISource.cpp:140) path, which
reaches IInputFormat::resetReadBuffer() and clears owned_buffers, destroying the
buffer.

ParquetV3BlockInputFormat did not override that hook, and Parquet::Prefetcher
holds a non-owning SeekableReadBuffer* to the same buffer (Prefetcher.h:175).
Background prefetch and decode tasks therefore kept reading through a destroyed
object. Prefetcher.cpp:111 is a virtual call on it, so the 8-byte read is the
freed vptr; observed both as an AddressSanitizer heap-use-after-free in
Prefetcher::readSync and as a libc++abi pure-virtual abort. ~Prefetcher() does
perform the correct shutdown handshake, but only at format destruction, which is
strictly later than onFinish(); the window between the two is the bug.

The hook is resetReadBuffer() rather than onFinish() because it is what actually
frees the buffers and it has a second caller,
StreamingFormatExecutor::execute()'s SCOPE_EXIT. Two task families need
draining, not one: Prefetcher's IO tasks and ReadManager's decode tasks, which
re-enter readSync inline via getRangeData(). ReadManager is drained first, since
it produces the tasks that reach the prefetcher. The reader itself is kept
alive, because getMatchedBuckets() reads row group metadata after the source is
exhausted to populate the query condition cache.

This mirrors ParallelParsingInputFormat::onFinish(), which waits for its threads
for the same reason.

Found by the La Casa Del Dolor (arm_asan_ubsan) fuzzer check. Reachable without
a fuzzer: ReadBufferFromFile leaves use_pread false, so a plain local file takes
the SeekAndRead path, and any CREATE DICTIONARY ... SOURCE(FILE(... format
'Parquet')) whose load throws hits it.

Co-Authored-By: Claude Fable 5 <[email protected]>
The regression test passed on the unfixed binary most of the time because it
did not exercise what its comments claimed.

Two independent defects, both confirmed by measurement before being changed.
The five-iteration loop performed a single real load: once the dictionary is
FAILED, a non-forced dictGet cannot re-enter startLoading, because
getMinIDToFinishLoading(false) returns 1 while loading_id is already at least
1, so checkLoaded rethrows the stored exception. Nothing filled the gap inside
one run, since a failed load pins the next update five seconds out and the
periodic updater's own period is also five seconds. Counting error messages
could not see this, as the replayed message is byte-identical. Per-iteration
prefetcher reads were 93, 0, 0, 0, 0; with SYSTEM RELOAD DICTIONARY, which
forces a reload, they are 85, 90, 85, 86, 83.

The three race-widening settings never reached the load either. A dictionary
loads in the global context, and the file source only applies the DDL SETTINGS
clause, so the format was built from defaults. Moving min_bytes_for_seek into
that clause changes the per-reload read count from 87 to 241 at 1 and to 2 at
100000000, while the same value on the client command line does not change it
at all. A typo'd name inside the clause is silently ignored, which is the
negative control that a dead clause cannot look like a live one.

With both fixed the test still reddened rarely, so the remaining difference
against the standalone reproducer was isolated: at 2000000 rows it survives
five forced reloads with 8 threads and dies with 32, so concurrency carries
the window, not fixture size. The test now reddens 7 of 7 scored runs on the
unfixed binary, all of them a pure-virtual abort at Prefetcher.cpp:111, and
passes 11 of 11 fixed plus 50 of 50 randomized runs. A local unfixed run also
produced a full heap-use-after-free whose symbolized stack matches the CI
report frame for frame, including both thread names and the 272-byte region.

The loop is now guarded by a control that reads per-query ProfileEvents from
system.query_log, so each of the five reloads is proven to have reached the
reader. The global system.events counter was rejected as pollutable on a
shared server, and system.dictionaries.error_count as unreliable, since the
periodic updater also increments it.

The long tag is dropped because it costs 90 percent of the flaky check's
repeats, and the test measures 16 to 24 seconds against a 180 second
threshold. The only source change is a comment trim.

Co-Authored-By: Claude Fable 5 <[email protected]>
The test asserted ParquetPrefetcherReadSeekAndRead > 0 per reload, but that
counter is also incremented by the two synchronous footer reads in
Reader::readFileMetaData, so a load rejected while its footer was parsed
satisfied the assertion without ever reading a row group. Measured on a file
with a corrupt footer length: the old assertion passed 5 of 5 while no row
group was read. ParquetReadRowGroups is counted once row groups are being
read, and measured 397 on 20 of 20 reloads of this fixture, so it separates
the two cases without making the test timing dependent.

Pin input_format_parquet_enable_row_group_prefetch so the prefetch pool
exists regardless of a server side or future default: without it
Prefetcher::scheduleTask does nothing and getRangeData runs the read inline
on the decoding thread, which no read counter distinguishes.

Renumber to 04895, since 04885 was taken first by another unmerged test.
Content half of the previous commit, which recorded only the rename.
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

Three rounds of independent cold review, each followed by a second-model gate pass. The source
fix was verified independently in every round and never needed a change; all fixed findings below
are about the regression test, and all were fixed before this PR was published.

Finding Verdict
❌ The test's 5-iteration dictGet loop performed only one real dictionary load. Once the dictionary is FAILED, a non-forced load never re-enters startLoading (ExternalLoader.cpp:922-923, :982-984) and checkLoaded rethrows the cached exception, while the retry backoff and the periodic updater both sit 5s out. A count-based oracle cannot see this, since the replayed error text is identical. Raised independently by the cold review and the gate. AGREE, fixed: each iteration now forces a reload. Measured per-iteration read counts went from 93, 0, 0, 0, 0 to 85, 90, 85, 86, 83
❌ The three race-widening settings were passed as query settings, but a dictionary load runs in the global context (ExternalDictionariesLoader.cpp:55) and the file source applies only the DDL SETTINGS(...) clause (FileDictionarySource.cpp:104 -> DictionarySourceHelpers.cpp:62-91), so the format was built with defaults. AGREE, fixed: settings moved into the DDL, confirmed by observation (two orders of magnitude in read count) plus a misspelled-setting control
❌ The per-iteration oracle used ParquetPrefetcherReadSeekAndRead, which the synchronous footer read in Reader::readFileMetaData (Reader.cpp:234) already increments, so a file rejected while its footer is parsed satisfied the oracle without reading a single row group. AGREE, fixed: the oracle moved to ParquetReadRowGroups (ReadManager.cpp:67, past the footer), demonstrated with a corrupted-footer fixture on which the old oracle passes 5/5 and the new one fails 0/5
⚠️ The long tag cut the flaky check's repeat count to 10% (tests/clickhouse-test:4370-4372) and excluded the test from the --no-long run, on a test measured at 16 to 24s against a 180s threshold. AGREE, fixed: tag dropped
⚠️ The randomized 50-run gate item was outstanding, and running it before the fixes above would have measured a test that did not exercise the defect. AGREE, run last: 50 passed, 0 skipped, no sanitizer reports
💡 A comment block exceeded the 3-line-per-block budget. AGREE, condensed

Two residuals were adjudicated as not blocking, and are recorded here rather than dropped:

  • The gate argued the oracle still does not prove that a background task ran, since a decode
    task can perform the read inline through getRangeData(). That is a coverage-attribution point,
    not a detector gap: in that state the read still happens on a decode-pool thread concurrently
    with onFinish(), so an unfixed binary still aborts and the test still fails. It was measured
    doing exactly that, with a base-arm crash through readSync <- Prefetcher::runTask <-
    getRangeData <- decodeDictionaryPage. The pooled path is confirmed separately: the base
    arm's ASAN report shows the 1 MiB write on thread ParquetPrefetch, a thread name that can
    only exist if the prefetch pool was created. No non-timing counter distinguishes the two paths
    (measured: with prefetch disabled the reads are relocated, not removed), and the only signal
    that does is a timing measurement.
  • Prefetcher::shutdownTasks()'s comment claims more than the method guarantees on its own, since
    an inline getRangeData() read bypasses its shutdown helper. The required ordering is
    documented on the only caller (ReadManager.h:47-50), so following the call chain is not
    misleading, but I am happy to tighten the wording if you prefer.

Verified sound with no change required: resetReadBuffer() as the hook rather than onFinish()
(it is what frees the buffers, resetOwnedBuffers() has exactly one caller, and there is a second
independent caller in StreamingFormatExecutor); no deadlock under reader_mutex
(resetParser() already performs a strictly heavier drain under it); idempotence
(ShutdownHelper::begin_shutdown detects the repeat, so both destructors still work); the
ReadManager-before-Prefetcher order; keeping the reader alive so getMatchedBuckets() can still
populate the query condition cache; safety of the drain being permanent (the only reuse route
calls resetParser() on every exit path first, which destroys the reader); and an independent
sweep of the other formats that own a buffer while reading in the background
(ParallelParsingInputFormat already waits in onFinish; ORC's futures are each joined by its
cache's own destructor, and its prefetch requires a remote filesystem; DWARF consumes the buffer
before its runner exists).

@clickhouse-gh

clickhouse-gh Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [64e43f8]

Summary: ✅


AI Review

Summary

This PR fixes a real lifetime bug in ParquetV3BlockInputFormat by draining Parquet decode and prefetch work before IInputFormat::resetReadBuffer releases an owned ReadBuffer. I reviewed the changed teardown paths, the surrounding onFinish / resetParser / onCancel behavior, the new regression test, the prior PR discussion, and the current all-green CI results. I did not find any remaining correctness, concurrency, or coverage issues in the current code.

Final Verdict

✅ Approved. No new findings.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.70% 86.80% +0.10%
Functions 92.00% 92.00% +0.00%
Branches 79.10% 79.10% +0.00%

Changed lines: Changed C/C++ lines covered: 14/14 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 13, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate
# Check Result
a Deterministic repro Yes. A dictionary over a multi-row-group local Parquet file whose read throws mid-flight: the shipped test reddens 6 of 6 scored runs on the unfixed ASAN binary and passes 6 of 6 on the fixed one in the same harness, plus 4 of 4 direct runs and 50 of 50 randomized runs green on the fix. A second, independent harness fails 31 of 33 runs unfixed and 0 of 35 fixed.
b Root cause explained Yes. addBuffer() gives the format ownership of the ReadBuffer in owned_buffers; ISource::work() calls onFinish() on both the clean and the exception path; that reaches IInputFormat::resetReadBuffer(), which clears owned_buffers. ParquetV3BlockInputFormat did not override the hook, and Prefetcher::reader is a non-owning pointer to the same buffer, so background tasks read a destroyed object. Prefetcher.cpp:111 is a virtual call, so the read is the freed vptr.
c Fix matches root cause Yes. Restores the lifetime invariant at the teardown chokepoint. Explicitly not a validity flag or null check in readSync, which would hide a dangling pointer instead of correcting ownership.
d Test intent preserved, new test added Yes. New stateless test 04895_parquet_dictionary_source_prefetch_lifetime. No existing test removed or weakened. Its per-reload assertion is ParquetReadRowGroups > 0, which is counted only once row groups are being read, so a load rejected at footer parse cannot satisfy it: on a file with a deliberately corrupt footer length the assertion holds 0 of 5 while the weaker read-counter form held 5 of 5.
e Demonstrated in both directions Yes, on two independent harnesses. Shipped test: unfixed 6 of 6 red, fixed 6 of 6 pass, plus 50 of 50 randomized runs green. Second harness: unfixed 31 of 33 fail, fixed 0 of 35. Failures are a heap-use-after-free in Prefetcher::readSync or a pure-virtual abort from the freed vptr; the locally symbolized stack matches the CI report frame for frame, including thread names and the 272-byte region. A negative control with only the new override reverted and both drain methods kept reddens at the unfixed rate, isolating the override as the cause of the fix.
f General across code paths Yes. All carriers of the invariant were enumerated: ParallelParsingInputFormat already correct and used as the precedent; DWARFBlockInputFormat safe because in is fully consumed before its runner exists; NativeORCBlockInputFormat safe because its futures are joined by the ORC read cache's own destruction; ArrowIPCBlockInputFormat does no async work over in; every other resetReadBuffer override is synchronous. Symmetric teardown paths of the fixed format checked: onCancel() does not free buffers, resetParser() already destroys the reader under the same mutex.
g Generalizes across inputs Not applicable by nature: an object-lifetime defect, not type dispatch. The relevant axis is read mode, and the drain is mode-independent.
h Backward compatible Yes. No setting, no default change, no format or serialization change, no ABI surface, so no SettingsChangesHistory.cpp entry. The two new methods are additive and no existing call site changes behavior.
i Invariants and contracts preserved Yes. The drain is idempotent, since ShutdownHelper::begin_shutdown detects a repeat call, so both destructors still work and the existing chassert in ~Prefetcher still holds. Format reuse after the hook was verified unreachable on both callers of resetReadBuffer. Lock ordering is unchanged from the existing resetParser shape, and draining under reader_mutex cannot deadlock because resetParser() already performs the full drain under that same mutex today.

50 randomized runs of the new test: 50 passed, 0 skipped, 1267.73 s, no sanitizer report and no pure-virtual abort in the server log.

Every arm asserts the server's buildId() equals the binary's Build ID before it is scored, so a server that never started is skipped rather than counted as a failure.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 13, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @al13n321, could you review this? ParquetV3BlockInputFormat never overrode resetReadBuffer(), so IInputFormat::onFinish() cleared owned_buffers while Prefetcher::reader, a non-owning SeekableReadBuffer *, was still being used by in-flight tasks; the fix drains ReadManager then Prefetcher under reader_mutex before delegating, keeping the reader alive so getMatchedBuckets() still works.

The style check rejects a bare global SYSTEM FLUSH LOGS
(ci/jobs/scripts/check_style/various_checks.sh:192): flushing every log table
on the server disturbs tests running in parallel. The test only reads
system.query_log, so name that table.

Verified the scoped form is effective rather than silently ignored: the log
name is parsed and validated, so a wrong name errors with BAD_ARGUMENTS, and
with the flush removed entirely the reloads_that_read oracle reads 0 instead
of 5, i.e. the flush is load-bearing for the assertion.
@clickhouse-gh

clickhouse-gh Bot commented Aug 13, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 64e43f894 with master fb565a7db (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
Binary Master PR Δ
programs/clickhouse-stripped 691.76 MiB 688.75 MiB -3.01 MiB (-0.44%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 64e43f8

CI is fully finished on this commit with no failing checks, so there is nothing to own.

Check / test Reason Owner / fixing PR
(none failing) - -
Sync - CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260813-233000

@PedroTadim PedroTadim added pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! and removed pr-bugfix Pull request with bugfix, not backported by default labels Aug 14, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 14, 2026
clickhouse-gh Bot pushed a commit that referenced this pull request Aug 14, 2026
clickhouse-gh Bot added a commit that referenced this pull request Aug 14, 2026
Backport #114668 to 26.7: Stop Parquet background reads before releasing the format's read buffer
robot-ch-test-poll3 added a commit that referenced this pull request Aug 15, 2026
Cherry pick #114668 to 25.8: Stop Parquet background reads before releasing the format's read buffer
robot-clickhouse added a commit that referenced this pull request Aug 15, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Aug 15, 2026
alexey-milovidov added a commit that referenced this pull request Aug 15, 2026
Backport #114668 to 26.5: Stop Parquet background reads before releasing the format's read buffer
alexey-milovidov added a commit that referenced this pull request Aug 15, 2026
Backport #114668 to 26.3: Stop Parquet background reads before releasing the format's read buffer
clickhouse-gh Bot added a commit that referenced this pull request Aug 18, 2026
Backport #114668 to 26.6: Stop Parquet background reads before releasing the format's read buffer
PedroTadim added a commit that referenced this pull request Aug 18, 2026
Backport #114668 to 25.8: Stop Parquet background reads before releasing the format's read buffer
@groeneai groeneai added the groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect label Aug 19, 2026
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 24, 2026
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 24, 2026
VighneshPath pushed a commit to VighneshPath/ClickHouse that referenced this pull request Sep 16, 2026
bytehalo-infra added a commit to sentioxyz/ClickHouse that referenced this pull request Sep 25, 2026
PROTO: Parquet through a format that owns its buffer (e.g. a FILE dictionary) -> crash.
Effect in the production build a394e92: its upstream test(s) 04895_parquet_dictionary_source_prefetch_lifetime fail on it (the server process died in 04895_parquet_dictionary_source_prefetch_lifetime) and pass on official 26.8.8.8, run on isolated servers (evidence/fix_ci_20260925/upstream_repro/server_triage_PROD263_vs_UP2688.tsv).
Upstream patch unchanged, with its test(s): 04895_parquet_dictionary_source_prefetch_lifetime.

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

can be tested Allows running workflows for external contributors groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR 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.

Heap-use-after-free: Parquet v3 prefetcher reads and writes through a ReadBuffer freed by IInputFormat::onFinish

5 participants