Skip to content

Reduce vMCP memory held by idle sessions and bursts - #7265

Merged
aponcedeleonch merged 4 commits into
mainfrom
vmcp-abandoned-session-memory
Nov 24, 2026
Merged

aponcedeleonch merged 4 commits into
mainfrom
vmcp-abandoned-session-memory

Conversation

@aponcedeleonch

@aponcedeleonch aponcedeleonch commented Nov 24, 2026 •

Copy link
Copy Markdown
Member

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 or list_changed notification 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 uses LookupOwner, 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:

    • Each caller waits on its own context, so a cancelled request returns right away instead of waiting on someone else's sweep.
    • A view built after the leading request was cancelled is neither cached nor shared. DefaultAggregator can 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.
    • A sweep that overlaps InvalidateAll doesn't put a stale view back into the cache.
    • Expired entries are pruned after each sweep instead of staying resident until LRU pressure evicts them.
    • A panic in the wrapped aggregator is recovered and returned as an error. With singleflight the sweep runs on its own goroutine, so an unrecovered panic would take down the process instead of a single request.
  • 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.WithSweptSessionHook option, instead of waiting for the next health or list_changed trigger. 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

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

pkg/vmcp/server and pkg/vmcp/aggregator pass 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 old GetMultiSession check. Locally, a few tests in pkg/desktop, pkg/plugins/pluginsvc and pkg/vmcp/optimizer/internal/similarity fail the same way with and without this change; nothing here touches those packages.

Changes

File Change
pkg/vmcp/server/serve_list_changed.go Resync liveness check uses LookupOwner instead of GetMultiSession
pkg/vmcp/server/serve_list_changed_test.go, serve_health_resync_test.go Cover gone, storage-error and shutdown cases, assert GetMultiSession is never called, add the TTL regression test
pkg/vmcp/aggregator/caching_aggregator.go Singleflight dedupe, per-caller cancellation, no caching or sharing of views built under a cancelled context, invalidation generation, expired-entry pruning, panic recovery with the stack logged
pkg/vmcp/server/sessionmanager/session_manager.go, factory.go WithSweptSessionHook option, cancellable sweep context, per-read timeout, cleanup waits for the loop
pkg/cache/validating_cache.go Sweep returns the evicted keys and stops once its context ends
pkg/vmcp/server/serve.go, serve_health_resync.go, serve_list_changed.go, server.go Wire the sweep hook to the health-resync registry and update the lifecycle comments
pkg/vmcp/server/sessionmanager/session_manager_test.go, pkg/cache/validating_cache_test.go Real sweep loop, interval defaults, in-flight cancellation, TTL not refreshed by the sweep, Sweep lock and re-check guarantees
pkg/vmcp/aggregator/caching_aggregator_test.go, export_test.go Tests for the above, with an injectable clock for pruning
docs/arch/10-virtual-mcp-architecture.md, docs/arch/13-vmcp-scalability.md Describe the new resync liveness check, the sweep as a release path, and registration cleanup

Does this introduce a user-facing change?

Yes.

  • Before: an abandoned session could be kept alive indefinitely by backend health changes or list_changed notifications, holding its backend connections and capability copies. After: it expires on its normal TTL regardless of backend activity, and the background sweep reclaims it.
  • Before: concurrent requests from the same caller that missed the capability cache each swept every backend. After: they share one sweep.
  • Before: an expired or remotely terminated session kept its health-resync registration until a backend health change or list_changed arrived. After: the session cache sweep drops it when it reclaims the session (within SweepInterval, 1 minute by default).
  • Embedders that call sessionmanager.New directly: 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.
  • Embedders that build the core with core.New and serve it themselves see no behavior change. The NewCachingAggregator doc now says core.New doesn't install the cache and when it's safe to wrap an aggregator with it.

Implementation plan

Approved implementation plan
  1. Resync liveness: replace the GetMultiSession guard in runListChangedResync with LookupOwner. Prune the health-resync registration only on ErrSessionNotFound. Skip without pruning on any other error or when the server is stopping. Update the architecture doc.
  2. Capability cache: keep it where it is (installed by server.New) and make it safe under bursts.
    • Deduplicate concurrent misses per cache key with singleflight.DoChan, re-checking the cache inside the flight.
    • Each caller selects on its own context. If the leader's context ends, waiters with a live context run their own sweep.
    • Don't cache or share a result built under a cancelled context, since the wrapped aggregator can return a partial view without an error.
    • Guard against InvalidateAll racing an in-flight sweep with a generation counter, also folded into the flight key.
    • Prune expired entries after each successful sweep.
    • Recover panics inside the flight.
    • Document that core.New doesn't install the cache.

Special notes for reviewers

  • The cache isn't moved into 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. The NewCachingAggregator doc spells out that condition.
  • Leader cancellation is detected through the leader's own ctx.Err(), not by matching context errors alone. A per-backend timeout can return DeadlineExceeded while the leader's request is still live, and matching on the error would send every waiter into its own sweep.
  • The fallback sweep after a leader cancellation isn't deduplicated. It keeps the logic simple, and waiters could rejoin a new flight later if that turns out to matter.
  • The swept-session hook fires only for sessions the sweep evicts because their record is gone or terminated, never for LRU or other cache removals, whose sessions may still be live. Sweep returns only keys it actually removed, so a session replaced by a concurrent Set keeps its registration. The lazy prune in runListChangedResync stays as the fallback for sessions the sweep never sees.
  • Serve now builds the Server before the session manager so it can pass srv.healthResync.remove as the hook. The method value binds the registry's address before the sweep goroutine starts, and the registry has its own lock.
  • store and InvalidateAll share a mutex rather than using an atomic generation, so a bump and purge can't land between the generation check and the Add.

🤖 Generated with Claude Code

aponcedeleonch and others added 2 commits November 24, 2026 16:31
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]>
@github-actions github-actions Bot added the size/L Large PR: 600-999 lines changed label Nov 24, 2026
rdimitrov
rdimitrov previously approved these changes Nov 24, 2026

@rdimitrov rdimitrov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@peppescg

Copy link
Copy Markdown
Contributor

Thanks for this. Switching the resync liveness check to LookupOwner closes a bigger gap than the ones we had noted on #7259.

A few points from our review of #7259 that this PR does not cover yet. Each could be a follow-up:

  1. The health-resync registration is now pruned only on the next health or list_changed trigger. When the Sweep terminated sessions from the node-local cache #7259 sweep evicts a session and no trigger follows, the registration stays. Pruning it in the sweep would make the cleanup independent of backend activity.
  2. Tests: no test starts the real sweepLoop (default interval, negative value, stop on cleanup). No test checks that the sweep does not refresh the session TTL. No test covers the two Sweep guarantees: pred runs outside the lock, and the sameEntry re-check protects a concurrent Set.
  3. sweepExpiredSessions still uses context.Background() with no per-call timeout, and cleanup does not cancel a sweep in flight. A cancellable context from New and a per-read timeout, as checkSession does with restoreStorageTimeout, would bound both.
  4. docs/arch/13-vmcp-scalability.md still says that cached sessions are released only by LRU eviction or explicit termination.

@codecov

codecov Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.00000% with 5 lines in your changes missing coverage. Please review.
✅ Project coverage is 81.84%. Comparing base (44f7d63) to head (2ff23d9).

Files with missing lines Patch % Lines
pkg/vmcp/aggregator/caching_aggregator.go 92.85% 5 Missing ⚠️
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.
📢 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.

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]>
@aponcedeleonch

Copy link
Copy Markdown
Member Author

@peppescg thanks for the thorough pass. I folded all four into this PR in 3965d0e instead of leaving them as follow-ups.

  1. Registration pruning in the sweep. sessionmanager.New takes a new WithSweptSessionHook option, called with the ID of each session the sweep evicts because its record is gone or terminated. Serve wires it to healthResync.remove, so the registration goes away with the cached session, without waiting for a health or list_changed trigger. To make that possible, ValidatingCache.Sweep now returns the evicted keys instead of a count. A key whose entry was replaced by a concurrent Set isn't returned, so a live session never loses its registration. The hook doesn't fire for LRU or other cache removals, since those sessions may still be live. The lazy prune in runListChangedResync stays as the fallback for sessions the sweep never sees (already LRU-evicted, or the sweep disabled).
  2. Tests.
    • TestSessionManager_SweepLoop starts the real loop: it evicts a gone session and calls the hook, cleanup stops the loop and is safe to call twice, a negative interval starts no loop, and cleanup cancels a read in flight.
    • TestResolveSweepInterval covers the 0 / negative / positive mapping. The 0 → 1m default is pulled into resolveSweepInterval so it's testable without waiting a minute.
    • TestSessionManager_SweepDoesNotExtendSessionLifetime sweeps far more often than a short TTL and checks the session still expires and is reclaimed.
    • On the cache side, TestValidatingCache_Sweep_PredRunsOutsideLock calls Set from inside pred with a deadlock timeout, and TestValidatingCache_Sweep_KeepsConcurrentlyReplacedEntry covers the sameEntry re-check.
  3. Context and timeouts. New now starts the loop with a cancellable context. Cleanup cancels it and waits for the loop to exit, bounded by the cleanup ctx. Each LoadMetadata gets restoreStorageTimeout, same as checkSession. Sweep also stops calling pred once its ctx ends, so a cancelled sweep doesn't walk the rest of the cache.
  4. Docs. docs/arch/13-vmcp-scalability.md now describes the sweep as a release path, adds it to the garbage collection table, and mentions the registration cleanup. docs/arch/10-virtual-mcp-architecture.md is updated the same way for the health-resync registry.

peppescg
peppescg previously approved these changes Nov 24, 2026
@github-actions github-actions Bot added size/XL Extra large PR: 1000+ lines changed and removed size/L Large PR: 600-999 lines changed size/XL Extra large PR: 1000+ lines changed labels Nov 24, 2026
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]>
@github-actions github-actions Bot added size/XL Extra large PR: 1000+ lines changed and removed size/XL Extra large PR: 1000+ lines changed labels Nov 24, 2026
@aponcedeleonch
aponcedeleonch merged commit c6c1b40 into main Nov 24, 2026
77 of 78 checks passed
@aponcedeleonch
aponcedeleonch deleted the vmcp-abandoned-session-memory branch November 24, 2026 16:00
@github-actions github-actions Bot mentioned this pull request Nov 24, 2026
2 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size/XL Extra large PR: 1000+ lines changed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants