Repository navigation
Add diagnostic bounds asserts in threadpool remote-fs metadata read path (#104692) - #106657
Conversation
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]>
Pre-PR validation gate
Session id: cron:clickhouse-ci-task-worker:20260607-024400 |
|
cc @kssenii @alesapin -- could you review this? Per @alexey-milovidov on issue #104692, this adds diagnostic |
|
Workflow [PR], commit [382ae4a] Summary: ❌
AI ReviewSummaryThis PR adds diagnostic Final VerdictStatus: ✅ Approve |
…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]>
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]>
LLVM Coverage Report
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 |
CI ledger (HEAD
|
| 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.
ff9dc27
The flaky test
03710_parallel_alter_comment_rename_selectsfails intermittently withserver diedwhile aSELECT * FROM system.tablesworker thread reads table metadata viareadMetadataFile. The two known surfacings look different but are both consistent with one underlying bug class.appendToStringOrVector, withAddress not mapped to object/SEGV_MAPERR-- the source pointer of the memcpy is unmapped.LargeMmapAllocator::DeallocatefromQuarantine::Recyclefromoperator deletefromTablesBlockSource::generate(StorageSystemTables.cpp:959) -- the per-tableStringreturned for oneCREATEquery 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_bufferends up either inverted (end < position) or extended past the ownedMemory<>. ThenappendToStringOrVector'ss.append(rb.position(), end - rb.position())memcpys an arbitrary span and corrupts the destinationString. The crash surfaces either at the memcpy (unmapped source) or much later when the oversizedStringis 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
chassertcalls 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 threeappendToStringOrVectoroverloads, assertend >= rb.position(),end <= rb.buffer().end(), andrb.position() >= rb.buffer().begin(). Catches an inverted or escapedworking_bufferat the consumer side regardless of which inner buffer produced it.src/Disks/IO/AsynchronousBoundedReadBuffer.cpp-- innextImpl, whereworking_bufferis set from theIAsynchronousReader::Result, assertresult.offset <= result.sizeand (when the page cache is not in use)result.size <= memory.size()andresult.buf == memory.data(). Catches the case where the inner Gather/S3 chain returned a range that exceeds or doesn't match the ownedMemory<>.src/Disks/IO/ReadBufferFromRemoteFSGather.cpp-- inreadImpl, aftercurrent_buf->next()succeeds, assert (whenuse_external_bufferis set) thatcurrent_buf->buffer()lies inside ourinternal_buffer.src/IO/ReadBufferFromS3.cpp-- innextImpl, beforeBufferBase::set(impl->buffer()...), assert (whenuse_external_bufferis set) thatimpl->buffer()lies inside ourinternal_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):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
...
Documentation entry for user-facing changes
Version info
26.6.1.603