Skip to content

Sweep terminated sessions from the node-local cache - #7259

Merged
aponcedeleonch merged 1 commit into
stacklok:mainfrom
HankGrimm:fix/session-cache-background-sweep
Nov 24, 2026
Merged

aponcedeleonch merged 1 commit into
stacklok:mainfrom
HankGrimm:fix/session-cache-background-sweep

Conversation

@HankGrimm

Copy link
Copy Markdown
Contributor

Summary

A session terminated on another replica is deleted from shared storage, but
its MultiSession stays in the caching replica's node-local ValidatingCache:
checkSession only runs on a cache hit, which never comes once the client is
done with the session, so the backend connections and per-session state leak
until LRU eviction.

  • Add a background sweep to the session Manager that periodically validates
    cached sessions against storage and evicts the gone/terminated ones, closing
    their backend connections via the existing onEvict path.
  • The sweep reads via LoadMetadata, which does not refresh the Redis TTL, so
    sweeping a live session does not extend its lifetime.
  • Add ValidatingCache.Sweep (predicate runs outside the cache lock so it may
    do I/O) and FactoryConfig.SweepInterval (0 uses the 1m default; negative
    disables).

Fixes #6932

Type of change

  • Bug fix

Test plan

  • Unit tests (task test) — go test ./pkg/cache/ ./pkg/vmcp/server/sessionmanager/
    (new TestValidatingCache_Sweep_EvictsMatchingEntries,
    TestValidatingCache_Sweep_NoMatch_NoEviction, and
    TestSessionManager_SweepExpiredSessions all pass).

Does this introduce a user-facing change?

Yes — sessions terminated on another replica are now reclaimed from the local
cache within SweepInterval (default 1 minute) instead of lingering until LRU
eviction. FactoryConfig.SweepInterval is a new, optional config field.

Special notes for reviewers

  • The sweep deliberately uses LoadMetadata (non-TTL-refreshing), not the
    cache-hit checkSession (which refreshes TTL via Load); sweeping must not
    keep idle live sessions alive.
  • SweepInterval default (1m) and the disable sentinel (negative) are initial
    choices; the cadence trade-off (Redis read cost vs. leak bound) is worth a
    look — the issue reporter may have a preference.

🤖 Generated with Claude Code

A session terminated on another replica is deleted from shared storage, but
its MultiSession stays in the caching replica's node-local ValidatingCache:
checkSession only runs on a cache hit, which never comes once the client is
done with the session, so the backend connections and per-session state leak
until LRU eviction.

Add a background sweep to the session Manager that periodically validates
cached sessions against storage and evicts the gone/terminated ones, closing
their backend connections via the existing onEvict path. The sweep reads via
LoadMetadata so it does not refresh live sessions' Redis TTL. Add
ValidatingCache.Sweep (the predicate runs outside the cache lock so it may do
I/O) and FactoryConfig.SweepInterval (0 uses the 1m default; negative
disables).

Fixes stacklok#6932

Co-Authored-By: Claude Code <[email protected]>
@codecov

codecov Bot commented Nov 24, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 92.85714% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 81.82%. Comparing base (ae8b232) to head (5b07eaa).

Files with missing lines Patch % Lines
pkg/vmcp/server/sessionmanager/session_manager.go 88.00% 3 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #7259      +/-   ##
==========================================
+ Coverage   81.81%   81.82%   +0.01%     
==========================================
  Files         914      914              
  Lines       92619    92661      +42     
==========================================
+ Hits        75773    75823      +50     
+ Misses      16841    16833       -8     
  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.

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

nice, thanks for the contribution!

@aponcedeleonch
aponcedeleonch merged commit c188075 into stacklok:main Nov 24, 2026
42 checks passed
aponcedeleonch added a commit that referenced this pull request Nov 24, 2026
* Stop resync liveness check refreshing session TTL

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

* Deduplicate concurrent capability cache misses

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

* Tie session sweep to health-resync cleanup

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

* Test cleanup reporting a sweep that outlives ctx

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
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: memory grows by several MB per session and is not released after DELETE or session TTL expiry (OOMKilled under session churn)

2 participants