Skip to content

Add diagnostic bounds asserts in threadpool remote-fs metadata read path (#104692) - #106657

Merged
Algunenano merged 4 commits into
ClickHouse:masterfrom
groeneai:groeneai/diagnostic-asserts-metadata-read-104692
Jun 10, 2026
Merged

Algunenano merged 4 commits into
ClickHouse:masterfrom
groeneai:groeneai/diagnostic-asserts-metadata-read-104692

Conversation

@groeneai

@groeneai groeneai commented Jun 7, 2026 •

Copy link
Copy Markdown
Collaborator

The flaky test 03710_parallel_alter_comment_rename_selects fails intermittently with server died while a SELECT * FROM system.tables worker thread reads table metadata via readMetadataFile. The two known surfacings look different but are both consistent with one underlying bug class.

  • In one occurrence the crash is in the memcpy inside appendToStringOrVector, with Address not mapped to object / SEGV_MAPERR -- the source pointer of the memcpy is unmapped.
  • In another occurrence (PR Optimize some joins by reusing the hash join's FixedHashMap as runtime filter #105640, 2026-05-25, aarch64 ASan+UBSan, decoded core), the live frames are LargeMmapAllocator::Deallocate from Quarantine::Recycle from operator delete from TablesBlockSource::generate (StorageSystemTables.cpp:959) -- the per-table String returned for one CREATE query has a corrupt large-allocation header by the time the loop iteration frees it.

Both fit one mechanism: somewhere in the threadpool remote-fs read chain (ReadBufferFromS3 -> ReadBufferFromRemoteFSGather -> AsynchronousBoundedReadBuffer), working_buffer ends up either inverted (end < position) or extended past the owned Memory<>. Then appendToStringOrVector's s.append(rb.position(), end - rb.position()) memcpys an arbitrary span and corrupts the destination String. The crash surfaces either at the memcpy (unmapped source) or much later when the oversized String is freed.

A core dump at the FREE site cannot reveal the WRITE site, and we have not been able to reproduce the failure locally despite several heavy MinIO+plain_rewritable+ASan stress runs.

Per @alexey-milovidov's request on #104692 (comment) ("yes, let's add more asserts"), this PR adds targeted chassert calls along the threadpool remote-fs metadata read chain. They are no-ops in release builds. They should fire on the WRITE site of the corruption with a deterministic stack trace next time CI hits this in a debug or sanitizer build, so we can identify the exact mechanism instead of guessing.

Asserts added:

  • src/IO/ReadHelpers.cpp -- in all three appendToStringOrVector overloads, assert end >= rb.position(), end <= rb.buffer().end(), and rb.position() >= rb.buffer().begin(). Catches an inverted or escaped working_buffer at the consumer side regardless of which inner buffer produced it.
  • src/Disks/IO/AsynchronousBoundedReadBuffer.cpp -- in nextImpl, where working_buffer is set from the IAsynchronousReader::Result, assert result.offset <= result.size and (when the page cache is not in use) result.size <= memory.size() and result.buf == memory.data(). Catches the case where the inner Gather/S3 chain returned a range that exceeds or doesn't match the owned Memory<>.
  • src/Disks/IO/ReadBufferFromRemoteFSGather.cpp -- in readImpl, after current_buf->next() succeeds, assert (when use_external_buffer is set) that current_buf->buffer() lies inside our internal_buffer.
  • src/IO/ReadBufferFromS3.cpp -- in nextImpl, before BufferBase::set(impl->buffer()...), assert (when use_external_buffer is set) that impl->buffer() lies inside our internal_buffer.

Closes: #104692

Related CI report: https://s3.amazonaws.com/clickhouse-test-reports/PRs/105640/9f1efa05d97b0c6bc1c652857999eded33b5d671/stateless_tests_arm_asan_ubsan_azure_sequential/

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

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

...

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.6.1.603

The flaky test 03710_parallel_alter_comment_rename_selects has been failing
intermittently with `server died` while a `SELECT * FROM system.tables`
worker thread was reading table metadata via `readMetadataFile`. The two
known surfacings are different:

* In one occurrence the crash is in the memcpy inside `appendToStringOrVector`
  with `Address not mapped to object` (`SEGV_MAPERR`). The source pointer of
  the memcpy is unmapped.
* In another occurrence (PR ClickHouse#105640, 2026-05-25, aarch64 ASan+UBSan, decoded
  core) the live frames are `LargeMmapAllocator::Deallocate <- Quarantine
  Recycle <- operator delete <- TablesBlockSource::generate
  (StorageSystemTables.cpp:959)`, meaning the `String` returned for one
  per-table `CREATE` query has a corrupt large-allocation header by the time
  the loop iteration frees it.

Both surfacings are consistent with one underlying class of bug: somewhere in
the threadpool remote-fs read chain
(`ReadBufferFromS3` -> `ReadBufferFromRemoteFSGather` ->
`AsynchronousBoundedReadBuffer`) `working_buffer` ends up either inverted
(`end < position`) or extended past the owned `Memory<>`, so
`appendToStringOrVector`'s `s.append(rb.position(), end - rb.position())`
memcpys an arbitrary span and corrupts the destination `String`. The crash
then surfaces immediately at the memcpy (unmapped source) or much later when
the oversized `String` is freed.

A core dump at the FREE site cannot reveal the WRITE site, and we have not
been able to reproduce the failure locally with several heavy
MinIO+plain_rewritable+ASan stress runs.

Per @alexey-milovidov's request on issue ClickHouse#104692, this PR adds targeted
`chassert` calls along the threadpool remote-fs metadata read chain. They are
no-ops in release builds. They should fire on the WRITE site of the
corruption with a deterministic stack trace the next time CI hits this in a
debug or sanitizer build, so we can identify the exact mechanism instead of
guessing.

Asserts:

* `src/IO/ReadHelpers.cpp` -- in all three `appendToStringOrVector` overloads,
  assert that `end >= rb.position()`, `end <= rb.buffer().end()`, and
  `rb.position() >= rb.buffer().begin()`. Catches inverted or escaped
  `working_buffer` at the consumer side, regardless of which inner buffer
  produced it.
* `src/Disks/IO/AsynchronousBoundedReadBuffer.cpp` -- in `nextImpl`, where
  `working_buffer` is set from the `IAsynchronousReader::Result`, assert
  `result.offset <= result.size` and (when not using the page cache)
  `result.size <= memory.size()` and `result.buf == memory.data()`. Catches
  the case where the inner Gather/S3 chain returned a range that exceeds or
  doesn't match the owned `Memory<>`.
* `src/Disks/IO/ReadBufferFromRemoteFSGather.cpp` -- in `readImpl`, after
  `current_buf->next()` succeeds, assert (when `use_external_buffer` is set)
  that `current_buf->buffer()` lies inside our `internal_buffer`.
* `src/IO/ReadBufferFromS3.cpp` -- in `nextImpl`, before
  `BufferBase::set(impl->buffer()...)`, assert (when `use_external_buffer` is
  set) that `impl->buffer()` lies inside our `internal_buffer`.

Closes: ClickHouse#104692

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

groeneai commented Jun 7, 2026

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? No. Despite four rounds of heavy local stress (MinIO + plain_rewritable + ASan, hundreds of iterations, multiple race shapes against system.tables), the bug does not reproduce. CIDB shows ~47 hits in 90 days across the entire CI fleet, last on 2026-05-25 -- it is rare even at fleet scale. This PR is therefore not a fix; it is a diagnostic instrument requested by @alexey-milovidov on issue #104692 ("yes, let's add more asserts"). The asserts pin the WRITE site of the corruption so the next CI occurrence produces a deterministic stack trace.
b Root cause explained? Partial. The unifying view across the 2026-05-12 stack (memcpy unmapped source) and the 2026-05-25 decoded core (Quarantine::Recycle / operator delete of an StorageSystemTables.cpp:959 per-table String) is that somewhere in the threadpool remote-fs chain (ReadBufferFromS3 -> ReadBufferFromRemoteFSGather -> AsynchronousBoundedReadBuffer) working_buffer becomes inverted or escapes its owned Memory<>. appendToStringOrVector then memcpys an arbitrary span into the destination String, corrupting its heap header. The crash surfaces either immediately (memcpy unmapped source) or later (free of the oversized chunk). Why the bounds become corrupt remains unknown -- exactly what these asserts are meant to find.
c Fix matches root cause? N/A (no code fix). The asserts encode the existing invariant that the consumer-visible working_buffer must lie within the buffer the caller / outer wrapper owns. They are placed at every level of the chain so the first place the invariant breaks fires the assert. They do not change behavior; in release builds chassert is a no-op.
d Test intent preserved / new tests added? N/A. No tests are modified. No regression test added because the bug does not reproduce. The asserts are intentionally placed in code paths that the existing flaky test exercises in CI sanitizer/debug builds.
e Both directions demonstrated? Partially demonstrated. The asserts compiled clean, the resulting ASan binary works (SELECT 1, basic local-disk read paths via clickhouse-local -- asserts do not false-positive on healthy reads). Cannot demonstrate that the asserts catch the bug because the bug does not reproduce locally; that is the entire reason for shipping them.
f Fix is general, not a narrow patch? Yes -- asserts are placed at every layer of the threadpool remote-fs read chain (ReadHelpers::appendToStringOrVector consumer, AsynchronousBoundedReadBuffer::nextImpl outer wrapper, ReadBufferFromRemoteFSGather::readImpl middle wrapper, ReadBufferFromS3::nextImpl inner producer), not only at the symptom site. Whichever layer first violates the bounds invariant fires its own assert, so the resulting CI stack should pinpoint the WRITE site rather than the consumer. The asserts also cover all consumers of the chain, not only the metadata-read path.

Session id: cron:clickhouse-ci-task-worker:20260607-024400

@groeneai

groeneai commented Jun 7, 2026

Copy link
Copy Markdown
Collaborator Author

cc @kssenii @alesapin -- could you review this? Per @alexey-milovidov on issue #104692, this adds diagnostic chasserts along the threadpool remote-fs read chain (ReadBufferFromS3 -> ReadBufferFromRemoteFSGather -> AsynchronousBoundedReadBuffer -> appendToStringOrVector) so the next CI occurrence of the 03710_parallel_alter_comment_rename_selects server died produces a deterministic write-site stack instead of the current free-site core. No behavior change; chassert is a no-op in release. 4 files, 56 insertions.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jun 7, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [382ae4a]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) FAIL
04295_04278_materialized_cte_in_union_runtime_set FAIL cidb IGNORED
02345_implicit_transaction NOT_FAILED cidb IGNORED
03707_statistics_cache NOT_FAILED cidb IGNORED

AI Review

Summary

This PR adds diagnostic chassert coverage around the remote filesystem metadata read path so debug and sanitizer builds can stop closer to a corrupt working_buffer producer instead of later in appendToStringOrVector. The earlier bot findings about SwapHelper ownership and unsafe pointer-range predicates are fixed in the current head, and I did not find any remaining correctness issue worth an inline comment.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Jun 7, 2026
…assert

`clickhouse-gh[bot]` flagged the diagnostic chasserts added in the previous
commit on `src/Disks/IO/ReadBufferFromRemoteFSGather.cpp`. While `SwapHelper`
is in scope, `internal_buffer` and `working_buffer` are exchanged between
`this` and `current_buf`, so `this->internal_buffer` is the OLD inner buffer
of `current_buf` (often empty/null when both readers use external buffers),
not the caller-provided external buffer. Comparing `current_buf->buffer`
against `this->internal_buffer` therefore fired on healthy reads.

Compare `current_buf->buffer` against `current_buf->internalBuffer` instead,
which is the post-swap location of the external buffer for the duration of
the helper's scope. Same diagnostic intent, same coverage, no false
positives on valid reads.

Bot review: ClickHouse#106657 (comment)

Tracking: ClickHouse#104692

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The previous diagnostic chasserts in ReadBufferFromRemoteFSGather::readImpl
and ReadBufferFromS3::nextImpl computed `Buffer::size()` and
`begin() + size()` on the very range they were trying to validate.
`Buffer::size()` is `end_pos - begin_pos`; if that range is inverted or
its begin/end come from different allocations (the failure shape this
diagnostic is meant to catch on issue ClickHouse#104692), the unsigned subtraction
returns a huge value and `begin + size` then overflows the pointer space
before `chassert` ever reports the bug. The diagnostic could therefore
miss exactly the corruption it is intended to detect, which defeats its
purpose.

Replace the predicates with `assertWorkingBufferContainedIn`, a small
file-scope helper that compares the four stored pointers as
`uintptr_t` integer addresses. No `Buffer::size` call and no
`begin + size` arithmetic on the untrusted range, so the integer
comparisons cannot themselves trigger UB on a corrupt input. The
diagnostic intent (working buffer must be a sub-range of the
caller-provided external buffer) is preserved.

The same shape is applied to both files. The `BufferBase::set` line in
`ReadBufferFromS3::nextImpl` immediately after the assert is unchanged,
production code we do not modify here.

Bot review reference:
ClickHouse#106657 (comment)

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Comment thread src/IO/ReadHelpers.cpp Resolved
The previous diagnostic chasserts in the three `appendToStringOrVector`
overloads in `src/IO/ReadHelpers.cpp` validated the caller-supplied
`[rb.position(), end)` source range against `rb.buffer()` using relational
pointer comparisons (`end >= rb.position()`, `end <= rb.buffer().end()`,
`rb.position() >= rb.buffer().begin()`). C++ relational comparisons
between pointers from different allocations are UB; if `working_buffer`
is corrupt and `end` / `position` / `buffer().{begin,end}` come from
different allocations (the failure shape this diagnostic is meant to
catch on issue ClickHouse#104692), the predicates can themselves trigger UB before
`chassert` ever reports the bug. The diagnostic could therefore miss
the very corruption it is intended to detect, which defeats its purpose.

This is the same bug class fixed in `74dfd4b9fcd1` for the producer-side
asserts in `ReadBufferFromRemoteFSGather` and `ReadBufferFromS3`. Apply
the same shape here: extract a file-scope helper that compares the four
pointers as `uintptr_t` integer addresses. No relational pointer
comparisons on the untrusted range, so the integer comparisons cannot
trigger UB on a corrupt input. The diagnostic intent (the source range
must lie inside the working buffer) is preserved.

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

clickhouse-gh Bot commented Jun 8, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.60% 84.50% -0.10%
Functions 92.30% 92.30% +0.00%
Branches 77.20% 77.20% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 47/50 (94.00%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 1 line(s) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Jun 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI ledger (HEAD 382ae4ab9de)

Workflow finished. One failure, classified flaky, not PR-caused.

check test classification disposition
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) 04295_04278_materialized_cte_in_union_runtime_set flaky tracked separately as task; 9 unrelated PRs hit this in last 30d (#91583, #102308, #104625, #106178, #100177, #106634, #96886) plus 1 master hit. Failure is UNKNOWN_TABLE: _materialized_cte_ct_* from QueryAnalyzer::initializeQueryJoinTreeNode — a CTE/analyzer race. This PR only modifies Disks/IO read paths (ReadBufferFromRemoteFSGather, AsynchronousBoundedReadBuffer, ReadBufferFromS3, ReadHelpers); no analyzer or CTE code touched.

PR ready for re-review.

@Algunenano
Algunenano added this pull request to the merge queue Jun 10, 2026
Merged via the queue into ClickHouse:master with commit ff9dc27 Jun 10, 2026
164 of 166 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 Jun 10, 2026
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 pr-ci 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.

Flaky test: 03710_parallel_alter_comment_rename_selects

4 participants