Skip to content

Close terminated vMCP sessions instead of waiting for eviction - #6807

Merged
JAORMX merged 3 commits into
stacklok:mainfrom
hellouz818:fix/6762-terminate-removes-session-cache-entry
Oct 15, 2026
Merged

JAORMX merged 3 commits into
stacklok:mainfrom
hellouz818:fix/6762-terminate-removes-session-cache-entry

Conversation

@hellouz818

@hellouz818 hellouz818 commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Manager.Terminate() deleted a vMCP session's storage record but left the entry in the node-local ValidatingCache. 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 Terminate doc comment described reclamation as deferred to "the next Get", where checkSession detects ErrSessionNotFound and onEvict closes 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 that Get may never come. ValidatingCache offered no way to fix this at the call site either: 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 × per-session footprint rather than by concurrency.

  • Add ValidatingCache.Remove(key K) bool, mirroring RemoveMatching's lock discipline: removal under mu (which buffers the eviction), user onEvict drained off the lock via drainEvictions. Removing an absent key is a no-op returning false.
  • Call sm.sessions.Remove(sessionID) from Terminate's Phase 2 branch, after storage.Delete. 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.
  • Update the Terminate doc comment, which documented the old lazy-reclamation behaviour.

Ordering note: storage is deleted first 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 — see Special notes for reviewers.

Fixes #6762

Type of change

  • Bug fix
  • New feature
  • Refactoring (no behavior change)
  • Dependency update
  • Documentation
  • Other (describe):

Test plan

  • Unit tests (task test)
  • E2E tests (task test-e2e)
  • Linting (task lint-fix)
  • Manual testing (describe below)

task test passes in full locally, and task lint-fix reports 0 issues. Note
that the full suite needs a container runtime available: without one,
pkg/container/docker, pkg/api and the cmd/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 and
re-running):

  • TestRegression_Terminate_RemovesCacheEntryAndClosesSession — the
    deterministic repro from the issue: after Terminate, sessions.Len() is 0
    and Close() has fired exactly once. The count is taken immediately after
    Terminate returns, so it pins that the close happened there and not at
    cache teardown.
  • TestRegression_Terminate_RepeatedIsSafe — terminating twice does not
    double-close.

Existing-behavior guardrail:

  • TestRegression_Terminate_StorageDeleteFailureKeepsCacheEntry — a failed
    storage delete preserves the cached entry and does not close the session.
    This test passes with or without the new Terminate cache-removal call.

Unit coverage for the new cache API:

  • TestRemove
  • TestRemove_AbsentKey
  • TestRemove_Idempotent
  • TestRemove_SlowOnEvictDoesNotBlockOtherKeys

These 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 was OOMKilled (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

File Change
pkg/cache/validating_cache.go Add Remove(key K) bool; reflect it in the type doc and mu field comment
pkg/cache/validating_cache_test.go 4 tests for Remove
pkg/vmcp/server/sessionmanager/session_manager.go Terminate Phase 2 removes the cache entry after the storage delete; doc comment updated
pkg/vmcp/server/sessionmanager/session_manager_test.go 3 regression tests

Does 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 DELETE still leave their cache entry until TTL-driven storage expiry plus a later eviction; entries cached on other replicas still wait for checkSession on 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. loadSession already guards the main one: it finishes with storage.Update (SET XX) and, on (false, nil), closes the restored session and returns ErrSessionNotFound. So a restore whose metadata update runs after Terminate's storage.Delete cannot complete that update and reach the cache.

A narrow window remains between that Update returning true and Get's miss path inserting the value:

v, loadErr := c.load(ctx, key)                            // Update returned true
// <- a Terminate landing entirely here deletes storage, finds the cache
//    empty, and the in-flight Get then inserts a retained entry
if alreadySet, _ := c.lruCache.ContainsOrAdd(key, v); alreadySet {

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 singleflight group is not a candidate on its own, since Do coalesces callers and would hand a Remove the in-flight Get'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. RemoveMatching is 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.CacheCapacity still has no non-test caller and is not exposed through the VirtualMCPServer CRD, the vmcp config file, or a CLI flag, so it remains fixed at defaultCacheCapacity = 1000. Left as-is here since it is a separate concern from the retention itself.

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
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

codecov Bot commented Oct 12, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 79.47%. Comparing base (0c25322) to head (69bda6a).
⚠️ Report is 1 commits behind head on main.

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Comment thread pkg/cache/validating_cache.go Resolved
@JAORMX
JAORMX merged commit 607cbe8 into stacklok:main Oct 15, 2026
47 checks passed
@JAORMX JAORMX mentioned this pull request 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]>
@github-actions github-actions Bot mentioned this pull request Oct 19, 2026
2 tasks
@hellouz818
hellouz818 deleted the fix/6762-terminate-removes-session-cache-entry branch November 23, 2026 05:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

vMCP: Terminate() retains backend connections in the node-local cache until eviction

2 participants