Repository navigation
Fix data race in CachedOnDiskReadBufferFromFile::getInfoForLog - #110154
Conversation
TSan reported a data race in `DB::BufferBase::Buffer::end()`, read from `CachedOnDiskReadBufferFromFile::getInfoForLog` (via `state->buf->available()`) racing with `state->buf->set()` in `nextImplStep` on another thread. `state->buf` is a shared pointer to a file segment's remote reader (e.g. `ReadBufferFromS3`), which is shared across readers through `FileSegment::getRemoteFileReader`/`setRemoteFileReader`. Access to it is only synchronized via the file segment's downloader election: a downloader's term lasts a single `nextImpl()` call, after which `completePartAndResetDownloader` releases it and another thread may become the downloader of the same segment and reuse the very same remote reader. However, our `state` kept referencing that reader. When the next step re-elected a downloader via `state = prepareReadFromFileSegmentState(...)` and that call threw, `state` still pointed at the reader now owned and mutated by the new downloader, and the diagnostics in `nextImplStep`'s `SCOPE_EXIT` (`getInfoForLog`) read its buffer pointers without synchronization. Release `state` (and thus our reference to the current segment's remote reader) before completing/popping the segment and before re-electing a downloader, so a throw leaves `state` empty and `getInfoForLog` does not touch a reader that another thread may now own. This mirrors the `readBigAt` path, which already resets its state between segments. The actual data reads were already safe (serialized by downloader election); only the diagnostic read was racy. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=19be9d5978685366017f194dc022c6a63ac5b17a&name_0=MasterCI&name_1=Stateless%20tests%20%28amd_tsan%2C%20s3%20storage%2C%20sequential%2C%202%2F2%29 Co-Authored-By: Claude Fable 5 <[email protected]>
|
Workflow [PR], commit [6f0434e] Summary: ✅
AI ReviewSummaryThis PR hardens Final Verdict
|
The `clickhouse-gh` review pointed out that in `completeFileSegmentAndGetNext` the `state.reset()` was still too late: `appendFilesystemCacheLog` ran before it. By the time we enter this helper, `nextImplStep` has already released downloader ownership via `completePartAndResetDownloader`, so another thread may become the downloader of the same segment and start mutating the reused remote reader. `cache_log->add` reaches `SystemLogBase::add`, which copies several strings and can throw `bad_alloc`; on that throw `nextImplStep`'s `SCOPE_EXIT` calls `getInfoForLog`, which would still dereference the stale shared `state->buf` — reproducing the same data race on the exception path. Snapshot `state->read_type` into `completed_read_type`, `state.reset()` before any potentially-throwing work, and pass the snapshot to `appendFilesystemCacheLog`. Now no throwing work in this helper runs while `state` still references a reader another thread may own. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…diagnostics The `clickhouse-gh` review pointed out that the earlier `state.reset()` calls covered only the segment-rollover (`completeFileSegmentAndGetNext`) and downloader re-election (`updateReadStateIfNeeded`) paths. Inside `readFromFileSegment` the predownload, `PARTIALLY_DOWNLOADED_NO_CONTINUATION` and bypass paths call `completePartAndResetDownloader`/`setDownloadFinishedWithoutContinuation` while `state->buf` still points at the shared remote reader, before swapping in a non-shared bypass buffer. Once downloader ownership is released, another reader can pick up the same reader (via `FileSegment::extractRemoteFileReader` / `getRemoteFileReader`) and start mutating it. If any of the later calls on those paths throws (e.g. `getRemoteReadBuffer` or `seek` while setting up the bypass buffer, or the predownload failure itself), `nextImplStep` unwinds and both the inner `SCOPE_EXIT`'s `state->buf->set(nullptr, 0)` (a write) and the enclosing `SCOPE_EXIT`'s `getInfoForLog` (a read of `state->buf`) touch a reader that another thread now owns — reproducing the same data race. The `readFromFileSegment` call is bracketed by an inner `SCOPE_EXIT` in `nextImplStep` (and an analogous one in `readBigAt`). On normal completion we still exclusively own `state->buf` — we are the segment's downloader (ownership is only released later, at the end of `nextImplStep`), or it is a non-shared bypass/cache reader — so un-borrowing our `internal_buffer` from it is safe. On the exception path the reader may already have been released, so drop our reference to it (`state.reset()` in `nextImplStep`) / skip the `set` (in `readBigAt`) instead of touching it. With `state` cleared, the enclosing `SCOPE_EXIT`'s `getInfoForLog` sees an empty `state` and no longer dereferences the stale shared `state->buf`. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…leasing it in predownload `predownloadForFileSegment` published `PARTIALLY_DOWNLOADED_NO_CONTINUATION` via `setDownloadFinishedWithoutContinuation` while the shared remote reader was still registered in the `FileSegment`. From that moment another thread (a waiter going bypass via `extractRemoteFileReader`, or the background download in `CacheMetadata::downloadImpl`) could take the reader and start mutating it, while this frame still read `state.buf` in the diagnostics of the truncation / predownload-failure throw path (`eof` may even call `next`) and restored its internal buffer in the `SCOPE_EXIT` — a data race. Withdraw the reader with `resetRemoteFileReader` (only the downloader may do it) before publishing the state, so this frame owns the reader exclusively afterwards. On the predownload-to-bypass path (`completePartAndResetDownloader` after a failed reservation or cache write) the reader had already been withdrawn by `FileSegment::setDownloadFailedUnlocked`, so the buffer restore and the `swap` handoff in `readFromFileSegment` were already race-free; withdraw it explicitly anyway so the invariant does not silently depend on that distant reset. Co-Authored-By: Claude Fable 5 <[email protected]>
…ore releasing the downloader `readBigAt`'s outer `SCOPE_EXIT` released downloader ownership via `completePartAndResetDownloader` without first withdrawing the shared remote reader from the `FileSegment`, unlike the matching cleanup in `nextImplStep`. If `readFromFileSegment` throws while this frame is still the downloader (for example the truncated-object path that calls `setDownloadFinishedWithoutContinuation` and throws `CANNOT_READ_ALL_DATA`), the inner `SCOPE_EXIT` leaves the reader still borrowing the caller's `to` buffer (it only un-borrows via `set(nullptr, 0)` on normal completion). Once downloader ownership is released on the `PARTIALLY_DOWNLOADED_NO_CONTINUATION` path, a bypass waiter can take that reader via `FileSegment::extractRemoteFileReader` and race on (and outlive) the stale `to` buffer. Withdraw the reader with `resetRemoteFileReader` before `completePartAndResetDownloader` on the exception path (and when the implementation buffer cannot be reused), mirroring `nextImplStep`. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…fer-getinfoforlog-race
|
CI note: the only red is This is unrelated to this change (which only touches |
…ion unwinds The `SCOPE_EXIT` blocks in `CachedOnDiskReadBufferFromFile::nextImplStep` and `readBigAt` used `std::uncaught_exceptions() > 0` to decide whether the scope was exiting because `readFromFileSegment` threw. That predicate is true whenever *any* exception is in flight, including an outer one being unwound *through* this frame. A cached read on an s3-backed disk can be issued from a destructor during rollback: `MutatePlainMergeTreeTask::executeStep` -> `MergeTreeData::Transaction::~Transaction` -> `rollback` -> `VersionMetadataOnDisk::readMetadataUnlocked` -> `readFile` -> `nextImplStep`. When the mutation failed and the transaction is destroyed while its own exception unwinds, `std::uncaught_exceptions()` is already `> 0` on entry, so the inner `SCOPE_EXIT` wrongly ran `state.reset()` even though the read completed normally, and the following `state->read_type` then dereferenced an empty optional -> a segmentation fault (server died). Capture `std::uncaught_exceptions()` on scope entry and compare the count at scope exit against that baseline, so the guards fire only for an exception thrown *within* the scope, not for one merely being unwound through it. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110154&sha=1d77e62f6a22f076d6c47209dd6ef0e62035f528&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20distributed%20plan%2C%20s3%20storage%2C%20parallel%29 PR: #110154 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…hes NO_CONTINUATION In `readFromFileSegment`, the zero-byte remote-truncation branch called `setDownloadFinishedWithoutContinuation` while the shared remote reader was still registered in the `FileSegment` (and, in the `readBigAt` path, still borrowing the caller's `to` buffer). That state transition publishes `PARTIALLY_DOWNLOADED_NO_CONTINUATION` and wakes waiters, and `FileSegment::extractRemoteFileReader` is only state-gated (not downloader-gated), so a bypass waiter could move the reader out and start mutating it in the window before the outer `SCOPE_EXIT` cleanup withdrew it -- a data race reachable from both `nextImplStep` and `readBigAt`. Withdraw the reader with `resetRemoteFileReader` before publishing the state change, so this frame owns it exclusively. This mirrors the handling already added to `predownloadForFileSegment`. PR: #110154 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Also fixed a segmentation fault (server died) that this PR had introduced, seen on the s3-storage stateless shards (amd_debug and amd_llvm_coverage), commit 2f74bfe. The When the mutation failed and the transaction is destroyed while its own exception unwinds, Fix: capture |
…fer-getinfoforlog-race
…fer-getinfoforlog-race
|
CI note: the only red before this refresh was the This is unrelated to this change (which only touches Merged |
…fer-getinfoforlog-race
|
CI note: on the previous head (d92f61c) the reds were:
No changes to this PR's own files; the merge is a pure CI refresh. |
|
CI note: on the previous head ( The branch was 170 commits behind master and red, so I merged |
Unlike the `nextImpl` path, which completes the downloaded part and releases downloader ownership after every step, `readBigAt` stays the downloader of a file segment until the whole call completes. After a partial read of a segment (e.g. the remote object turned out to be shorter than expected), the next loop iteration called `updateReadStateIfNeeded`, which re-runs `prepareReadFromFileSegmentState` -- a function that may only be called by a non-downloader (it chasserts that, and on a DOWNLOADING segment it waits for the downloader to make progress). Waiting for ourselves means waiting forever: an exception in debug and sanitizer builds, an infinite loop of 60-second `FileSegment::wait` slices in release builds. In particular, a remote object truncated between listing and reading could never reach the `CANNOT_READ_ALL_DATA` branch of `readFromFileSegment` through `readBigAt`. Keep reading with the existing state when this frame is still the segment's downloader: it is intact and positioned at the current download offset, so the next `readFromFileSegment` either reads further or reports the truncation. Found by the new `FileCacheTest.CachedReadBufferTruncatedObjectReadBigAt` unit test, added in the next commit.
Address the review: the exception-only ownership-handoff paths of `CachedOnDiskReadBufferFromFile` (the `predownloadForFileSegment` and `readFromFileSegment` truncation release sites and the `readBigAt` cleanup) were not covered by any test that would fail deterministically if one of the new `resetRemoteFileReader` calls or the `std::uncaught_exceptions` baseline guards were removed. New unit tests (`FileCacheTest.CachedReadBuffer*`) drive a cached read over a source that imitates a remote object truncated between listing and reading (detected mid-read, during predownload, and under `readBigAt`) and a source that fails mid-read, and assert that the failing downloader releases the segment as `PARTIALLY_DOWNLOADED_NO_CONTINUATION` with the shared remote reader withdrawn, that the segment stays usable afterwards, and that the propagated error is a retryable `CANNOT_READ_ALL_DATA` rather than a logical error. A separate test performs cached reads from a destructor while an unrelated exception is being unwound -- the scenario in which a plain `std::uncaught_exceptions() > 0` check instead of the entry-baseline comparison broke an earlier revision of this fix with a null dereference -- and would fail deterministically on such a regression. `FileSegment::setDownloadFinishedWithoutContinuation` now chasserts, at the publication point itself, that the caller has withdrawn the remote reader first: on the `nextImpl` paths a removed withdrawal would otherwise be masked in the segment's final state by the later cleanup in `nextImplStep` (the hazard is the window between publishing the state and that cleanup, which a concurrent reader can exploit), so the chassert turns any such regression into a deterministic failure of these tests in debug and sanitizer builds.
…fer-getinfoforlog-race
|
Addressed the review: added focused regression tests for the exception-path reader handoffs ( CI note: on the previous head ( |
clang-tidy (`clang-analyzer-deadcode.DeadStores`) flagged the custom `RunOnDestroy` guard as a dead initialization, because a direct aggregate initialization from a lambda has no side effects visible to the analyzer. `SCOPE_EXIT` initializes the guard through `make_scope_guard`, which the analyzer treats as opaque, and is the idiomatic guard in this codebase anyway. https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110154&sha=26df64b34f88b98d148ca4febbf9b01b44af179b&name_0=PR&name_1=Build%20%28arm_tidy%29 #110154
…fer-getinfoforlog-race
|
CI note: on the previous head (26df64b) the two reds were:
All 34 |
…fer-getinfoforlog-race
|
CI note: on the previous head (
None of these touch |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 327/328 (99.70%) · Uncovered code |
…ion unwinds The `SCOPE_EXIT` blocks in `CachedOnDiskReadBufferFromFile::nextImplStep` and `readBigAt` used `std::uncaught_exceptions() > 0` to decide whether the scope was exiting because `readFromFileSegment` threw. That predicate is true whenever *any* exception is in flight, including an outer one being unwound *through* this frame. A cached read on an s3-backed disk can be issued from a destructor during rollback: `MutatePlainMergeTreeTask::executeStep` -> `MergeTreeData::Transaction::~Transaction` -> `rollback` -> `VersionMetadataOnDisk::readMetadataUnlocked` -> `readFile` -> `nextImplStep`. When the mutation failed and the transaction is destroyed while its own exception unwinds, `std::uncaught_exceptions()` is already `> 0` on entry, so the inner `SCOPE_EXIT` wrongly ran `state.reset()` even though the read completed normally, and the following `state->read_type` then dereferenced an empty optional -> a segmentation fault (server died). Capture `std::uncaught_exceptions()` on scope entry and compare the count at scope exit against that baseline, so the guards fire only for an exception thrown *within* the scope, not for one merely being unwound through it. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110154&sha=1d77e62f6a22f076d6c47209dd6ef0e62035f528&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20distributed%20plan%2C%20s3%20storage%2C%20parallel%29 PR: ClickHouse#110154 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…hes NO_CONTINUATION In `readFromFileSegment`, the zero-byte remote-truncation branch called `setDownloadFinishedWithoutContinuation` while the shared remote reader was still registered in the `FileSegment` (and, in the `readBigAt` path, still borrowing the caller's `to` buffer). That state transition publishes `PARTIALLY_DOWNLOADED_NO_CONTINUATION` and wakes waiters, and `FileSegment::extractRemoteFileReader` is only state-gated (not downloader-gated), so a bypass waiter could move the reader out and start mutating it in the window before the outer `SCOPE_EXIT` cleanup withdrew it -- a data race reachable from both `nextImplStep` and `readBigAt`. Withdraw the reader with `resetRemoteFileReader` before publishing the state change, so this frame owns it exclusively. This mirrors the handling already added to `predownloadForFileSegment`. PR: ClickHouse#110154 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
clang-tidy (`clang-analyzer-deadcode.DeadStores`) flagged the custom `RunOnDestroy` guard as a dead initialization, because a direct aggregate initialization from a lambda has no side effects visible to the analyzer. `SCOPE_EXIT` initializes the guard through `make_scope_guard`, which the analyzer treats as opaque, and is the idiomatic guard in this codebase anyway. https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110154&sha=26df64b34f88b98d148ca4febbf9b01b44af179b&name_0=PR&name_1=Build%20%28arm_tidy%29 ClickHouse#110154
…buffer-getinfoforlog-race Fix data race in CachedOnDiskReadBufferFromFile::getInfoForLog
Fixes a ThreadSanitizer data race reported on master in
DB::BufferBase::Buffer::end(), read fromCachedOnDiskReadBufferFromFile::getInfoForLog(state->buf->available())while another thread was mutating the same buffer via
state->buf->set()innextImplStep.state->bufis a shared pointer to a file segment's remote reader (e.g.ReadBufferFromS3), shared across readers throughFileSegment::getRemoteFileReader/setRemoteFileReaderand synchronized onlyby the segment's downloader election. A downloader's term lasts a single
nextImpl()call; aftercompletePartAndResetDownloaderanother thread maybecome the downloader of the same segment and reuse the very same reader. Our
statekept referencing it, so when the next step re-elected a downloader viastate = prepareReadFromFileSegmentState(...)and that call threw, theSCOPE_EXITdiagnostics innextImplStep(getInfoForLog) read the reader'sbuffer pointers without synchronization while the new downloader mutated them.
The fix releases
state(and thus our reference to the current segment's remotereader) before completing/popping the segment and before re-electing a
downloader, so a throw leaves
stateempty andgetInfoForLognever touches areader that another thread may now own. This mirrors the
readBigAtpath, whichalready resets its state between segments. The actual data reads were already
safe (serialized by downloader election); only the diagnostic read was racy.
This race started appearing after the FileCache sync (#109203) and has recurred
on master and several unrelated PRs (#108377, #108838, #109459, #101768).
Also, per review: unit tests (
FileCacheTest.CachedReadBuffer*) now cover theexception-path ownership handoffs (truncated-object detection mid-read, during
predownload and under
readBigAt, a source failing mid-read, and cached readsexecuted while an unrelated exception is being unwound), and
FileSegment::setDownloadFinishedWithoutContinuationchasserts that the callerwithdrew the remote reader before publishing
PARTIALLY_DOWNLOADED_NO_CONTINUATION. Writing these tests exposed apre-existing self-deadlock in
readBigAtafter a partial read of a filesegment (re-electing a downloader while still being one), fixed here as well.
CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=19be9d5978685366017f194dc022c6a63ac5b17a&name_0=MasterCI&name_1=Stateless%20tests%20%28amd_tsan%2C%20s3%20storage%2C%20sequential%2C%202%2F2%29
Related: #109203
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
🤖 Generated with Claude Code
Version info
26.7.1.1043(included in26.7and later)