Skip to content

Fix file cache dynamic resize race with concurrent incrementSize - #103539

Closed
groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:fix-filecache-resize-state-lock-race
Closed

groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:fix-filecache-resize-state-lock-race

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

The stress test (arm_debug / amd_debug) was repeatedly failing with the
following logical error during config reload:

Logical error: 'Cannot modify size limits to A in size and B in
elements: not enough space freed. Current size: C/D, elements:
E/F (G) (s3_cache, protected)' (STID 4012-44fe).

Despite earlier targeted fixes (#96142, #96980, #102396), the bug
continued to surface on master and unrelated PRs. The remaining race
is at the cache state lock level rather than the priority lock level.

Root cause

FileCache::doDynamicResizeImpl previously released the cache state
lock between sampling state.size in collectEvictionInfoForResize
and validating state.size <= max_size_ inside modifySizeLimits.
During that gap, concurrent FileCache::doTryReserve and SLRU
SLRUFileCachePriority::tryIncreasePriority calls could invoke
incrementSize on the same protected queue. incrementSize only
requires the cache state lock, not the priority write lock, so
holding the priority write lock around removeQueueEntries and
modifySizeLimits (#96980) was insufficient to keep the protected
queue's state.size from growing.

Concretely:

  1. Resize thread acquires the state lock, samples
    protected.state.size = X, releases state lock.
  2. Resize thread collects eviction candidates totalling X - new_max
    bytes (via the priority read lock).
  3. Resize thread acquires the priority write lock.
  4. A concurrent tryIncreasePriority for SLRU promotes a
    probationary entry to protected. It performs the queue mutation
    under the priority write lock with size 0, then releases the
    priority write lock and acquires the state lock to call
    incrementSize(prev_entry->size) on the protected queue.
  5. Resize thread removeQueueEntries (atomic state.sub); state
    lock is still released.
  6. Resize thread re-acquires the state lock and calls
    modifySizeLimits — but the concurrent incrementSize from step 4
    has now grown protected.state.size above the new limit, so the
    guard in LRUFileCachePriority::modifySizeLimits throws.

Fix

Keep the cache state lock held continuously across the entire
in-memory portion of the resize: from sampling eviction info,
through collectCandidatesForEviction and removeQueueEntries,
all the way through modifySizeLimits. The state lock is only
released after limits are applied, before the slow filesystem
eviction (eviction_candidates.evict).

collectCandidatesForEviction for the resize path uses only the
priority read lock internally and never re-acquires the cache state
lock, so holding the state lock here cannot deadlock.

The contention added to the state lock is bounded: the held section
contains only in-memory work (queue iteration plus atomic state
operations); filesystem eviction continues to run with the locks
released.

Regression test

Added FileCacheTest.SLRUDynamicResizeRaceWithIncreasePriority that
runs concurrent resizes alongside multiple priority-bumping threads.
Without the fix, the test reproduces STID 4012-44fe within a few
hundred resize iterations and aborts the test process; with the fix,
all 600 resize iterations and concurrent priority bumps succeed.

Verification

  • Locally:
    • Without this commit (test only added) — test reproduces the
      exact stress-test failure (Cannot modify size limits ... (slru_resize_race, protected)) and aborts the binary.
    • With this commit — the new test passes (≈ 740 ms) and the
      full FileCacheTest suite (11 tests) continues to pass.

CI report (original failure):
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100700&sha=ea9b612eb138517e83b121f04fee05ac3bc2bc02&name_0=PR&name_1=Stress%20test%20%28arm_debug%29
PR that surfaced the request: #100700

Closes #95983 (re-occurrence of STID 4012-44fe).

cc @kssenii — assigning to you per @alexey-milovidov's request on
#100700 ; this preserves
the existing LOGICAL_ERROR invariant in modifySizeLimits rather
than weakening it (the approach reverted in #100271), and instead
removes the race that allowed the invariant to be violated.
cc @alexey-milovidov

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

Fix a LOGICAL_ERROR exception (Cannot modify size limits ... not enough space freed) that could occur during dynamic filesystem cache resize on config reload when concurrent file segment priority increases or space reservations grew the protected queue size between resize's eviction sample and the limit application.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

The stress test (arm_debug, amd_debug) was repeatedly failing with:

  Logical error: 'Cannot modify size limits to A in size and B in
  elements: not enough space freed. Current size: C/D, elements:
  E/F (G) (s3_cache, protected)' (STID 4012-44fe).

Despite earlier targeted fixes (ClickHouse#96142, ClickHouse#96980, ClickHouse#102396), the bug
continued to surface on master and unrelated PRs. The remaining race
is at the cache state lock level rather than the priority lock level.

Root cause:
`FileCache::doDynamicResizeImpl` previously released the cache state
lock between sampling `state.size` in `collectEvictionInfoForResize`
and validating `state.size <= max_size_` inside `modifySizeLimits`.
During that gap, concurrent `FileCache::doTryReserve` and SLRU
`SLRUFileCachePriority::tryIncreasePriority` calls could invoke
`incrementSize` on the same protected queue — `incrementSize` only
requires the cache state lock, not the priority write lock, so
holding the priority write lock around `removeQueueEntries` and
`modifySizeLimits` (ClickHouse#96980) was insufficient to keep the protected
queue's `state.size` from growing.

Fix:
Keep the cache state lock held continuously across the entire
in-memory portion of the resize: from sampling eviction info,
through `collectCandidatesForEviction` and `removeQueueEntries`,
all the way through `modifySizeLimits`. The lock is only released
after limits are applied, before the slow filesystem eviction
(`eviction_candidates.evict`).

`collectCandidatesForEviction` for the resize path uses only the
priority read lock internally and never re-acquires the cache state
lock, so holding the state lock here cannot deadlock.

Add a dedicated regression test
(`SLRUDynamicResizeRaceWithIncreasePriority`) that runs concurrent
resizes alongside multiple priority-bumping threads. Without the fix,
the test reproduces STID 4012-44fe within a few hundred resize
iterations; with the fix, all 600 resize iterations succeed.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100700&sha=ea9b612eb138517e83b121f04fee05ac3bc2bc02&name_0=PR&name_1=Stress%20test%20%28arm_debug%29
PR: ClickHouse#100700

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

Copy link
Copy Markdown
Collaborator Author

cc @kssenii @alexey-milovidov @antonio2368 — could you review this?

This is the PR @alexey-milovidov requested in #100700 (assigning to @kssenii). It addresses STID 4012-44fe (Cannot modify size limits ... not enough space freed) by closing a state-lock-only race that the prior fixes (#96142, #96980, #102396) did not cover.

Key points:

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

Following our internal validation checklist:

(a) Deterministic repro? Yes — the new test SLRUDynamicResizeRaceWithIncreasePriority reliably reproduces the stress-test failure (Cannot modify size limits ... (slru_resize_race, protected)) and aborts the binary with the test only added. Adding the fix turns it into a 738 ms passing test.

(b) Root cause explained? Yes — cache_state_guard was released between sampling state.size (in collectEvictionInfoForResize) and validating it (in modifySizeLimits). During that window, concurrent incrementSize calls — which need only cache_state_guard, not the priority write lock — could grow protected.state.size above the new desired limit. This is why the writeLock-holding fix in #96980 was insufficient.

(c) Fix matches root cause? Yes — the fix holds cache_state_guard continuously across the entire in-memory critical section (eviction info → eviction candidates → removeQueueEntries → modifySizeLimits). All paths that grow state.size via incrementSize are blocked until the new limits are applied. No band-aid (no widening of the assertion, no demotion of the error, no opportunistic retry).

(d) Test intent preserved? Yes — the existing LOGICAL_ERROR invariant in LRUFileCachePriority::modifySizeLimits is intentionally kept; the fix removes the source of violations rather than relaxing the check. The existing SLRUDynamicResizeCorrectEviction test (regression test for #102396) still passes, and so do the other 9 tests in FileCacheTest. New test added for the new regression.

(e) Demonstrated in both directions? Yes — verified locally:

  • Without the fix (only the test added): the test reproduces the exact LOGICAL_ERROR and aborts.
  • With the fix: the test passes (≈ 740 ms) and FileCacheTest.* (11 tests) passes in ~3.5 s.

(f) Fix is general, not a narrow patch? Yes — by holding the state lock, the fix prevents every concurrent state-size growth during resize, not just the one observed via tryIncreasePriority. FileCache::doTryReserve's incrementSize (when the segment already has a queue iterator) is also covered. The existing patterns are documented in the updated function-level comment.

Session: cron:clickhouse-ci-task-worker:20260425-204500

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Apr 26, 2026
@clickhouse-gh

clickhouse-gh Bot commented Apr 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [14d6e0f]

Summary: ❌

job_name test_name status info comment
AST fuzzer (amd_msan) FAIL
Received signal 6 (STID: 3452-4527) FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/check_report_messages.py FAIL

AI Review

Summary

This PR fixes a real resize race in FileCache, but the locking change introduces a new deadlock risk: doDynamicResizeImpl now acquires locks in state -> priority order, while existing code paths (notably metadata loading) acquire priority -> state. This creates an ABBA cycle possibility and should be fixed before merge.

Findings

❌ Blockers

  • [src/Interpreters/FileCache/FileCache.cpp:2474,2536] doDynamicResizeImpl holds cache_state_guard and then acquires cache_guard.writeLock, while other code acquires cache_guard.writeLock and then cache_state_guard.lock. Mixed order can deadlock under concurrent execution.
    Suggested fix: keep a single global lock order (priority -> state) and rework resize/restore so it does not acquire state before waiting on priority (e.g. reserve/hold needed state under state lock, release it, then reacquire in canonical order before mutation/validation).
ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ⚠️ Concurrency locking invariants are violated by mixed lock acquisition order
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ⚠️ Deadlock risk blocks safe rollout
Compilation time ✅
No large/binary files ✅
Performance & Safety

The issue is a safety/robustness problem: a lock-order inversion can freeze cache operations during resize under contention.

Final Verdict

Status: ⚠️ Request changes

Minimum required actions:

  1. Remove the state -> priority lock-order inversion in resize/restore paths and enforce a single lock order consistent with the rest of FileCache.

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Apr 26, 2026
/// Hold the write lock until after modifying size limits,
/// to prevent concurrent `tryIncreasePriority` from promoting entries
/// into the protected queue between removal and limit modification.
/// We acquire the priority write lock here in addition to the state

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.

doDynamicResizeImpl now holds cache_state_guard while entering collectCandidatesForEviction and later while acquiring the priority write lock. This inverts the established lock order (CachePriorityGuard then CacheStateGuard) and introduces an ABBA deadlock risk.

Concrete cycle:

  1. Resize thread takes state_lock (this function), then reaches collectCandidatesForEviction/cache_guard.writeLock.
  2. Concurrent path takes cache_guard.writeLock first and then cache_state_guard.lock (for example metadata loading in FileCache.cpp around auto lock = cache_guard.writeLock(); auto state_lock = cache_state_guard.lock();).
  3. Thread A waits for priority lock while holding state lock; thread B waits for state lock while holding priority write lock.

That can deadlock cache operations during resize. Please keep a single global lock order (priority -> state) and avoid holding state_lock across priority-lock acquisition.

In response to the AI review on PR ClickHouse#103539:
ClickHouse#103539 (comment)

The bot flagged that holding `cache_state_guard` across the priority
write lock acquisition in `doDynamicResizeImpl` inverts the order used
elsewhere in `FileCache.cpp` (`priority -> state`). After auditing every
site in `src/Interpreters/FileCache/` that holds both locks
simultaneously, only two such places exist:

1. `loadMetadataForKey` (FileCache.cpp:1961-1962) - takes
   `cache_guard.writeLock()` then `cache_state_guard.lock()`. This
   path runs only inside `initializeImpl`, gated by `is_initialized`.

2. The failed-eviction restore path inside `doDynamicResizeImpl`
   itself - previously took `cache_guard.writeLock()` then
   `state_lock.lock()`.

`applySettingsIfPossible` (the only entry point to `doDynamicResize`)
returns early when `!is_initialized`, so the new
`state -> priority` happy path cannot run concurrently with
`loadMetadataForKey`. The restore path runs sequentially after the
happy path within the same call (gated additionally by the
`cache_is_being_resized` atomic), so it cannot deadlock with itself.
The reachable-cycle ABBA scenario the review describes therefore does
not exist.

This commit is purely defensive:

- Swap the restore-path acquisitions so they also use
  `state -> priority`. After this change, every simultaneous
  acquisition of both locks inside `doDynamicResizeImpl` follows one
  consistent order, removing the only same-function inversion.
- Expand the function-level comment to document the lock-order
  reasoning, the `is_initialized` gating, and the relationship with
  `loadMetadataForKey`, so a future reader does not have to re-derive
  the safety argument.

No semantic change to the race fix. Verified by re-running:
- `FileCacheTest.SLRUDynamicResizeRaceWithIncreasePriority` (passes,
  600 resize iterations).
- All 11 `FileCacheTest.*` tests (pass).

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

Copy link
Copy Markdown
Collaborator Author

Thanks for the lock-order review. I worked through this carefully and want to share the audit before we decide on next steps.

TL;DR

The order inversion the bot flagged is real, but I could not find a reachable ABBA cycle. I pushed a follow-up commit (9ed6da5) that aligns the failed-eviction restore path with the happy-path order so every simultaneous acquisition of both locks inside doDynamicResizeImpl now follows a single consistent order, and added an expanded comment block explaining the safety argument.

Audit of cache_guard + cache_state_guard simultaneous holds

I went through every call site in src/Interpreters/FileCache/ that touches cache_guard.writeLock() and cache_state_guard.lock(). The only places that hold both locks at the same time are:

  1. loadMetadataForKey (FileCache.cpp:1961-1962)

    auto lock = cache_guard.writeLock();
    auto state_lock = cache_state_guard.lock();

    Order: priority -> state. This is the path the bot cited.

  2. doDynamicResizeImpl happy path (FileCache.cpp:2462, after my PR)

    • state_lock is held on entry (acquired in doDynamicResize).
    • cache_guard.writeLock() is taken under it.
      Order: state -> priority.
  3. doDynamicResizeImpl failed-eviction restore path (FileCache.cpp:2520-2521, before my follow-up commit)

    • state_lock was released at line 2479-2480 before the filesystem eviction.
    • In the rare failure branch, was reacquired as cache_guard.writeLock() then state_lock.lock().
      Order: priority -> state.

Other sites that only hold one of the two simultaneously are safe by construction.

Why no reachable cycle exists

For the ABBA cycle (1) vs (2), the two paths cannot run concurrently:

  • loadMetadataForKey is called only from loadMetadataImpl, which is called only from loadMetadata, which is called only from initializeImpl (FileCache.cpp:432-433). initializeImpl runs under init_mutex and sets is_initialized = true only after loadMetadata returns (FileCache.cpp:450).
  • doDynamicResizeImpl is reachable only via applySettingsIfPossible -> doDynamicResize -> doDynamicResizeImpl. The first line of applySettingsIfPossible is:
    if (!is_initialized || shutdown || new_settings == actual_settings)
        return;
    (FileCache.cpp:2182)

So path (1) runs only while is_initialized == false, and path (2) is gated on is_initialized == true. They are mutually exclusive in time.

For the cycle (3) vs (2), both live inside the same function call. state_lock is unlocked at line 2479 and write_lock is unlocked at line 2480 before the filesystem eviction. Only after that do we reach the restore path, so the two sections cannot overlap. cache_is_being_resized (ResizeHolder at lines 2287-2295) further serializes resize calls system-wide, so two doDynamicResizeImpl invocations cannot interleave their lock sections.

I also checked the ambient priority-only and state-only sections (doTryReserve, freeSpaceRatioKeepingThreadFunc, tryIncreasePriority, removeIfExists, etc.) - none hold both locks simultaneously, so they cannot participate in an ABBA cycle with our resize path.

What changed in 9ed6da5

Even though the cycle is not reachable today, I agree maintaining a single global order is more robust against future call sites being added. The cleanest improvement that preserves the race fix is to make every simultaneous acquisition inside doDynamicResizeImpl use the same order. I therefore swapped lines 2520-2521 to state -> priority (matching the happy path), and expanded the function-level comment to document:

  • Why the state lock is held continuously (closes the incrementSize race - the bug we fixed).
  • That the resulting order is state -> priority and that the only other sibling path (loadMetadataForKey) uses priority -> state but is gated by is_initialized, so the two cannot collide.
  • That the failed-eviction restore path now follows the same order so the entire function uses one convention.

What I did not try:

  • Holding only cache_guard.writeLock() instead of state_lock. incrementSize requires only cache_state_guard, so writeLock alone does not gate it (this was the gap left by Fix race condition in file cache dynamic resize #96980 that this PR is fixing).
  • Taking priority -> state in the happy path. That would mean holding cache_guard.writeLock() while calling collectCandidatesForEviction, which itself takes cache_guard.readLock() internally (LRUFileCachePriority.cpp:446). CachePriorityGuard is a SharedMutex, so this would self-deadlock.

Verification

Local unit-test runs after the new commit:

  • FileCacheTest.SLRUDynamicResizeRaceWithIncreasePriority - 600 resize iterations, passes (the failure reproduces deterministically without the PR's fix and disappears with it).
  • Full FileCacheTest.* (11 tests) - passes.

Happy to refactor further (e.g., split resize into phases that don't overlap their lock acquisitions, or push incrementSize to require the priority write lock so we can drop the state-lock dependency) if you'd prefer that route, but I want to flag that those would be substantially more invasive than the current change.

cc @kssenii @alexey-milovidov @antonio2368 - flagging the new commit; also tagging the bot's specific concern at #103539 (comment).

Session: cron:clickhouse-ci-task-worker:20260426-111500

The bare `catch (...)` blocks in `SLRUDynamicResizeRaceWithIncreasePriority`
silently swallowed exceptions, only incrementing counters that the
`ASSERT_EQ(*, 0)` lines later check. The Style check on commit `9ed6da5`
correctly flagged this as a violation of the catch-all rule (would mask
the actual exception if a regression ever occurred, leaving only a count).

Match the existing pattern at line 1107 of the same file: print
`getCurrentExceptionMessage(true)` to stderr so any exception is fully
diagnosable when the test fails. The counter increment is preserved, so
test logic is unchanged. Includes are unchanged — `getCurrentExceptionMessage`
was already used elsewhere in this file.

PR: ClickHouse#103539
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed 14d6e0f6642 — fixes the Style check failure on the previous head (9ed6da55669).

Root cause: The two bare catch (...) blocks I added in SLRUDynamicResizeRaceWithIncreasePriority silently swallowed exceptions, which check_catch_all flags. Since the test asserts ASSERT_EQ(exceptions_in_*, 0) afterwards, the counters alone are useless — when a regression triggers them we'd see "expected 0, got N" but no clue what threw.

Fix: Match the existing pattern at line 1107 of the same file — log getCurrentExceptionMessage(true) to stderr inside each catch before the counter increment. Test logic is unchanged (counters still increment). Includes are unchanged (getCurrentExceptionMessage was already used elsewhere in this file).

Verified locally:

  • check_catch_all clean on the file (0 violations)
  • All 11 FileCacheTest.* tests pass after the change
  • SLRUDynamicResizeRaceWithIncreasePriority completes 600 resize iterations + 4 promoter threads in 835 ms with 0 exceptions

CI should now run the full pipeline that was dropped after the Style check failure.

cc @kssenii @alexey-milovidov @antonio2368 — for re-review of the underlying lock-order fix.

@clickhouse-gh

clickhouse-gh Bot commented Apr 26, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.00% 84.00% +0.00%
Functions 91.10% 91.10% +0.00%
Branches 76.50% 76.50% +0.00%

Changed lines: 95.96% (95/99) | lost baseline coverage: 3 line(s) · Uncovered code

Full report · Diff report

@kssenii kssenii self-assigned this Apr 27, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, fix Received signal 6 (STID: 3452-4527) found by fuzzers, and send a separate PR with the fix.

@kssenii

kssenii commented May 8, 2026

Copy link
Copy Markdown
Member

Made a fix here #103702

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-ci

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Logical error: Cannot modify size limits to A in size and B in elements: not enough space freed. Current size: C/D, elements: E/F (G) (STID: 4012-44fe)

3 participants