Skip to content

Fix data race in CachedOnDiskReadBufferFromFile::getInfoForLog - #110154

Merged
kssenii merged 19 commits into
masterfrom
fix-cached-read-buffer-getinfoforlog-race
Jul 16, 2026
Merged

kssenii merged 19 commits into
masterfrom
fix-cached-read-buffer-getinfoforlog-race

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jul 12, 2026 •

Copy link
Copy Markdown
Member

Fixes a ThreadSanitizer data race reported on master in
DB::BufferBase::Buffer::end(), read from
CachedOnDiskReadBufferFromFile::getInfoForLog (state->buf->available())
while another thread was mutating the same buffer via state->buf->set() in
nextImplStep.

state->buf is a shared pointer to a file segment's remote reader (e.g.
ReadBufferFromS3), shared across readers through
FileSegment::getRemoteFileReader/setRemoteFileReader and synchronized only
by the segment's downloader election. A downloader's term lasts a single
nextImpl() call; after completePartAndResetDownloader another thread may
become the downloader of the same segment and reuse the very same reader. Our
state kept referencing it, so when the next step re-elected a downloader via
state = prepareReadFromFileSegmentState(...) and that call threw, the
SCOPE_EXIT diagnostics in nextImplStep (getInfoForLog) read the reader's
buffer pointers without synchronization while the new downloader mutated them.

The fix releases 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 never touches 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.

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 the
exception-path ownership handoffs (truncated-object detection mid-read, during
predownload and under readBigAt, a source failing mid-read, and cached reads
executed while an unrelated exception is being unwound), and
FileSegment::setDownloadFinishedWithoutContinuation chasserts that the caller
withdrew the remote reader before publishing
PARTIALLY_DOWNLOADED_NO_CONTINUATION. Writing these tests exposed a
pre-existing self-deadlock in readBigAt after a partial read of a file
segment (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):

  • 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)

🤖 Generated with Claude Code

Version info

  • Merged into: 26.7.1.1043 (included in 26.7 and later)

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]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6f0434e]

Summary: ✅


AI Review

Summary

This PR hardens CachedOnDiskReadBufferFromFile around downloader handoff and exception unwinds, adds the missing remote-reader withdrawals on the PARTIALLY_DOWNLOADED_NO_CONTINUATION paths, fixes the readBigAt self-deadlock exposed by those paths, and adds focused FileCacheTest.CachedReadBuffer* coverage. I reread the current diff and all prior review threads on the latest head and did not find any remaining correctness or safety issues in the touched paths.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Jul 12, 2026
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]>
alexey-milovidov and others added 2 commits July 12, 2026 16:54
…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]>
alexey-milovidov and others added 2 commits July 12, 2026 21:52
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

CI note: the only red is Upgrade check (amd_release) → Error message in clickhouse-server.log, flagging

<Error> DB::DatabasePostgreSQL::getTablesIterator: Code: 614. DB::Exception: Try 2. Connection to `192.0.2.1:5432` failed ... timeout expired

This is unrelated to this change (which only touches CachedOnDiskReadBufferFromFile). 192.0.2.1 is the RFC 5737 documentation address a test points a PostgreSQL database engine at, and the tolerated connection-timeout is logged at <Error> level, which the upgrade check treats as unexpected. It is a master-wide flaky — 7 PRs hit it on 2026-07-12, 4 on 07-11, 9 on 07-10. A fix is already in progress: it is being addressed by #109472 (log tolerated remote MySQL/PostgreSQL connection failures as warnings) and #109350 (allowlist this exact getTablesIterator upgrade-check message). Branch was merged up to master so fresh CI runs.

alexey-milovidov and others added 2 commits July 13, 2026 02:32
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

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 SCOPE_EXIT guards added in earlier commits used std::uncaught_exceptions() > 0 to mean "readFromFileSegment threw". That predicate is actually 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 to nextImplStep, so the inner SCOPE_EXIT wrongly ran state.reset() even though the read completed normally, and the subsequent state->read_type dereferenced an empty optional.

Fix: capture std::uncaught_exceptions() on scope entry and compare the exit count against that baseline, so each guard fires only for an exception thrown within its scope. Applied to all five sites in nextImplStep and readBigAt. This path is exercised by 02345_implicit_transaction on the s3-storage shards, which reproduced the crash.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

CI note: the only red before this refresh was the Stress test (amd_debug) Logical error: Block structure mismatch in JoinStep: [__table3.number, __table3.number] and [__table3.number] stream: different number of columns (STID 0993-386d).

This is unrelated to this change (which only touches CachedOnDiskReadBufferFromFile). The assertion fires in JoinStep::updatePipeline / InterpreterSelectQueryAnalyzer during query-pipeline construction — nothing on the FileCache path. It is a known master-wide flaky in the analyzer/JoinStep pipeline that has hit many unrelated PRs over the last two weeks (e.g. #110178, #109940, #109536, #109433, #107567, #109097, #107236), always in Stress tests. It is tracked by the open issue #109215 (same "Block structure mismatch in A stream: different number of columns" class), which has no fix merged to master yet.

Merged master to refresh CI on an up-to-date base.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

CI note: on the previous head (d92f61c) the reds were:

  1. 02346_text_index_bug108519_qcc_skip_index on six stateless shards — the CI harness minimized it to the randomized setting materialize_statistics_on_insert = 1, unrelated to this PR. The fix merged to master today in Fix flaky 02346_text_index_bug108519_qcc_skip_index under randomized statistics #110260, so I merged master to pull it in and refresh CI.
  2. test_replicated_database/test.py::test_replicated_table_structure_alter on two integration shards — known flaky Flaky test: test_replicated_database/test.py::test_replicated_table_structure_alter (regression since 2026-07-10) #110036 (auto-labeled by CI), fix in progress in Converge kept matching-UUID table structure on Replicated database recovery #110145.

No changes to this PR's own files; the merge is a pure CI refresh.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

CI note: on the previous head (22a56e1c) the only red was Integration tests (amd_msan, 7/8) → test_replicated_database/test.py::test_replicated_table_structure_alter (assert '1\t2\t3\n' == '1\t2\n'), the known master-wide flaky tracked by #110036 (auto-labeled issue/retry_ok; fix #110145 still open, not yet on master). The PR's own change is unrelated to Replicated database recovery.

The branch was 170 commits behind master and red, so I merged origin/master to refresh CI. The merge is conflict-free and the PR's only file (src/Disks/IO/CachedOnDiskReadBufferFromFile.cpp) is byte-identical to the previous head, so this is a pure CI refresh. No dup fix PR / no ping for #110036 (already tracked, fix in progress in #110145).

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.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Addressed the review: added focused regression tests for the exception-path reader handoffs (FileCacheTest.CachedReadBuffer*), an invariant chassert in FileSegment::setDownloadFinishedWithoutContinuation, and a fix for a pre-existing self-deadlock the new tests exposed in readBigAt after a partial segment read — see the review thread for details and the mutation-testing evidence.

CI note: on the previous head (25ec1c97) the reds were 01730_distributed_group_by_no_merge_order_by_long (MEMORY_LIMIT_EXCEEDED in AggregatingTransform with distributed_group_by_no_merge=2) and the known test_replicated_table_structure_alter flaky #110036. The 01730 failure is master-wide — CIDB shows it on master itself (PR=0) and on ~20 unrelated PRs on 2026-07-14 across amd_tsan/amd_asan_ubsan/amd_debug/arm_binary, while this PR only touches the filesystem-cache read path — and it has no failures recorded today, so I merged master (1020 commits behind, conflict-free, no changes to this PR's files from the master side) to refresh CI on top of whatever settled it.

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
@alexey-milovidov

Copy link
Copy Markdown
Member Author

CI note: on the previous head (26df64b) the two reds were:

  1. Build (arm_tidy): clang-analyzer-deadcode.DeadStores on the custom RunOnDestroy guard in the new CachedReadBufferReadDuringExceptionUnwinding unit test (a direct aggregate initialization from a lambda has no side effects visible to the analyzer). Fixed in d51ecf2 by using the idiomatic SCOPE_EXIT instead, whose make_scope_guard initializer the analyzer treats as opaque.
  2. Style check: the analyzer-wording check flagged 04402_with_fill_interpolate_fill_column_overlap.sql, which is not part of this PR — the branch had merged master between the commit that introduced that file and the wording fix 79959bf. Merged master (c132265) to pull the fix in.

All 34 FileCacheTest.* unit tests pass locally on the new head.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110154&sha=26df64b34f88b98d148ca4febbf9b01b44af179b&name_0=PR

@alexey-milovidov

Copy link
Copy Markdown
Member Author

CI note: on the previous head (c1322654) the reds were:

  1. Three flaky stateless tests (03216_arrayWithConstant_limits, 02477_single_value_data_string_regression, 04033_tpc_ds_q13), all already labeled flaky by the harness; 03216_arrayWithConstant_limits was confirmed flaky by rerun (1/4 failed with a randomized-settings memory limit).
  2. The known master-wide flaky test_replicated_database/test.py::test_replicated_table_structure_alter (issue Flaky test: test_replicated_database/test.py::test_replicated_table_structure_alter (regression since 2026-07-10) #110036, retry_ok).
  3. Docker server image failing to build head-arm64/head-distroless-arm64 (apt-get install returning "Package 'busybox' has no installation candidate") — a transient Ubuntu package-mirror issue, unrelated to this change.

None of these touch FileCache/CachedOnDiskReadBufferFromFile. The branch was 144 commits behind master, so I merged master to refresh CI. The merge is conflict-free and doesn't touch this PR's own files (CachedOnDiskReadBufferFromFile.cpp, FileSegment.cpp, gtest_filecache.cpp); rebuilt dbms + unit_tests_dbms locally and all 34 FileCacheTest.* (including the CachedReadBuffer* regressions) pass.

@clickhouse-gh

clickhouse-gh Bot commented Jul 16, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.80% 85.90% +0.10%
Functions 92.70% 92.70% +0.00%
Branches 78.00% 78.10% +0.10%

Changed lines: Changed C/C++ lines covered: 327/328 (99.70%) · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov requested a review from kssenii July 16, 2026 14:19
@kssenii kssenii self-assigned this Jul 16, 2026
@kssenii
kssenii added this pull request to the merge queue Jul 16, 2026
Merged via the queue into master with commit befb96d Jul 16, 2026
179 checks passed
@kssenii
kssenii deleted the fix-cached-read-buffer-getinfoforlog-race branch July 16, 2026 15:52
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 16, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
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
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…buffer-getinfoforlog-race

Fix data race in CachedOnDiskReadBufferFromFile::getInfoForLog
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

3 participants