Skip to content

Remove a few FileSegment::mutex locks from a few places - #108932

Merged
kssenii merged 7 commits into
masterfrom
file-segment-remove-mutex-locks
Jul 7, 2026
Merged

kssenii merged 7 commits into
masterfrom
file-segment-remove-mutex-locks

Conversation

@kssenii

@kssenii kssenii commented Jun 30, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Improvement

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

Remove a few FileSegment::mutex locks in a few places.

Version info

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

`FileSegment::state`, `getReservedSize`, `isDownloaded` and `isDetached`
each return a single-field snapshot of an already-atomic field
(`download_state`, `reserved_size`). Taking `segment_guard` added no
consistency and only contended hot segments, so read these fields without
the lock.

To keep the lockless `download_state` reads safe, publish `DOWNLOADED` as
the last write of each transition in `setDownloadedUnlocked` and
`shrinkFileSegmentToDownloadedSize`: previously `DOWNLOADED` was set before
finalizing the writer, releasing the reader and (when shrinking) settling
the range and reserved size. A reader observing `DOWNLOADED` reads the
cache file from disk directly, so it must happen-after all the finalizing
writes. Since `download_state` is a seq-cst atomic, publishing it last
guarantees an observer of `DOWNLOADED` sees a consistent, fully downloaded
segment.

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

clickhouse-gh Bot commented Jun 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [977c99a]

Summary: ❌

job_name test_name status info comment
AST fuzzer (arm_asan_ubsan) FAIL
Logical error: Block structure mismatch in A stream: different columns: (STID: 0993-2cc2) FAIL cidb, issue ISSUE EXISTS

AI Review

Summary

This PR removes a few FileSegment mutex acquisitions and adjusts the surrounding completion paths so the lock-free reads still observe a consistent terminal state. After re-checking the current head against both prior review threads, I did not find a remaining correctness or concurrency regression in the changed code. The only issue I would still fix is the changelog metadata: the current category/entry describe the patch too vaguely for a performance-motivated change.

PR Metadata

Changelog category should be Performance Improvement, not Improvement, because the change is explicitly reducing lock contention in a hot cache path.

Changelog entry is required for that category, but the current text is too internal and vague. A better replacement would be: Reduced redundant filesystem-cache locking in FileSegment state checks and completion paths.

Missing context / blind spots
  • ⚠️ I did not run local gtest_filecache: this checkout does not have a ready build directory, and the full amd_debug / ASan / TSan CI jobs were still pending when I reviewed the current head. Passing those jobs would close the remaining concurrency/error-path blind spot.
Final Verdict

✅ No remaining code blockers in the current head from manual review. Clean up the changelog metadata and rely on the pending debug/sanitizer CI for final confidence.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jun 30, 2026
@kssenii
kssenii marked this pull request as ready for review July 1, 2026 14:19
kssenii and others added 3 commits July 2, 2026 14:00
`setDownloadedUnlocked` now publishes `DOWNLOADED` as its last write, so if
`cache_writer->finalize()` throws, the segment would unwind with
`download_state` still `DOWNLOADING` and the downloader gone. `resetDownloader`
/ `complete` wake waiters on scope exit, so readers blocked in
`FileSegment::wait` would wake up, observe `DOWNLOADING` again and spin forever
with no terminal state to progress to.

Wrap the `finalize` call in a try/catch and, on failure, move the segment to a
non-`DOWNLOADING` state via `setDownloadFailedUnlocked` instead of propagating.

#108932 (comment)

Co-Authored-By: Claude Fable 5 <[email protected]>
When completing a `PARTIALLY_DOWNLOADED` / `PARTIALLY_DOWNLOADED_NO_CONTINUATION`
file segment as the last holder, `complete` finalizes the cache writer and then
calls `shrinkFileSegmentToDownloadedSize`, which reclaims the reserve-ahead
surplus (reserved but not downloaded space) back to the cache quota. If
`cache_writer->finalize()` threw, the shrink was skipped and the surplus stayed
charged against the quota forever.

Wrap the `finalize` call so a failure is logged and the segment is still resized
and its reserved surplus reclaimed. Also log the swallowed exception in
`setDownloadedUnlocked`.

Co-Authored-By: Claude Fable 5 <[email protected]>
`FileSegment::complete` uses `isDetached` to confirm a benign concurrent detach
when `lockKeyMetadata(false)` returns `nullptr`. `setDetachedState` sets
`DETACHED` and resets `key_metadata` under the segment lock, so a lockless
atomic load in `isDetached` can race: `lockKeyMetadata` can observe the key
metadata gone while the load still returns a non-`DETACHED` state, turning a
benign concurrent detach into `LOGICAL_ERROR: Cannot complete file segment`.

Take the segment lock in `isDetached` so the read has a happens-after edge with
`setDetachedState`. This path is not hot, so the lock costs nothing on the hot
read path (which uses `state` / `isDownloaded`).

#108932 (comment)

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 2, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.50% 85.50% +0.00%
Functions 92.60% 92.60% +0.00%
Branches 77.70% 77.70% +0.00%

Changed lines: Changed C/C++ lines covered: 50/51 (98.04%) · Uncovered code

Full report · Diff report

@kssenii
kssenii requested a review from antonio2368 July 3, 2026 10:40
@kssenii
kssenii added this pull request to the merge queue Jul 7, 2026
@kssenii kssenii added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Jul 7, 2026
Merged via the queue into master with commit 9d5fd8a Jul 7, 2026
172 of 174 checks passed
@kssenii
kssenii deleted the file-segment-remove-mutex-locks branch July 7, 2026 12:43
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 7, 2026
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Jul 7, 2026
@tavplubix tavplubix removed the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Jul 7, 2026
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Jul 7, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Jul 8, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
`setDownloadedUnlocked` now publishes `DOWNLOADED` as its last write, so if
`cache_writer->finalize()` throws, the segment would unwind with
`download_state` still `DOWNLOADING` and the downloader gone. `resetDownloader`
/ `complete` wake waiters on scope exit, so readers blocked in
`FileSegment::wait` would wake up, observe `DOWNLOADING` again and spin forever
with no terminal state to progress to.

Wrap the `finalize` call in a try/catch and, on failure, move the segment to a
non-`DOWNLOADING` state via `setDownloadFailedUnlocked` instead of propagating.

ClickHouse#108932 (comment)

Co-Authored-By: Claude Fable 5 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
`FileSegment::complete` uses `isDetached` to confirm a benign concurrent detach
when `lockKeyMetadata(false)` returns `nullptr`. `setDetachedState` sets
`DETACHED` and resets `key_metadata` under the segment lock, so a lockless
atomic load in `isDetached` can race: `lockKeyMetadata` can observe the key
metadata gone while the load still returns a non-`DETACHED` state, turning a
benign concurrent detach into `LOGICAL_ERROR: Cannot complete file segment`.

Take the segment lock in `isDetached` so the read has a happens-after edge with
`setDetachedState`. This path is not hot, so the lock costs nothing on the hot
read path (which uses `state` / `isDownloaded`).

ClickHouse#108932 (comment)

Co-Authored-By: Claude Fable 5 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…ove-mutex-locks

Remove a few FileSegment::mutex locks from a few places
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-improvement Pull request with some product improvements pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v25.12-must-backport v26.2-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants