Skip to content

Wire profiled lock wrappers into FileCache guards to measure contention wait time - #108806

Merged
antonio2368 merged 9 commits into
masterfrom
fs-cache-lock-changes
Aug 19, 2026
Merged

antonio2368 merged 9 commits into
masterfrom
fs-cache-lock-changes

Conversation

@antonio2368

@antonio2368 antonio2368 commented Jun 29, 2026 •

Copy link
Copy Markdown
Member

Previously, FileCache lock guards measured lock wait time including uncontended acquisitions. The guards now use ProfiledLock wrappers directly, so the corresponding profile events only increment when the lock was actually contended, making the metrics more meaningful.

As a cleanup, the three profiled lock classes in ProfiledLocks.h are consolidated into a single template with the original names kept as type aliases.

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

Version info

  • Merged into: 26.8.1.1676 (included in 26.8 and later)

Replace ad-hoc `ProfileEventTimeIncrement` timing (which always
measures, regardless of contention) with a unified
`ProfiledLockBase<MutexType, LockType>` template that measures
wait-time only when the lock was actually contended.

Key changes:

- `ProfiledLocks.h`: introduce `ProfiledLockBase<MutexType, LockType>`,
  a `TSA_SCOPED_LOCKABLE` template with contention-only profiling,
  move support, `owns_lock()`, and `operator bool()`. Four aliases:
  `ProfiledMutexLock`, `ProfiledTimedMutexLock`, `ProfiledExclusiveLock`,
  `ProfiledSharedLock`.

- `Guards.h`: replace `std::unique_lock`/`std::shared_lock` in
  `CachePriorityGuard` and `CacheStateGuard` with the new profiled
  lock types; `CacheMetadataGuard`, `KeyGuard`, `FileSegmentGuard`
  `Lock` structs now inherit from `ProfiledMutexLock`. All factory
  methods annotated `TSA_NO_THREAD_SAFETY_ANALYSIS` (Clang TSA cannot
  model functions that return a scoped lock by value).

- `FileSegment.h`: change `cv` from `std::condition_variable` to
  `std::condition_variable_any` since `FileSegmentGuard::Lock` is
  no longer a plain `std::unique_lock<std::mutex>`.

- `FileCache.h`: annotate `doDynamicResizeImpl` with
  `TSA_NO_THREAD_SAFETY_ANALYSIS` — it takes a `CacheStateGuard::Lock`
  by reference and manually calls `unlock()`/`lock()` on it.

- `FileSegment.cpp`, `Metadata.cpp`: remove now-redundant
  `ProfileEventTimeIncrement` wrappers at the call sites.

Co-Authored-By: Claude Sonnet 4.6 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [831e20b]

Summary: ✅


AI Review

Summary

This PR replaces the ad-hoc FileCache and Keeper lock-wait timers with reusable ProfiledExclusiveLock / ProfiledSharedLock wrappers so the profile events grow only when acquisition really blocks, and it also fixes the exception path in FileSegment::wait so the adopted condition_variable lock is not unlocked twice. The remaining gap is evidence: the observable contract of the new wrappers changed, but there is still no focused regression test proving the uncontended, contended, and timed-wait cases, so I cannot approve it yet.

Tests
  • ⚠️ Add a small src/Common/tests gtest that checks ProfileEvents::global_counters deltas for the new wrappers: uncontended ProfiledExclusiveLock / ProfiledSharedLock acquisition should leave the wait counter unchanged, while a contended acquisition and a timed-out CacheStateGuard::tryLockFor path should increment the corresponding event. The timed constructor already regressed once during review, so this contract needs direct coverage.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions:
    • Add the focused regression coverage above.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.80% 86.70% -0.10%
Functions 92.00% 92.00% +0.00%
Branches 79.20% 79.20% +0.00%

Changed lines: Changed C/C++ lines covered: 86/122 (70.49%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Jun 29, 2026
Comment thread src/Interpreters/FileCache/Guards.h Resolved
antonio2368 added a commit that referenced this pull request Jun 29, 2026
- Revert `FileSegment::cv` from `condition_variable_any` back to
  `condition_variable` to avoid a heap allocation per `FileSegment`
  construction. Add `mutex()` accessor to `ProfiledLockBase` and use
  the adopt-lock/release pattern at the `cv.wait_for` call site so the
  plain `unique_lock<mutex>` required by `condition_variable` can be
  formed from the profiled lock without double-ownership.

- Restore `CacheStateGuard::Lock` as a distinct nested struct
  (`:Lock : public ProfiledTimedMutexLock`) so that any independently-
  constructed `ProfiledTimedMutexLock` over an unrelated `timed_mutex`
  no longer satisfies APIs taking `CacheStateGuard::Lock &`.

- Add a `duration<Rep,Period>` constructor overload to `ProfiledLockBase`
  that measures the timed-wait path: tries the lock first, and if
  contended measures the `try_lock_for` wait with a `Stopwatch` before
  incrementing the profile event. This ensures `tryLockFor` callers
  (background free-space-keeping loops) contribute to
  `FilesystemCacheStateLockMicroseconds` as intended.

Related: #108806 (comment)
- Revert `FileSegment::cv` from `condition_variable_any` back to
  `condition_variable` to avoid a heap allocation per `FileSegment`
  construction. Add `mutex()` accessor to `ProfiledLockBase` and use
  the adopt-lock/release pattern at the `cv.wait_for` call site so the
  plain `unique_lock<mutex>` required by `condition_variable` can be
  formed from the profiled lock without double-ownership.

- Restore `CacheStateGuard::Lock` as a distinct nested struct
  (`:Lock : public ProfiledTimedMutexLock`) so that any independently-
  constructed `ProfiledTimedMutexLock` over an unrelated `timed_mutex`
  no longer satisfies APIs taking `CacheStateGuard::Lock &`.

- Add a `duration<Rep,Period>` constructor overload to `ProfiledLockBase`
  that measures the timed-wait path: tries the lock first, and if
  contended measures the `try_lock_for` wait with a `Stopwatch` before
  incrementing the profile event. This ensures `tryLockFor` callers
  (background free-space-keeping loops) contribute to
  `FilesystemCacheStateLockMicroseconds` as intended.

Related: #108806 (comment)
@antonio2368
antonio2368 force-pushed the fs-cache-lock-changes branch from 9cdd424 to 7002501 Compare June 29, 2026 12:38
public:
ProfiledSharedLock(SharedMutex & mutex, ProfileEvents::Event wait_event_) TSA_ACQUIRE_SHARED(mutex)
template <typename Rep, typename Period>
ProfiledLockBase(MutexType & mutex, ProfileEvents::Event wait_event_, std::chrono::duration<Rep, Period> timeout)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The observable contract here is that ProfiledLockBase leaves the wait event unchanged for uncontended acquisition, but increments it when acquisition really blocks, including the timed path used by CacheStateGuard::tryLockFor. There is no focused regression test for those semantics, and this timed constructor was already missing profiling in the first revision, so future changes can silently make the FileCache lock metrics misleading again.

Please add a small src/Common/tests gtest that compares ProfileEvents::global_counters deltas for at least an uncontended ProfiledMutexLock acquisition and a contended/timed-out ProfiledTimedMutexLock acquisition.

Comment thread src/Common/ProfiledLocks.h Resolved
@antonio2368
antonio2368 force-pushed the fs-cache-lock-changes branch from 137c3a0 to 44bb2d7 Compare June 30, 2026 08:17
Comment thread src/Common/ProfiledLocks.h Outdated
Comment on lines +46 to +48
Stopwatch watch;
LockType::try_lock_for(timeout);
ProfileEvents::increment(wait_event, watch.elapsedMicroseconds());

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.

nit: could be put into tryLockAndProfileWait for consistency with lockAndProfileWait

The underlying lock type is fully determined by the mutex type plus the
exclusive/shared choice, so the four aliases (`ProfiledMutexLock`,
`ProfiledTimedMutexLock`, `ProfiledExclusiveLock`, `ProfiledSharedLock`)
collapse to two alias templates generic over the mutex type, with the
mutex deduced from the constructor argument via CTAD:

    template <typename MutexType>
    using ProfiledExclusiveLock = ProfiledLockBase<MutexType, std::unique_lock<MutexType>>;
    template <typename MutexType>
    using ProfiledSharedLock = ProfiledLockBase<MutexType, std::shared_lock<MutexType>>;

`ProfiledMutexLock`/`ProfiledTimedMutexLock` become `ProfiledExclusiveLock`
over `std::mutex`/`std::timed_mutex`. An explicit deduction guide is added to
`ProfiledLockBase` so alias-template CTAD does not trip
`-Wctad-maybe-unsupported`; the implicit constructor guides still perform the
actual deduction. Aliases (not derived classes) are used so the type identity
stays `ProfiledLockBase` and thread-safety analysis keeps recognizing the
`TSA_ACQUIRE` annotations.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@antonio2368
antonio2368 force-pushed the fs-cache-lock-changes branch from 44bb2d7 to fd10b55 Compare June 30, 2026 12:22
@clickhouse-gh

clickhouse-gh Bot commented Jun 30, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 34 queries analysed

This PR is a lock-profiling instrumentation refactor (templating ProfiledExclusiveLock/ProfiledSharedLock) plus Keeper coordination and FileCache/distributed-cache lock plumbing; it relocates or removes per-lock timing counters but does not change any query-execution compute path. None of the flagged queries exercise the changed code, and several deltas (×8.4 and ×2.2 faster, a -25% shift) are far too large to come from removing microsecond-scale lock timers. With only 6 source runs sharing a single benchmark host against 30 base runs, all flagged results — the improvements and the single +5.6% regression alike — are best read as colocation and run-to-run variance, so every one has been downgraded to not sure.

clickbench

⚠️ 9 inconclusive

Flagged queries (9 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 13 not_sure 422 344 -18.5% <0.0001 This PR only refactors lock-profiling instrumentation plus Keeper/FileCache lock plumbing; it does not touch Q13's execution path, so the -18.5% is run-to-run variance.
⚠️ 15 not_sure 192 159 -17.2% <0.0001 No compute-path code changes here; the -17.2% cannot be attributed to a lock-instrumentation refactor and reads as variance.
⚠️ 16 not_sure 734 622 -15.3% <0.0001 The diff is lock-profiling/coordination plumbing only; Q16's -15.3% is off-path and consistent with noise.
⚠️ 18 not_sure 1244 1062 -14.7% <0.0001 Q18 also shows the noisiest underlying measurements; the -14.7% is not plausibly caused by this instrumentation-only change.
⚠️ 23 not_sure 164 75 ×2.2 faster <0.0001 A ×2.2 faster shift is far larger than anything removing a per-lock timer could produce; this is off-path variance, not a PR effect.
⚠️ 28 not_sure 1051 1110 +5.6% <0.0001 The lone flagged regression (+5.6%) touches no code Q28 executes; borderline delta reads as variance, downgraded symmetrically with the improvements.
⚠️ 30 not_sure 279 230 -17.6% <0.0001 Instrumentation-only diff; the -17.6% is off Q30's execution path and attributable to variance.
⚠️ 31 not_sure 408 305 -25.2% <0.0001 No compute-path change; the -25.2% cannot be sourced to this lock-profiling refactor.
⚠️ 33 not_sure 1250 1186 -5.0% <0.0001 The -5.0% is off-path relative to the lock-instrumentation/Keeper/FileCache changes and reads as noise.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

⚠️ 2 inconclusive

Flagged queries (2 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 7 not_sure 560 67 ×8.4 faster <0.0001 A ×8.4 faster swing is orders of magnitude beyond what removing microsecond lock timers could yield; off-path, so variance/colocation, not this PR.
⚠️ 8 not_sure 166 78 ×2.1 faster <0.0001 ×2.1 faster on a path this diff does not touch; consistent with run-to-run variance rather than a real PR effect.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

Debug info
  • StressHouse run: 5fdda5bf-0b14-4e50-bcc8-c354aa30c39c
  • MIRAI run: 5b8950ed-5658-4458-8b4d-44730b05fdcc
  • PR check IDs:
    • clickbench_1921783_1787056633
    • clickbench_1921796_1787056633
    • clickbench_1921804_1787056633
    • tpch_adapted_1_official_1921815_1787056633
    • tpch_adapted_1_official_1921839_1787056633
    • tpch_adapted_1_official_1921853_1787056633

@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: 78/134 (58.21%) · Uncovered code

Full report · Diff report

# Conflicts:
#	src/Interpreters/FileCache/FileSegment.cpp
@clickhouse-gh

clickhouse-gh Bot commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

Dear @kssenii, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@kssenii kssenii self-assigned this Jul 30, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

AddressSanitizer: double-free (STID: 0883-4595)

Absolute blocker.

@clickhouse-gh

clickhouse-gh Bot commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 831e20b2c with master 7ac9a3b20 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 2dba8ed9d; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 692.70 MiB 689.70 MiB -3.00 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Object file sizes

22 object files changed (+49.38 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/ObjectStorage/DataLakes/Paimon/BinaryRow.cpp.o 127.31 KiB 143.98 KiB +16.67 KiB (+13.09%)

737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

405 translation units recompiled, 4672 s compile time in total, 405 of them have a recent master baseline.

Job report

@antonio2368
antonio2368 enabled auto-merge August 18, 2026 19:11
@antonio2368
antonio2368 added this pull request to the merge queue Aug 19, 2026
Merged via the queue into master with commit 8b9c617 Aug 19, 2026
182 checks passed
@antonio2368
antonio2368 deleted the fs-cache-lock-changes branch August 19, 2026 00:37
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 19, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@antonio2368 @kssenii — title/description suggestions:

Description (currently misleading):

  • Why: Two problems. (a) "the original names kept as type aliases" is false: ProfiledMutexLock is deleted (grep -rn ProfiledMutexLock src/ tests/ returns nothing; the same grep finds 60+ ProfiledExclusiveLock hits, so the probe works), all its call sites are rewritten to ProfiledExclusiveLock, and no using aliases are introduced -- ProfiledExclusiveLock/ProfiledSharedLock are class templates, not aliases. (b) The body does not mention FileSegment::wait (FileSegment.cpp:602), the only behavioral code in the diff: because FileSegmentGuard::Lock is no longer a std::unique_lock, the wait loop now adopts the guard's mutex into a separate std::unique_lock for cv.wait_for and release()s it on scope exit. A reviewer will stumble on that hunk.

  • Suggested addition:

    ProfiledMutexLock is removed, not aliased: all of its call sites in KeeperRequestDispatcherOld.cpp, KeeperServer.cpp, KeeperStateMachine.cpp and ShardedMap.h now use ProfiledExclusiveLock<std::mutex> via CTAD.

    Because the guards' Lock types no longer derive from std::unique_lock, FileSegment::wait can no longer pass its guard lock to std::condition_variable::wait_for. It now adopts the guard's mutex into a local std::unique_lock for the duration of the wait loop and release()s it on scope exit, leaving the original guard lock owning the mutex on both the normal and the throwing (throwIfKilled) exit.

    Note for operators: FileSegmentLockMicroseconds, FilesystemCacheLockKeyMicroseconds, FilesystemCacheLockMetadataMicroseconds, FilesystemCacheStateLockMicroseconds and the two FilesystemCachePriority*LockMicroseconds counters change meaning from total acquisition time to contended wait time only, so their values will drop sharply after upgrade.

Ignore if intentional.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-not-for-changelog This PR should not be mentioned in the changelog 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.

5 participants