Skip to content

Fix use-after-free of the read buffer when creating an object storage reader throws - #125090

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-object-storage-reader-buffer-lifetime
Oct 12, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-object-storage-reader-buffer-lifetime

Conversation

@groeneai

@groeneai groeneai commented Oct 10, 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 a heap use-after-free in the s3, azureBlobStorage, hdfs and other object storage table functions and engines when an exception (for example MEMORY_LIMIT_EXCEEDED) was thrown while creating the reader of a file in a row input format such as CSV.

Description

On 26.8 (also 25.8, 26.3, 26.9), a CSV read from s3 that hits max_memory_usage while a file's reader is being created writes into freed memory (heap-use-after-free under ASan, use-of-uninitialized-value under MSan).

Found by Stress test (amd_msan): report.

StorageObjectStorageSource::createReader declared builder and source before read_buf. When an exception unwinds the function after the input format is created, read_buf is destroyed first, and the input format, still owned by builder or source, then runs ~PeekableReadBuffer, which reads and writes the freed buffer. ReaderHolder already declares read_buf first; this PR does the same for the locals.

Validation (ASan, local MinIO): the new test aborts master 10/10 and passes 50/50 with the fix (also 50/50 through clickhouse-test with randomized settings); reverting only the reorder brings the abort back 10/10. A local probe that throws right before return ReaderHolder( aborts the old order 3/3 and returns a clean error with the fix 3/3.

IInputFormat::addBuffer had the same ordering problem: it took the buffer by value, so a failed allocation in owned_buffers.emplace_back destroyed the buffer before the format reading it. It now takes the buffer by reference. No SQL test reaches that allocation reliably; a probe that throws there aborts an ASan server on a .csv.gz read from S3 and on an HTTP INSERT ... FORMAT CSV with the old signature, and both fail cleanly with the new one.

CI report and the crashing query
WARNING: MemorySanitizer: use-of-uninitialized-value
#0 DB::PeekableReadBuffer::~PeekableReadBuffer() src/IO/PeekableReadBuffer.cpp:324:9
#4 DB::CSVRowInputFormat::~CSVRowInputFormat() src/Processors/Formats/Impl/CSVRowInputFormat.h:20:7
#7 std::shared_ptr<DB::ISource>::~shared_ptr()
#8 DB::StorageObjectStorageSource::createReader(unsigned long, ...) StorageObjectStorageSource.cpp:1825:1
#9 DB::StorageObjectStorageSource::createReader() StorageObjectStorageSource.cpp:1120:12
#10 DB::StorageObjectStorageSource::lazyInitialize() StorageObjectStorageSource.cpp:733:14
Uninitialized value was created by a heap deallocation
#3 std::unique_ptr<DB::ReadBuffer>::~unique_ptr()
#4 DB::StorageObjectStorageSource::createReader(unsigned long, ...) StorageObjectStorageSource.cpp:1825:1

Query 2aa8085a, run with memory_tracker_fault_probability = 0.05, input_format_parallel_parsing = 0:

14:48:01.663241 [ 14841 ] executeQuery: SELECT id, _file, data, _size, _path FROM cosn(s3_conn, filename = '03036_archive1.zip :: example1.csv') ...
14:48:01.868788 [ 12955 ] StorageObjectStorageSource: Reading object '03036_archive1.zip::example1.csv', size: 372 bytes, with format: CSV

Thread 12955 logs nothing after this line.


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

Version info

  • Merged into: 26.10.1.2229-master (included in 26.10 and later)
  • Backported to: 26.9.18.6, 26.8.26.6, 26.7.29.13, 26.3.50.11

… reader throws

`StorageObjectStorageSource::createReader` declared `builder` and `source`
before `read_buf`. If an exception (for example `MEMORY_LIMIT_EXCEEDED`)
unwinds the function after the input format has been created over
`*read_buf`, the buffer is destroyed first, and the input format, still
owned by `builder` or `source`, then runs `~PeekableReadBuffer`, which
reads and writes the freed buffer. Found by `Stress test (amd_msan)` as
`use-of-uninitialized-value` in `~PeekableReadBuffer` with the
uninitialized value created by a heap deallocation in `createReader`.

Declare `read_buf` first, as `ReaderHolder` already does, so it outlives
the objects that read it on every path.

The test reads 100 CSV objects from S3 under
`memory_tracker_fault_probability`: master ASan aborts 10/10, the fix
passes 50/50.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Oct 10, 2026
@groeneai

groeneai commented Oct 10, 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; 2 findings), plus my own cold review (1 nit).

# Sev Finding Verdict Evidence / action
1 ❌ IInputFormat::addBuffer takes the buffer by value, so if owned_buffers.emplace_back throws, the wrapper is freed before the format (IInputFormat.h:127, FormatFactory.cpp:683) AGREE (later) Fixed in cbb1ad3: addBuffer takes the buffer by reference. A probe throwing there aborts an ASan server by value (S3 .csv.gz read, HTTP inline INSERT) and fails cleanly by reference.
2 ⚠️ The test does not prove that an exception reaches the window, and swallowed errors would let it pass if injection never landed DISAGREE Measured with the shipped test: master ASan aborts 10/10, and 3/3 under clickhouse-test randomization; reverting only the reorder aborts 10/10; the fix passes 50/50 in three separate sets. In the randomized debug runs, 5942 of 6396 logged queries failed with code 241. Same oracle as 04299_move_assignment_memory_limit.sh.
3 💡 No long tag (my review) noted The loop is capped at 60 s (12-24 s on ASan), and the flaky-check limit is 180 s.

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

Session id: cron:clickhouse-review-slot-8:20261010-170300

@groeneai

groeneai commented Oct 10, 2026 •

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. A local probe throwing right before return ReaderHolder( aborts an ASan server 3/3 with the CI stack; the new test aborts master ASan 10/10.
b Root cause explained? createReader declared read_buf after builder and source; on unwind the buffer is freed first and the input format's ~PeekableReadBuffer then reads and writes it.
c Fix matches root cause? Yes. read_buf is declared first, as in ReaderHolder; no guard and no try/catch.
d Test intent preserved / new tests added? New test 05384_object_storage_reader_exception_buffer_lifetime.sh: 100 S3 CSV reads under memory_tracker_fault_probability, then checks the server and the data.
e Both directions demonstrated? Master 10/10 abort, fix 50/50 pass (ASan), mutation (reorder reverted) 10/10 abort; probe 3/3 abort vs 3/3 clean error.
f Fix is general across code paths? S3Queue/AzureQueue and the async reader call the same function. Other file-like readers already own the buffer first. IInputFormat::addBuffer (same class) is fixed in cbb1ad3.
g Fix generalizes across inputs (params/datatypes/wrappers)? Independent of format, compression and archive members: the fix is on the owner of the buffer. Seen on plain objects (test) and an archive member (CI).
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or non-exception behaviour change.
i Invariants and contracts preserved? The buffer outlives every reader of it on normal and exception paths; pipeline and current_reader still die before it; the normal return moves the same objects into ReaderHolder.

Session id: cron:clickhouse-impl-slot-5:20261010-135300

@groeneai
groeneai requested review from kssenii and scanhex12 October 10, 2026 17:37
@clickhouse-gh

clickhouse-gh Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [cbb1ad3]

Summary: ✅


AI Review

Summary

This PR fixes a real lifetime bug in object-storage reader construction and the companion ownership hole in IInputFormat::addBuffer. I re-checked the changed destruction order in src/Storages/ObjectStorage/StorageObjectStorageSource.cpp:1270 and every current addBuffer caller, and the current patch closes the previously reported unwind path without introducing a new ownership mismatch.

Final Verdict

✅ No blocking issues found. The existing inline finding is fixed in the current code.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 10, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-object-storage Object storage connectivity (S3/GCS/Azure) including credentials, retries, multipart, etc. label Oct 10, 2026
`addBuffer` took the `unique_ptr` by value, so the ownership moved into
the parameter before `owned_buffers.emplace_back` could allocate. If that
allocation threw, the parameter destroyed the buffer while the format
built over it was still alive, and destroying the format then ran
`~PeekableReadBuffer` on the freed buffer. `FormatFactory::getInputImpl`
hits this for every wrapped buffer (compressed or parallel object storage
reads), `getInputFormatFromASTInsertQuery` for inline insert data.

Take the buffer by reference, so it moves only once the insertion
succeeded and a failure leaves it with the caller, which declares it
before the format. The template keeps that true for callers passing a
`unique_ptr` to a derived buffer, which would otherwise bind a temporary.

A probe that throws in `addBuffer` before the insertion aborts an ASan
server with `heap-use-after-free` in `~PeekableReadBuffer` on a `.csv.gz`
read from S3 and on an HTTP `INSERT ... FORMAT CSV`; with this change both
fail cleanly with the thrown exception.

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

clickhouse-gh Bot commented Oct 10, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing cbb1ad3e4 with master 630394453 (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.

Compile time of recompiled translation units

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

Median compile-time ratio to the baselines is ×0.94 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost -57.9 s (-4%) in total before that adjustment.

Job report

@PedroTadim PedroTadim self-assigned this Oct 12, 2026
@alexey-milovidov alexey-milovidov added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Oct 12, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 12, 2026
Merged via the queue into ClickHouse:master with commit fd87d02 Oct 12, 2026
163 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 12, 2026
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Oct 12, 2026
@robot-clickhouse robot-clickhouse added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Oct 12, 2026
clickhouse-gh Bot added a commit that referenced this pull request Oct 12, 2026
Backport #125090 to 26.9: Fix use-after-free of the read buffer when creating an object storage reader throws
clickhouse-gh Bot added a commit that referenced this pull request Oct 12, 2026
Backport #125090 to 26.8: Fix use-after-free of the read buffer when creating an object storage reader throws
clickhouse-gh Bot added a commit that referenced this pull request Oct 12, 2026
Backport #125090 to 26.7: Fix use-after-free of the read buffer when creating an object storage reader throws
alexey-milovidov added a commit that referenced this pull request Oct 13, 2026
Backport #125090 to 26.3: Fix use-after-free of the read buffer when creating an object storage reader throws
strtgbb pushed a commit to Altinity/ClickHouse that referenced this pull request Oct 13, 2026
…ffer when creating an object storage reader throws
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-object-storage Object storage connectivity (S3/GCS/Azure) including credentials, retries, multipart, etc. groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default 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.

6 participants