Skip to content

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 into
backport/26.3/107028from
cherrypick/26.3/107028
Aug 14, 2026
Merged

robot-ch-test-poll4 merged 8 commits into
backport/26.3/107028from
cherrypick/26.3/107028

Conversation

@robot-ch-test-poll2

Copy link
Copy Markdown
Contributor

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-pick locally.
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:

  • delete the pr-cherrypick label from the PR
  • delete this branch from the repository

You also need to check the Original pull-request for pr-backports-created label, and delete if it's presented there

The PR source

The PR is created in the CI job

groeneai and others added 7 commits June 10, 2026 16:00
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
@robot-ch-test-poll2 robot-ch-test-poll2 added pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only! do not test disable testing on pull request pr-bugfix Pull request with bugfix, not backported by default labels Aug 13, 2026
…ypick/26.3/107028

# Conflicts:
#	src/Interpreters/tests/gtest_filecache.cpp
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

do not test disable testing on pull request pr-bugfix Pull request with bugfix, not backported by default pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only!

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants