Repository navigation
Fix data race on FileCacheQueryLimit::query_map causing LOGICAL_ERROR - #107028
Conversation
FileCacheQueryLimit::query_map (a std::unordered_map) was accessed under two
different cache locks with no single lock serializing it:
- read (tryGetQueryContext, query_map.find) runs under CacheStateGuard::Lock,
called from FileCache::doTryReserve once per reservation;
- writes (getOrSetQueryContext, query_map.emplace; removeQueryContext,
query_map.erase) run under CachePriorityGuard::WriteLock, called from
FileCache::getQueryContextHolder and ~QueryContextHolder.
Because the read uses a different mutex than the writes, a find() can run
concurrently with an emplace()/erase() that rehashes and invalidates buckets
and iterators. This is undefined behaviour on std::unordered_map and shows up
as either "Attempt to release query context that does not exist" (the map was
corrupted so a present key looks absent in removeQueryContext) or a server
crash while reading a half-rehashed bucket. Both were observed together in the
same CI run on Stateless tests (amd_debug, sequential).
The split was introduced when tryGetQueryContext was moved from the priority
write lock to the cheaper cache state lock, which left the map reachable from
two locks at once.
Guard all three query_map accessors with a dedicated leaf mutex so the map has
a single owning lock regardless of which cache lock the caller holds. The mutex
is taken last and never nests another cache lock under it, so it cannot change
the existing lock order. The earlier optimization of keeping the read off the
priority write lock is preserved.
Reproduced with a concurrent reader/writer witness: 2073 overlapping accesses
to query_map without the fix, 0 with it.
Pre-PR validation gate
Session id: cron:clickhouse-worker-slot-1:20260610-143600 |
|
cc @kssenii could you review this? It fixes a data race on |
|
Workflow [PR], commit [5ff6ffc] Summary: ✅
AI ReviewSummaryThis PR fixes the Final VerdictStatus: ✅ Approve |
The previous commit serialized query_map access with query_map_mutex, which fixed the data race that corrupted the map (LOGICAL_ERROR / Server died). But the last-holder decision (use_count() == 2) in ~QueryContextHolder was still made before any lock was taken. A real interleaving remained: 1. the only holder sees use_count() == 2 and decides to release; 2. before it reaches removeQueryContext, another buffer for the same query_id calls getOrSetQueryContext and revives the same context; 3. this holder then erases the map entry anyway. The new holder stays alive but its query_map entry is gone, so subsequent tryGetQueryContext calls cannot find it and enable_filesystem_query_cache_limit stops being enforced for the rest of the query. A later release of the revived context then fails to find its entry (the "Attempt to release query context that does not exist" LOGICAL_ERROR). Move the decision into removeQueryContext, made under the cache write lock that also serializes getOrSetQueryContext, and only erase when the map still points at this exact context and use_count() == 2 (compare-and-erase). A revived or already-removed entry is left untouched instead of throwing. Adds a unit test (FileCacheTest.QueryLimitContextRevivedDuringRelease) that reproduces the revive-during-release interleaving: it fails on the previous code (the revived context becomes undiscoverable) and passes with this change. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (updated for HEAD eff66eb, follow-up commit)This covers the second commit, which addresses the review comment that the last-holder decision was still made before any lock.
Session id: cron:clickhouse-worker-slot-1:20260610-184028 |
|
CI fully finished (Finish Workflow passed). Failures, both pre-existing chronic classes, none PR-caused (this PR fixes the FileCacheQueryLimit data race):
|
| if (query_iter == query_map.end() || query_iter->second != context) | ||
| { | ||
| throw Exception( | ||
| ErrorCodes::LOGICAL_ERROR, | ||
| "Attempt to release query context that does not exist (query_id: {})", | ||
| query_id); | ||
| /// The entry was already removed, or was re-created for a newer holder via | ||
| /// getOrSetQueryContext after this holder decided to release. Both writers run | ||
| /// under the same cache write lock, so observing a different (or missing) context | ||
| /// here means another live holder now owns it. Leave it in place. | ||
| return; |
There was a problem hiding this comment.
Was a test added for this case? Why can we try to remove query context twice?
There was a problem hiding this comment.
Yes. FileCacheTest.QueryLimitContextRevivedDuringRelease in src/Interpreters/tests/gtest_filecache.cpp covers this case. It drives the revive-during-release interleaving deterministically: holder1 takes the context (use_count() == 2); holder2 revives it via getOrSetQueryContext before holder1 releases (use_count() == 3); holder1 releases, which must be a no-op so the revived context survives and stays discoverable via tryGetQueryContext; then holder2 releases and the entry is removed exactly once with no throw. It fails against the pre-fix logic (the revived context becomes undiscoverable, so per-query enforcement is lost) and passes with this change. The full FileCacheTest.* suite is green.
On why a query context can be released more than once: a single query opens one CachedOnDiskReadBufferFromFile per cached file it reads, and each buffer constructs its own QueryContextHolder for the same query_id (getQueryContextHolder hands back the shared context via getOrSetQueryContext). On teardown each ~QueryContextHolder calls removeQueryContext, so the same query_id is released once per buffer. Before this PR the last-holder check (use_count() == 2) was made in ~QueryContextHolder before any lock, so a late release could erase an entry that a still-live or just-revived holder owned, and that stale release threw Attempt to release query context that does not exist. The check now lives in removeQueryContext under the cache write lock (which also serializes the getOrSetQueryContext revival path), with compare-and-erase: it erases only when the map still maps query_id to this exact context and no other holder is alive (use_count() is just the map entry plus this release). Otherwise it is a no-op. A duplicate or late release is then a legitimate concurrent outcome, not an invariant violation.
… context leak The last-holder decision in ~QueryContextHolder still dropped this holder's own reference to the query context outside the cache lock, and removeQueryContext gated the erase on use_count() > 2 before that drop. A query with parallel read streams has several holders for the same query_id, so when two of them release at the same time both observe the shared count, both skip the erase, and after both drop their reference only the map entry remains and is never removed. That orphans query_map[query_id] for the lifetime of the cache; a later query reusing the same query_id then picks up stale per-query limit state. Move the reference drop into removeQueryContext under query_map_mutex and erase only once the map entry is the sole owner, so every reference change to the context is serialized by the lock that also guards getOrSetQueryContext. Add FileCacheTest.QueryLimitConcurrentReleaseNoLeak, which reproduces the concurrent-release leak deterministically (fails on the previous logic, passes now). Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Follow-up commit Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-7:20260706-162800 |
The last-holder path in removeQueryContext erased the query_map entry while ~QueryContextHolder still held the global cache WriteLock. Being the sole owner at that point, the erase destroyed the whole QueryContext (its per-query records map and LRUFileCachePriority queue) under cache->lockCache(), so a query that touched many segments freed all of that state while holding the lock and could block unrelated reserve/eviction work for the duration of teardown. Extract the doomed QueryContextPtr from the map under query_map_mutex and return it, so the caller destroys it after the cache write lock scope has ended. This restores the pre-ClickHouse#109508 teardown timing (the context used to destruct when the holder member fell out of scope, after the lock released) while keeping the under-lock compare-and-erase that fixes the leak and the revival race. The QueryContext and LRU iterator destructors take no cache locks, so destroying it outside the lock is safe. Extend FileCacheTest.QueryLimitConcurrentReleaseNoLeak and QueryLimitContextRevivedDuringRelease to assert that only the last release hands the context back (use_count 1) for out-of-lock destruction and earlier releases return nullptr. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-0:20260706-173400 |
|
Updating the branch to fix the |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 85/87 (97.70%) · Uncovered code |
CI finish ledger — 5ff6ffcCI fully finished on head
No PR-caused failure. Ready for review. Session id: cron:our-pr-ci-monitor:20260706-230000 |
alexey-milovidov
left a comment
There was a problem hiding this comment.
Ok. It was failing. Now it doesn't.
Fix data race on FileCacheQueryLimit::query_map causing LOGICAL_ERROR
Cherry pick #107028 to 25.8: Fix data race on FileCacheQueryLimit::query_map causing LOGICAL_ERROR
…_map causing LOGICAL_ERROR
The two regression tests added by the backport were written against `master`, where `9de468d826bc1c4` renamed the settings type passed to `FileCacheQueryLimit::getOrSetQueryContext`. On 26.5 that method still takes `const ReadSettings &` and `FilesystemCacheSettings` does not exist, so clang typo-corrected it to the unrelated `FileCacheSettings` and the `amd_debug`, `amd_asan_ubsan` and `amd_tsan` builds failed on `src/Interpreters/tests/gtest_filecache.cpp`. The cherry-pick produced no textual conflict because both tests are appended at the end of the file. Use `ReadSettings` with `filesystem_cache_max_download_size`, which is the pre-rename spelling of the same value read by `getOrSetQueryContext` on this branch, so the assertions are unchanged. `ReadSettings` is only forward-declared in `QueryLimit.h`, so include `IO/ReadSettings.h` explicitly. Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=114585&sha=46540245a0d34a4f50e96e6dabb0aa5b58a83b35&name_0=BackportPR Related: #114585 Related: #107028 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Backport #107028 to 26.5: Fix data race on FileCacheQueryLimit::query_map causing LOGICAL_ERROR
Cherry pick #107028 to 26.3: Fix data race on FileCacheQueryLimit::query_map causing LOGICAL_ERROR
…_map causing LOGICAL_ERROR
Backport #107028 to 26.3: Fix data race on FileCacheQueryLimit::query_map causing LOGICAL_ERROR
Backport #107028 to 25.8: Fix data race on FileCacheQueryLimit::query_map causing LOGICAL_ERROR
Backport #107028 to 26.6: Fix data race on FileCacheQueryLimit::query_map causing LOGICAL_ERROR
Both sides appended new tests to the end of `src/Interpreters/tests/gtest_filecache.cpp`. Resolved by keeping both: the two `readBigAt` tests from this backport and the two `FileCacheQueryLimit` tests that `26.6` gained from the #107028 backport. Co-Authored-By: Claude Opus 5 <[email protected]>
…mit::query_map causing LOGICAL_ERROR
…y-limit-race Fix data race on FileCacheQueryLimit::query_map causing LOGICAL_ERROR
…mit::query_map causing LOGICAL_ERROR
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix a rare
LOGICAL_ERROR"Attempt to release query context that does not exist" and the accompanying server crash when readingMergeTreetables through a filesystem cache disk created withenable_filesystem_query_cache_limit = 1.Description
FileCacheQueryLimit::query_map(astd::unordered_map) was reachable from two different cache locks with no single lock serializing it:tryGetQueryContext(query_map.find) runs underCacheStateGuard::Lock(called fromFileCache::doTryReserve, once per reservation);getOrSetQueryContext(query_map.emplace) andremoveQueryContext(query_map.erase) run underCachePriorityGuard::WriteLock(called fromFileCache::getQueryContextHolderand~QueryContextHolder).Since the read takes a different mutex than the writes, a
find()can run concurrently with anemplace()/erase()that rehashes the table and invalidates buckets and iterators. That is undefined behaviour onstd::unordered_mapand surfaces as eitherAttempt to release query context that does not exist(the map is corrupted so a present key looks absent inremoveQueryContext) or a server crash while reading a half-rehashed bucket. Both were seen together in the same CI run onStateless tests (amd_debug, sequential).The split appeared when
tryGetQueryContextwas moved from the priority write lock to the cheaper cache state lock, leaving the map reachable from two locks at once.Fix: guard all three
query_mapaccessors with a dedicated leaf mutex, so the map has a single owning lock regardless of which cache lock the caller holds. The mutex is taken last and never nests another cache lock under it, so it does not change the existing lock order, and the optimization of keeping the read off the priority write lock is preserved.Reproduced with a concurrent reader/writer witness over an S3-backed cache disk with
enable_filesystem_query_cache_limit = 1: 2073 overlapping accesses toquery_mapwithout the fix, 0 with it.Follow-up: last-holder release leak (#109508)
@ Algunenano found a related issue by code analysis (#109508): the last-holder decision in
~QueryContextHolderstill dropped this holder's own reference to the context outside the cache lock, andremoveQueryContextgated the erase onuse_count() > 2before that drop.use_count()is not a synchronization primitive, so this is a TOCTOU. A query with parallel read streams has several holders for the samequery_id(eachCachedOnDiskReadBufferFromFilecreates its own), souse_count > 2. When two holders release at the same time both observe the shared count, both skip the erase, and after both drop their reference only the map entry remains and is never removed. That orphansquery_map[query_id]for the lifetime of the cache, so a later query reusing the samequery_idpicks up stale per-query limit state.Fix: drop this holder's reference inside
removeQueryContextunderquery_map_mutexand erase only once the map entry is the sole owner (use_count() == 1). Every reference change to the context is then serialized by the lock that also guardsgetOrSetQueryContext, so the check-and-erase is atomic with respect to concurrent holders. AddedFileCacheTest.QueryLimitConcurrentReleaseNoLeak, which drives the concurrent-release interleaving deterministically (fails on the previoususe_count() > 2logic, passes now).Related: #109508
Version info
26.7.1.840(included in26.7and later)26.6.3.44,26.5.7.53,26.3.18.29,25.8.30.20