Repository navigation
Conversation
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]>
|
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 ( Key points:
|
|
Pre-PR validation gate Following our internal validation checklist: (a) Deterministic repro? Yes — the new test (b) Root cause explained? Yes — (c) Fix matches root cause? Yes — the fix holds (d) Test intent preserved? Yes — the existing (e) Demonstrated in both directions? Yes — verified locally:
(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 Session: cron:clickhouse-ci-task-worker:20260425-204500 |
|
Workflow [PR], commit [14d6e0f] Summary: ❌
AI ReviewSummaryThis PR fixes a real resize race in Findings❌ Blockers
ClickHouse Rules
Performance & SafetyThe issue is a safety/robustness problem: a lock-order inversion can freeze cache operations during resize under contention. Final VerdictStatus: Minimum required actions:
|
| /// 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 |
There was a problem hiding this comment.
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:
- Resize thread takes
state_lock(this function), then reachescollectCandidatesForEviction/cache_guard.writeLock. - Concurrent path takes
cache_guard.writeLockfirst and thencache_state_guard.lock(for example metadata loading inFileCache.cpparoundauto lock = cache_guard.writeLock(); auto state_lock = cache_state_guard.lock();). - 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]>
|
Thanks for the lock-order review. I worked through this carefully and want to share the audit before we decide on next steps. TL;DRThe 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 Audit of
|
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
|
Pushed Root cause: The two bare Fix: Match the existing pattern at line 1107 of the same file — log Verified locally:
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. |
LLVM Coverage Report
Changed lines: 95.96% (95/99) | lost baseline coverage: 3 line(s) · Uncovered code |
|
@groeneai, fix |
|
Made a fix here #103702 |
The stress test (arm_debug / amd_debug) was repeatedly failing with the
following logical error during config reload:
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::doDynamicResizeImplpreviously released the cache statelock between sampling
state.sizeincollectEvictionInfoForResizeand validating
state.size <= max_size_insidemodifySizeLimits.During that gap, concurrent
FileCache::doTryReserveand SLRUSLRUFileCachePriority::tryIncreasePrioritycalls could invokeincrementSizeon the same protected queue.incrementSizeonlyrequires the cache state lock, not the priority write lock, so
holding the priority write lock around
removeQueueEntriesandmodifySizeLimits(#96980) was insufficient to keep the protectedqueue's
state.sizefrom growing.Concretely:
protected.state.size = X, releases state lock.X - new_maxbytes (via the priority read lock).
tryIncreasePriorityfor SLRU promotes aprobationary 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.removeQueueEntries(atomicstate.sub); statelock is still released.
modifySizeLimits— but the concurrentincrementSizefrom step 4has now grown
protected.state.sizeabove the new limit, so theguard in
LRUFileCachePriority::modifySizeLimitsthrows.Fix
Keep the cache state lock held continuously across the entire
in-memory portion of the resize: from sampling eviction info,
through
collectCandidatesForEvictionandremoveQueueEntries,all the way through
modifySizeLimits. The state lock is onlyreleased after limits are applied, before the slow filesystem
eviction (
eviction_candidates.evict).collectCandidatesForEvictionfor the resize path uses only thepriority 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.SLRUDynamicResizeRaceWithIncreasePrioritythatruns 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
exact stress-test failure (
Cannot modify size limits ... (slru_resize_race, protected)) and aborts the binary.full
FileCacheTestsuite (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_ERRORinvariant inmodifySizeLimitsratherthan 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):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix a
LOGICAL_ERRORexception (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