Repository navigation
Conversation
Manager.Terminate's Phase 2 branch deleted the storage record but left the entry in the node-local ValidatingCache, so a terminated session kept its backend connections and its copies of the aggregated capability set. The doc comment described reclamation as deferred to "the next Get", where checkSession would detect ErrSessionNotFound and evict. That path only runs on a cache hit, and a well-behaved client stops using a session ID once it has terminated it, so the entry may never be accessed again. ValidatingCache also offered no way to fix this at the call site: its API was Get/Set/Len/ RemoveMatching, and the only non-test caller of RemoveMatching fires when a backend leaves the registry. That left capacity-triggered LRU eviction as the only reliable reclamation path, so retained memory tracked the cumulative number of sessions ever created rather than the live ones, bounded by CacheCapacity x per-session footprint. Add ValidatingCache.Remove(key) and call it from Terminate after the storage delete. Remove mirrors RemoveMatching's lock discipline: removal under mu, onEvict drained off the lock, so a slow teardown never blocks other keys. onEvict already closes the backend connections, so no new teardown logic is needed, and other replicas keep self-healing through checkSession on their next cache access. Storage is deleted before the cache entry so that a loadSession whose metadata Update runs after the delete is rejected by the pre-existing SET XX guard. This does not make termination race-free: the residual window between that Update returning true and the cache insertion is pre-existing and left out of scope here. A failed storage delete returns before the cache is touched, so a session Validate still reports as alive keeps its connections. Fixes stacklok#6762
hellouz818
requested review from
ChrisJBurns,
JAORMX,
amirejaz,
jerm-dro,
jhrozek and
tgrunnagle
as code owners
October 12, 2026 09:19
codespell flags the possessive "Get's" as a misspelling of "Gets". Rephrase to "the cache insertion on the Get miss path"; no behavior change.
Review follow-ups on the regression tests: - Count Close() calls instead of relying on gomock's end-of-test verification. The success and repeat-termination tests now assert exactly one close immediately after Terminate returns, which distinguishes a close during Terminate from one at cache teardown. - The storage-delete-failure test asserted only that the cache entry survived. Close().AnyTimes() would have tolerated a stray close, so Len()==1 alone did not prove the backend connections were still open. It now asserts zero closes as well, and its doc comment records that it holds on both old and new code: it is a guardrail against a future change removing the entry ahead of a successful delete, not coverage for this fix. - Two existing doc comments (TestRemoveMatching, and TestTerminate_Phase2DetectionUsesIdentityBindingKey) ended up above the newly inserted tests. Moved them back above the functions they describe.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #6807 +/- ##
==========================================
- Coverage 79.52% 79.47% -0.05%
==========================================
Files 810 811 +1
Lines 82147 82175 +28
==========================================
- Hits 65324 65308 -16
- Misses 16818 16862 +44
Partials 5 5 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
JAORMX
approved these changes
Oct 15, 2026
3 of 10 tasks
JAORMX
added a commit
that referenced
this pull request
Oct 15, 2026
Distinguish eager cache removal from callback completion under shared eviction draining. Correct lock ownership guarantees and stale lazy-eviction test comments after #6807 without changing behavior. Co-authored-by: Mecatl <[email protected]>
1 task
hellouz818
deleted the
fix/6762-terminate-removes-session-cache-entry
branch
November 23, 2026 05:10
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.
Summary
Manager.Terminate()deleted a vMCP session's storage record but left the entry in the node-localValidatingCache. That entry holds the session's live backend connections and its copies of the aggregated capability set, so a terminated session kept holding both.The
Terminatedoc comment described reclamation as deferred to "the next Get", wherecheckSessiondetectsErrSessionNotFoundandonEvictcloses the connections. That path only runs on a cache hit, and a well-behaved client stops using a session ID once it has terminated it — so thatGetmay never come.ValidatingCacheoffered no way to fix this at the call site either: its API wasGet/Set/Len/RemoveMatching, and the only non-test caller ofRemoveMatchingfires when a backend leaves the registry.That left capacity-triggered LRU eviction as the only reliable reclamation path, so retained memory tracked the cumulative number of sessions ever created rather than the live ones, bounded by
CacheCapacity × per-session footprintrather than by concurrency.ValidatingCache.Remove(key K) bool, mirroringRemoveMatching's lock discipline: removal undermu(which buffers the eviction), useronEvictdrained off the lock viadrainEvictions. Removing an absent key is a no-op returningfalse.sm.sessions.Remove(sessionID)fromTerminate's Phase 2 branch, afterstorage.Delete.onEvictalready closes the backend connections, so no new teardown logic is needed, and other replicas keep self-healing throughcheckSessionon their next cache access.Terminatedoc comment, which documented the old lazy-reclamation behaviour.Ordering note: storage is deleted first so that a
loadSessionwhose metadataUpdateruns after the delete is rejected by the pre-existing SET XX guard. This does not make termination race-free — see Special notes for reviewers.Fixes #6762
Type of change
Test plan
task test)task test-e2e)task lint-fix)task testpasses in full locally, andtask lint-fixreports 0 issues. Notethat the full suite needs a container runtime available: without one,
pkg/container/docker,pkg/apiand thecmd/thv-operator/test-integration/...packages fail with
no available runtime found/Cannot connect to the Docker daemon. The packages this PR touches —pkg/cache,pkg/vmcp/server/sessionmanager,pkg/vmcp/server— pass either way.Seven new tests.
Regression coverage for this fix. These two fail when the
sm.sessions.Remove(sessionID)call is reverted (verified by reverting it andre-running):
TestRegression_Terminate_RemovesCacheEntryAndClosesSession— thedeterministic repro from the issue: after
Terminate,sessions.Len()is 0and
Close()has fired exactly once. The count is taken immediately afterTerminatereturns, so it pins that the close happened there and not atcache teardown.
TestRegression_Terminate_RepeatedIsSafe— terminating twice does notdouble-close.
Existing-behavior guardrail:
TestRegression_Terminate_StorageDeleteFailureKeepsCacheEntry— a failedstorage delete preserves the cached entry and does not close the session.
This test passes with or without the new
Terminatecache-removal call.Unit coverage for the new cache API:
TestRemoveTestRemove_AbsentKeyTestRemove_IdempotentTestRemove_SlowOnEvictDoesNotBlockOtherKeysThese cover removal, exactly-once eviction callbacks, absent-key and repeated
removal behavior, and teardown outside the cache lock.
Production observation of the defect (not of the fix): this was found on a production deployment (ToolHive v0.51.4,
VirtualMCPServer, 5 backends) where the vMCP pod wasOOMKilled(exit 137) every 8–17 hours depending on load, with container memory climbing alongside the cumulative session count while live sessions stayed flat (~20). The code-level assertions above are what pin the defect; the production numbers are supporting evidence, not proof of causality.Production validation of the fix is pending. This patch has not yet been deployed to that cluster, so the Manual testing box is left unchecked.
Changes
pkg/cache/validating_cache.goRemove(key K) bool; reflect it in the type doc andmufield commentpkg/cache/validating_cache_test.goRemovepkg/vmcp/server/sessionmanager/session_manager.goTerminatePhase 2 removes the cache entry after the storage delete; doc comment updatedpkg/vmcp/server/sessionmanager/session_manager_test.goDoes this introduce a user-facing change?
Yes. A session that is explicitly terminated (client
DELETE) now releases its node-local cache entry and its backend connections immediately, on the replica that handled the termination, instead of holding them until some later eviction trigger.Scope, to be precise about what this does not change: sessions that end without a
DELETEstill leave their cache entry until TTL-driven storage expiry plus a later eviction; entries cached on other replicas still wait forcheckSessionon their next access; and the residual insertion race described below is untouched. So retention is reduced for the explicit-termination path, not eliminated in general.Special notes for reviewers
This does not close every termination race, by design.
loadSessionalready guards the main one: it finishes withstorage.Update(SET XX) and, on(false, nil), closes the restored session and returnsErrSessionNotFound. So a restore whose metadata update runs afterTerminate'sstorage.Deletecannot complete that update and reach the cache.A narrow window remains between that
UpdatereturningtrueandGet's miss path inserting the value:There is no I/O in that gap, so it is very narrow, and it is pre-existing — this patch neither widens it nor depends on it being closed; the entry it can produce is exactly the kind this issue describes. Closing it would need extra synchronisation or validation around cache insertion, and I would rather follow your preference on the approach than pick one here. One note either way: the cache's existing
singleflightgroup is not a candidate on its own, sinceDocoalesces callers and would hand aRemovethe in-flightGet's result without running its own function.Also deliberately out of scope: sessions whose clients disconnect without sending
DELETE. Their storage record expires on its TTL but nothing touches the cache entry.RemoveMatchingis already the right primitive for a periodic sweep, but that adds a storage read per cached session, so it seems better as its own change. Happy to take either follow-up on, separately or here, if you would rather see them together.FactoryConfig.CacheCapacitystill has no non-test caller and is not exposed through theVirtualMCPServerCRD, the vmcp config file, or a CLI flag, so it remains fixed atdefaultCacheCapacity = 1000. Left as-is here since it is a separate concern from the retention itself.