Repository navigation
Cherry pick #107028 to 26.3: Fix data race on FileCacheQueryLimit::query_map causing LOGICAL_ERROR - #114584
Merged
robot-ch-test-poll4 merged 8 commits intoAug 14, 2026
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.
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]>
… 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]>
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-#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]>
Fix data race on FileCacheQueryLimit::query_map causing LOGICAL_ERROR
1 task
…ypick/26.3/107028 # Conflicts: # src/Interpreters/tests/gtest_filecache.cpp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Original pull-request #107028
Do not merge this PR manually
This pull-request is a first step of an automated backporting.
It contains changes similar to calling
git cherry-picklocally.If you intend to continue backporting the changes, then resolve all conflicts if any.
Otherwise, if you do not want to backport them, then just close this pull-request.
The check results does not matter at this step - you can safely ignore them.
Troubleshooting
If the conflicts were resolved in a wrong way
If this cherry-pick PR is completely screwed by a wrong conflicts resolution, and you want to recreate it:
pr-cherrypicklabel from the PRYou also need to check the Original pull-request for
pr-backports-createdlabel, and delete if it's presented thereThe PR source
The PR is created in the CI job