Skip to content

Fix TSAN data race in CachedOnDiskReadBufferFromFile::getInfoForLog - #109359

Closed
groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-cachedondisk-getinfoforlog-tsan-race
Closed

groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-cachedondisk-getinfoforlog-tsan-race

Conversation

@groeneai

@groeneai groeneai commented Jul 3, 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):

Fix a data race in the filesystem cache read path. CachedOnDiskReadBufferFromFile::getInfoForLog() read the working buffer pointers (available, offset, buffer size) of a remote reader that can be shared between file segments and used concurrently by another thread, which could race with the buffer swap in BoundedReadBuffer.

Description

TSAN report from BuzzHouse (amd_tsan):

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108838&sha=2586502fbedc5ab52b2531d82464fb0251bac909&name_0=PR&name_1=BuzzHouse%20%28amd_tsan%29

  • Read of size 8 by the logging path: BufferBase::Buffer::end() <- available() <- CachedOnDiskReadBufferFromFile::getInfoForLog() (src/Disks/IO/CachedOnDiskReadBufferFromFile.cpp).
  • Previous write of size 8 by the read path: std::swap<char*> <- BufferBase::Buffer::swap() <- SwapHelper::~SwapHelper() <- BoundedReadBuffer::nextImpl().

Root cause: getInfoForLog() logged state->buf->available(), ->offset() and ->buffer().size(), all of which read the working_buffer char* pointers non-atomically. state->buf can be a remote reader (BoundedReadBuffer) that is deliberately shared between file segments (see getRemoteReadBuffer), and this logging runs after the buffer is released, while another thread already reads through the shared reader and swaps those pointers via SwapHelper in BoundedReadBuffer::nextImpl().

This is the same class of race that PR #55372 fixed for getFileOffsetOfBufferEnd() by making it atomic and documenting the contract (the buffer is released before logging, so another thread can already use it). The three remaining working-buffer accessors were left unguarded. This change logs only getFileOffsetOfBufferEnd() here, which is atomic, and leaves a NOTE explaining why the other accessors must not be read.

getInfoForLog() read state->buf->available(), offset() and buffer().size(),
which read the working_buffer char* pointers non-atomically. state->buf can
be a remote reader shared between file segments (getRemoteReadBuffer), and
this logging runs after the buffer was released, while another thread already
reads through the shared reader and swaps those pointers via SwapHelper in
BoundedReadBuffer::nextImpl(). That is a data race.

This is the same race PR ClickHouse#55372 fixed for getFileOffsetOfBufferEnd() (made it
atomic) but the three working_buffer accessors were left unguarded. Log only
getFileOffsetOfBufferEnd() here, which is atomic.

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

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? No standalone deterministic reproducer (this is a TSAN data race, inherently timing-dependent, ~2 hits ever). It is report-backed: the TSAN report gives both racing stacks with an exact matching address. Same situation as the precedent fix #55372, which was also merged from a TSAN report without a deterministic reproducer. The PR's own BuzzHouse/*(tsan) CI is the validation mechanism.
b Root cause explained? getInfoForLog() reads state->buf->available()/offset()/buffer().size(), all of which read the working_buffer char* pointers non-atomically. state->buf is a remote reader (BoundedReadBuffer) shared between file segments (getRemoteReadBuffer), and this logging runs after the buffer is released. Another thread that took over the shared reader runs BoundedReadBuffer::nextImpl(), whose SwapHelper dtor swaps those same pointers via BufferBase::swap(). Read vs write of the same char* with no synchronization = data race.
c Fix matches root cause? Yes. It removes exactly the three non-thread-safe reads and keeps only getFileOffsetOfBufferEnd(), which is atomic (std::atomic<off_t> offset in ReadBufferFromWebServer, std::atomic<size_t> file_offset_of_buffer_end in BoundedReadBuffer). No band-aid, no bound-widening, no tag.
d Test intent preserved / new tests added? No behavior change (log content only; getInfoForLog is diagnostic). No test is weakened. A deterministic regression test is not feasible for a data race; the TSAN CI covers the concurrent path.
e Both directions demonstrated? On HEAD the racy reads are present (bug reproduces in CI); with the fix they are gone. Compiles clean (debug build, Build ID 4b32f54a...). Race elimination is by construction (no non-atomic read of the swapped pointers remains in this path).
f Fix is general across code paths? Yes. The fix is in getInfoForLog() itself, which is the single source of the racy log line for ALL its callers (nextImplStep scope guard, exception messages, LOG_TEST sites). The other direct reads of state->buf->available()/buffer() in readFromFileSegment/nextImplStep (e.g. lines ~893, ~1319, ~1507) run while THIS thread is the active downloader and sole next() caller, so they are not part of the released-shared-buffer race. getFileOffsetOfBufferEnd() was already made atomic by #55372; this completes the same fix.
g Fix generalizes across inputs? N/A for datatype/wrapper inputs (not a value-processing bug). It is general across read types: the shared-reader hazard applies regardless of ReadType, and logging only the atomic offset is safe for all of them.
h Backward compatible? Yes. Only a diagnostic log line changes (three buf.* fields dropped from a debug log string). No setting, no on-disk/wire/replication format, no new validation. Nothing to gate; no SettingsChangesHistory.cpp change.
i Invariants and contracts preserved? Yes. Honours the contract #55372 documented in SeekableReadBuffer.h: methods used from the logging path after buffer release must be thread-safe against seek()/buffer swap. getFileOffsetOfBufferEnd() satisfies it (atomic); the removed accessors did not. No lifetime, ownership, or lock contract is touched.

Session id: cron:clickhouse-worker-slot-1:20260703-194000

@groeneai

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author

cc @kssenii @antonio2368 for review. This is a follow-up to #55372, which fixed the same getInfoForLog() data race for getFileOffsetOfBufferEnd() (made it atomic) but left the three working-buffer accessors (available()/offset()/buffer().size()) unguarded. A new TSAN report from BuzzHouse (amd_tsan) shows those reads racing with the SwapHelper buffer swap in BoundedReadBuffer::nextImpl() on a remote reader shared between segments. Fix logs only the atomic offset.

@clickhouse-gh

clickhouse-gh Bot commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f5196b6]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_asan_ubsan, targeted) FAIL
03532_window_function_and_null_source_max_threads FAIL cidb
Stateless tests (amd_tsan, s3 storage, parallel, 1/2) FAIL
Server died FAIL cidb, issue
ThreadSanitizer: data race (STID: 1464-2f74) FAIL cidb

AI Review

Summary

This PR removes the racy working-buffer reads from CachedOnDiskReadBufferFromFile::getInfoForLog() and extends the follow-up fix to the Azure reader by making its shared offset state atomic before the logging path relies on getFileOffsetOfBufferEnd(). I re-checked the prior Azure thread against the current head, read the touched files and the sibling right-bounded remote readers, and did not find a remaining correctness, compatibility, or safety issue in the patched path.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 3, 2026
CachedOnDiskReadBufferFromFile::getInfoForLog reads getFileOffsetOfBufferEnd()
of a remote reader that getRemoteReadBuffer shares across file segments, from a
thread logging the read info while another thread reads through the same buffer.
ReadBufferFromAzureBlobStorage returned a plain off_t offset there, mutated by
nextImpl/seek, so on Azure-backed filesystem caches that read still raced.

ReadBufferFromS3 and ReadBufferFromWebServer already make offset atomic for
exactly this reason. Mirror that: make the Azure reader's offset a
std::atomic<off_t> and read it via .load() in getFileOffsetOfBufferEnd() and the
few logging sites. Completes the getInfoForLog TSAN race fix for the Azure path.

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

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author

Updated pre-PR validation gate after extending the fix to the Azure path (f5196b6, per the review above):

Pre-PR validation gate (Azure atomic offset addition) (click to expand)
# Question Answer
a Deterministic repro? No standalone repro (inherent rare TSAN race, same as the parent #55372 which was merged from a report). Report-backed with exact both-thread stacks + matching address; validated by this PR's TSAN CI.
b Root cause explained? getInfoForLog reads getFileOffsetOfBufferEnd() of a remote reader that getRemoteReadBuffer shares across segments, from a logging thread while another thread reads through it. ReadBufferFromAzureBlobStorage backed that with a plain off_t offset mutated by nextImpl/seek, so the Azure path stayed racy after the first commit reduced the log to only getFileOffsetOfBufferEnd().
c Fix matches root cause? Yes. Makes the raced field (offset) atomic, mirroring the exact mechanism used by ReadBufferFromS3/ReadBufferFromWebServer for this same caller. Not a guard/band-aid.
d Test intent preserved / new tests added? No test changed. As with #55372 (merged from a report, no standalone test), the validation vehicle is the TSAN CI of this PR.
e Both directions demonstrated? Race is confirmed by the reported TSAN stacks; the fix removes the unsynchronized access. Confirmation is the PR's TSAN run (no local deterministic trigger for a rare cross-thread race).
f Fix is general across code paths? Yes. Audited every supportsRightBoundedReads() == true reader that can be the shared un-wrapped state->buf: S3 (atomic), WebServer (atomic), Azure (this fix). Non-right-bounded readers (HDFS, local file) are wrapped in BoundedReadBuffer whose file_offset_of_buffer_end is already atomic. No remaining non-atomic sibling on this path.
g Fix generalizes across inputs? N/A (thread-safety change to a single scalar field; no datatype/wrapper/parameter surface).
h Backward compatible? Yes. Internal field storage type only; no setting/format/wire/API change.
i Invariants and contracts preserved? Yes. All offset uses are load/store/compound-add; std::atomic<off_t> provides these via implicit conversion and atomic operators. Only fmt/log sites needed explicit .load(). Debug build compiles clean (Build ID changed b8457b9f). No change to seek/read semantics.

Session id: cron:clickhouse-worker-slot-7:20260703-212900

@clickhouse-gh

clickhouse-gh Bot commented Jul 4, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.60% 85.60% +0.00%
Functions 92.70% 92.70% +0.00%
Branches 77.70% 77.80% +0.10%

Changed lines: Changed C/C++ lines covered: 11/16 (68.75%) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Jul 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — f5196b6

Every failure below has an owner. This PR touches only src/Disks/IO/CachedOnDiskReadBufferFromFile.cpp and src/Disks/IO/ReadBufferFromAzureBlobStorage.{h,cpp} (the getInfoForLog / Azure-offset TSAN fix) — neither failure is caused by that diff.

Check / test Reason Owner
Stateless tests (amd_tsan, s3 storage, parallel, 1/2) / ThreadSanitizer data race STID 1464-2f74 (UniqExactSet::merge → HashSetTable::merge → HashTable::emplaceNonZeroImpl) + Server died (its crash victim) trunk TSAN race (10 hits / 10 unrelated PRs incl. master in 30d; not in our diff) a fix task is moved to pending (investigating at full effort — fixing-PR link to follow here)
Stateless tests (arm_asan_ubsan, targeted) / 03532_window_function_and_null_source_max_threads flaky (query_plan_optimize_join_order_randomize + join_algorithm reorder the crazy-max_threads EXPLAIN PIPELINE so the expected error 290 is not raised; PR-only, 0 master, ~20 unrelated PRs/day) #109330 (external, open)

Reports:

Session id: cron:our-pr-ci-monitor:20260704-023000

@groeneai

groeneai commented Jul 4, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the uniqExact two-level parallel-merge TSan data race (STID 1464-2f74 / 1464-31ed) from this PR's CI finish ledger: #109389

@kssenii kssenii self-assigned this Jul 6, 2026
/// this variable via getFileOffsetOfBufferEnd() from a thread that logs the
/// read info (getInfoForLog) while another thread reads through this shared
/// reader. Same reason ReadBufferFromS3/ReadBufferFromWebServer use atomic.
std::atomic<off_t> offset = 0;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this change still needed after the change in src/Disks/IO/CachedOnDiskReadBufferFromFile.cpp? AFAIS it is not

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, it is still needed. The .cpp change dropped the three working_buffer accessors but kept state->buf->getFileOffsetOfBufferEnd(), which is the racy read on the Azure path.

Call path:

  • getInfoForLog() reads state->buf->getFileOffsetOfBufferEnd().
  • state->buf comes from getRemoteReadBuffer -> create_remote_read_buffer: when impl->supportsRightBoundedReads() is true it returns the impl un-wrapped (no BoundedReadBuffer). ReadBufferFromAzureBlobStorage::supportsRightBoundedReads() returns true, so state->buf is the raw Azure reader.
  • That reader is shared across file segments (setRemoteFileReader/getRemoteFileReader/info.remote_file_reader), so the logging thread and the reading thread can touch it at once.
  • Azure's getFileOffsetOfBufferEnd() returned a plain off_t offset written by nextImpl() (offset += bytes_read) and seek() (offset = offset_) on the reading thread, so that read still races.

ReadBufferFromS3 and ReadBufferFromWebServer already make offset a std::atomic<off_t> for exactly this reason; Azure was the last remote reader left non-atomic. Making the Azure offset atomic completes the fix for the Azure-backed cache path.

@kssenii

kssenii commented Jul 16, 2026

Copy link
Copy Markdown
Member

@groeneai investigate why this issue does not happen without BoundedReadBuffer, for example there is AsynchronousBoundedReadBuffer -- why it never hit this issue?

@groeneai

Copy link
Copy Markdown
Collaborator Author

The race is not about BoundedReadBuffer vs AsynchronousBoundedReadBuffer as a type. It is about which object getInfoForLog logs and whether that object is shared across threads.

CachedOnDiskReadBufferFromFile::getInfoForLog() logs state->buf, i.e. the per-segment remote reader returned by getRemoteReadBuffer(). That reader is deliberately shared between file segments (FileSegment::setRemoteFileReader/getRemoteFileReader, info.remote_file_reader) so segment2 can reuse the impl buffer segment1 downloaded. So one thread reads through it (mutating offset in nextImpl/seek) while the logging thread reads getFileOffsetOfBufferEnd() -> the race. When supportsRightBoundedReads() is true (Azure/S3/WebServer), that shared reader is returned un-wrapped (no BoundedReadBuffer), so its own offset must be atomic. BoundedReadBuffer::file_offset_of_buffer_end is already std::atomic (BoundedReadBuffer.h:39); S3 (ReadBufferFromS3.h:42) and WebServer (ReadBufferFromWebServer.h:86) already made offset atomic for exactly this. Azure was the last un-wrapped shared reader with a plain off_t, hence commit f5196b6.

AsynchronousBoundedReadBuffer never hits it for two reasons:

  1. It is a different pipeline stage (ReadPipeline stage 5, wrapAsyncPrefetch) that wraps the whole chain from the top. It is not state->buf and is never stored in FileSegment::remote_file_reader, so it is never shared across segments. It owns its inner reader uniquely (const ImplPtr impl = std::unique_ptr, AsynchronousBoundedReadBuffer.h:69). No second thread mutates it while another logs it.

  2. Its own getInfoForLog() (AsynchronousBoundedReadBuffer.cpp) does prefetch_future.wait() first, then delegates to impl->getInfoForLog() on the single owning thread, so its file_offset_of_buffer_end is not read concurrently with an in-flight prefetch mutating it.

So the shared-un-wrapped-remote-reader case is unique to the CachedOnDiskReadBufferFromFile inner reader, which confirms making Azure's offset atomic is the right minimal fix (mirroring S3/WebServer), not a BoundedReadBuffer change.

@kssenii

kssenii commented Jul 16, 2026

Copy link
Copy Markdown
Member

Closing in favour of #110154

@kssenii kssenii closed this Jul 16, 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-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants