Repository navigation
Reduce vMCP memory held by idle sessions and bursts - #7265
Conversation
The list_changed/health resync opened with a GetMultiSession liveness check. That goes through the node-local cache: a hit runs checkSession, whose storage.Load refreshes the session TTL (GETEX on Redis, the last-access time in memory), and a miss restores the session and opens backend connections. The resync fires for every registered session on each backend health change and on each backend list_changed, so sessions abandoned without a DELETE were kept alive for as long as backends flapped. The expiry sweep from #7259 then never reclaimed them, which contributed to OOM kills from abandoned sessions. Check liveness with LookupOwner instead. It reads metadata only, never restores, and reports absent or terminated sessions as ErrSessionNotFound, which still prunes the health-resync registration. A storage failure now skips the run without pruning, since it says nothing about whether the session is alive. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A vMCP embedder was OOMKilled on a 512Mi pod. Part of the cause was bursts of concurrent requests from one caller: every request that missed the capability cache ran its own full backend sweep, so up to 24 sweeps ran at once, each allocating tens of MiB. Expired entries were also only checked lazily on read and never removed, so a key that was never requested again kept a full tool catalogue copy in the LRU. Concurrent misses for the same key now share one sweep through singleflight. Each caller waits on its own context, so a cancelled request returns promptly. If the shared sweep ends because the leader's context was cancelled, waiters with a live context sweep on their own context. That covers a sweep that still succeeds with a partial view, since the default aggregator skips backends it could not reach; such a view is neither cached nor shared, so waiters do not get "unknown tool" for the missing backends. An invalidation generation keeps a sweep that overlaps InvalidateAll from repopulating the cache with a pre-invalidation view, and keeps later callers from joining that sweep, which the list_changed resync depends on. A successful sweep also prunes expired entries. A panic in the wrapped aggregator is recovered and returned as an error, because singleflight's DoChan otherwise re-raises it on a goroutine where it crashes the process. Co-Authored-By: Claude Opus 5.5 <[email protected]>
rdimitrov
left a comment
There was a problem hiding this comment.
LGTM. Verified the core claim: LookupOwner → LoadMetadata is a plain GET on both Redis storages and doesn't touch lastAccess on the local one, whereas GetMultiSession → checkSession → storage.Load refreshes TTL (GETEX / lastAccess). The rest of the resync body (serveSessionTools, coreSessionResources/Prompts) never goes back through the session manager, so nothing else re-extends the session. Pruning only on ErrSessionNotFound is the right call.
The singleflight changes read correctly to me: leader-cancel detection via the leader's own ctx.Err() (not the error type) avoids fanning out on per-backend timeouts, the gen check + Add under one mutex closes the InvalidateAll race, and the panic recover is needed since DoChan re-panics on a fresh goroutine. One small non-blocking nit inline.
|
Thanks for this. Switching the resync liveness check to A few points from our review of #7259 that this PR does not cover yet. Each could be a follow-up:
|
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #7265 +/- ##
==========================================
- Coverage 81.88% 81.84% -0.05%
==========================================
Files 915 915
Lines 92769 92853 +84
==========================================
+ Hits 75966 75995 +29
- Misses 16798 16853 +55
Partials 5 5 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Sessions that expire or are terminated on another replica kept their health-resync registration until the next health or list_changed trigger, so cleanup depended on backend activity. The session cache sweep now reports each session it evicts through a new WithSweptSessionHook option, and Serve uses it to drop the registration at the same time. The sweep also ran on context.Background() with no per-read timeout, and cleanup could not stop a sweep in flight. It now runs on a cancellable context from New. Each storage read is bounded by restoreStorageTimeout, and cleanup cancels the sweep and waits for the loop to exit. Also log the stack when the capability cache recovers a panic, since the returned error only carries the panic value. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@peppescg thanks for the thorough pass. I folded all four into this PR in 3965d0e instead of leaving them as follow-ups.
|
Covers the stopSweep path where the cleanup ctx ends before the sweep loop exits, which Codecov flagged as uncovered. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
Two gaps let vMCP hold on to memory it no longer needs. Both show up with clients that leave sessions open without sending DELETE, which most MCP clients do.
The list_changed and health-driven resync checked session liveness with
GetMultiSession. On a cache hit that refreshes the session TTL, and on a miss it restores the session and opens backend connections. So every backend health change orlist_changednotification kept abandoned sessions alive, and the expiry sweep added in Sweep terminated sessions from the node-local cache #7259 never got to reclaim them. The check now usesLookupOwner, which reads metadata only. A session that's gone is still pruned from the health-resync registry. A storage error skips that run without pruning, since it says nothing about whether the session is alive.The capability cache let concurrent misses for the same caller each run a full backend sweep. A burst of requests from one client turned into a burst of parallel sweeps, each building its own copy of the capability view. Concurrent misses for the same key now share one sweep. On top of that:
DefaultAggregatorcan succeed with a partial view in that case, which would otherwise surface as "unknown tool" for every caller sharing it. Waiters with a live context run their own sweep instead.InvalidateAlldoesn't put a stale view back into the cache.The session cache sweep from Sweep terminated sessions from the node-local cache #7259 now also cleans up after itself. A session it reclaims has its health-resync registration dropped right away, through a new
sessionmanager.WithSweptSessionHookoption, instead of waiting for the next health orlist_changedtrigger. The sweep runs on a cancellable context with a per-read timeout, and cleanup cancels a sweep in flight and waits for the loop to exit.Follow-up to #7259.
Type of change
Test plan
task test)task test-e2e)task lint-fix)pkg/vmcp/serverandpkg/vmcp/aggregatorpass with-race. The new resync regression test runs the real session manager against in-memory storage, triggers health changes faster than the TTL, and checks the session still expires and is pruned. It fails against the oldGetMultiSessioncheck. Locally, a few tests inpkg/desktop,pkg/plugins/pluginsvcandpkg/vmcp/optimizer/internal/similarityfail the same way with and without this change; nothing here touches those packages.Changes
pkg/vmcp/server/serve_list_changed.goLookupOwnerinstead ofGetMultiSessionpkg/vmcp/server/serve_list_changed_test.go,serve_health_resync_test.goGetMultiSessionis never called, add the TTL regression testpkg/vmcp/aggregator/caching_aggregator.gopkg/vmcp/server/sessionmanager/session_manager.go,factory.goWithSweptSessionHookoption, cancellable sweep context, per-read timeout, cleanup waits for the looppkg/cache/validating_cache.goSweepreturns the evicted keys and stops once its context endspkg/vmcp/server/serve.go,serve_health_resync.go,serve_list_changed.go,server.gopkg/vmcp/server/sessionmanager/session_manager_test.go,pkg/cache/validating_cache_test.goSweeplock and re-check guaranteespkg/vmcp/aggregator/caching_aggregator_test.go,export_test.godocs/arch/10-virtual-mcp-architecture.md,docs/arch/13-vmcp-scalability.mdDoes this introduce a user-facing change?
Yes.
list_changednotifications, holding its backend connections and capability copies. After: it expires on its normal TTL regardless of backend activity, and the background sweep reclaims it.list_changedarrived. After: the session cache sweep drops it when it reclaims the session (withinSweepInterval, 1 minute by default).sessionmanager.Newdirectly: the cleanup function now cancels a sweep in flight and waits for the loop to exit, bounded by the ctx passed to it, and can return an error if that ctx ends first.core.Newand serve it themselves see no behavior change. TheNewCachingAggregatordoc now sayscore.Newdoesn't install the cache and when it's safe to wrap an aggregator with it.Implementation plan
Approved implementation plan
GetMultiSessionguard inrunListChangedResyncwithLookupOwner. Prune the health-resync registration only onErrSessionNotFound. Skip without pruning on any other error or when the server is stopping. Update the architecture doc.server.New) and make it safe under bursts.singleflight.DoChan, re-checking the cache inside the flight.InvalidateAllracing an in-flight sweep with a generation counter, also folded into the flight key.core.Newdoesn't install the cache.Special notes for reviewers
core.New. Doing that by default would be unsafe for an embedder whose aggregator reads per-request context beyond the cache key inputs (subject, forwarded headers, backend IDs), for example to check a guarded call against a fresh view. TheNewCachingAggregatordoc spells out that condition.ctx.Err(), not by matching context errors alone. A per-backend timeout can returnDeadlineExceededwhile the leader's request is still live, and matching on the error would send every waiter into its own sweep.Sweepreturns only keys it actually removed, so a session replaced by a concurrentSetkeeps its registration. The lazy prune inrunListChangedResyncstays as the fallback for sessions the sweep never sees.Servenow builds theServerbefore the session manager so it can passsrv.healthResync.removeas the hook. The method value binds the registry's address before the sweep goroutine starts, and the registry has its own lock.storeandInvalidateAllshare a mutex rather than using an atomic generation, so a bump and purge can't land between the generation check and theAdd.🤖 Generated with Claude Code