Skip to content

vMCP: memory grows by several MB per session and is not released after DELETE or session TTL expiry (OOMKilled under session churn) #6932

Done

Description

@nilsberberich

Summary

With a steady rate of short-lived sessions (initialize → DELETE), the vMCP container's memory grows linearly by roughly 4–6 MB per session. It is not released when the session is terminated by the client, nor after the session TTL (30 min default) expired and the session storage is empty. Eventually the container is OOMKilled. Raising the memory limit only delays the kill.

Environment

  • ToolHive operator / vMCP v0.55.2, Kubernetes, VirtualMCPServer with 2 replicas
  • 10 backends (MCPServerEntry, streamable HTTP), ≈ 310 tools per session after Cedar filtering (≈ 475 aggregated)
  • Embedded auth server (OIDC upstream, Redis via Sentinel, TLS), session storage Redis (sessionStorage.provider: redis)
  • Cedar authorization (MCPAuthzConfig), conflict resolution prefix, audit enabled
  • Container resources: default 128Mi/512Mi, then raised to 256Mi/1Gi via podTemplateSpec

Reproduction

A test client authenticated once and then ran this loop for 15 minutes:

  1. one tools/call on a long-lived session (unrelated to the leak, kept for comparison)
  2. a new session: initialize (+ notifications/initialized), then DELETE /mcp with the Mcp-Session-Id
  3. sleep 2 s

The vMCP log shows session capabilities injected from core ... tool_count=310 and Manager.Terminate: session terminated for every new session. The two counts match (e.g. 80 created / 80 terminated on one pod in 10 minutes).

Observed (working set via kubectl top, limit 1Gi)

Pod A Pod B
fresh pods, idle 115Mi 42Mi
after run 1 (15 min) 972Mi 812Mi
35 min after run 1 (all sessions terminated or expired; session DB in Redis has 0 keys) 650Mi 570Mi
run 2 starts from there 1Gi after ≈ 4 min, then terminated (Shutdown timeout, exit 1) OOMKilled (exit 137)
10 min of the same load after restart 123 → 538Mi 72 → 402Mi

With the default limit of 512Mi the same load OOMKilled both replicas roughly every 10–12 minutes. Each kill produced a short window of 502 for new sessions. Existing sessions survived thanks to the shared session storage.

Memory released by Go but not returned to the OS would be reused by the second run. Instead, run 2 grew on top of the 650Mi left from run 1.

Expected

Memory associated with a session (backend connections, capability/tool copies, Cedar or audit state, optimizer state, …) is released when the session is terminated or expires, so memory stays bounded under constant session churn.

Notes

Activity

  1. added
    needs-triage
    on Oct 23, 2026
  2. HankGrimm commented on Nov 19, 2026

    @HankGrimm
    Contributor

    I'd like to work on this. I can reproduce the retained-allocation pattern
    locally with a loop of initialize+DELETE against local mock backends and a
    pprof heap profile (no external dependencies), and will report back with
    what's retained before proposing a fix.

  3. jhrozek commented on Nov 19, 2026

    @jhrozek
    Contributor

    Thank you @HankGrimm I assigned the issue to you

  4. removed
    needs-triage
    on Nov 19, 2026
  5. HankGrimm commented on Nov 20, 2026

    @HankGrimm
    Contributor

    Thanks — that heap profile would let me pin the retained type quickly.

    One clarification on "is there a supported way to enable pprof in vMCP": there isn't, and it's deliberate. The diagnostics listener (pkg/diagnostics/server.go) explicitly refuses to register pprof or any handler that exposes process memory/goroutines/config (see the package doc). So there's no built-in debug endpoint to curl.

    The least-effort way to capture one is a throwaway build that registers net/http/pprof on a loopback-only listener, e.g. in Start before the main listener binds (or in cmd/ main):

    import _ "net/http/pprof"
    
    go func() { _ = http.ListenAndServe("127.0.0.1:6060", nil) }()

    Loopback-only, so it doesn't change any NetworkPolicy-visible port surface.

    If that's a hassle on your side, I can push a small branch with an opt-in, env-gated (TOOLHIVE_PROFILE_ADDR, default off) loopback pprof listener that you could deploy to reproduce — just say the word.

    What I'd most want from the profile (captured after the churn loop stops and the session DB is empty, so only the leak is in the heap):

    • go tool pprof -top <binary> heap.prof — top retained types
    • if one type dominates, -list / -alloc_space / -traces for it

    Even just the top ~10 -top lines plus inuse-object counts would be enough to point at ServerTool vs the go-sdk per-session Server vs something else, and I can go from there.

  6. nilsberberich commented on Nov 20, 2026

    @nilsberberich
    ContributorAuthor

    Thanks for picking this up and for the pprof details. We'll go with the throwaway build: v0.66.0 plus a loopback-only net/http/pprof listener, deployed only to our test gateway via podTemplateSpec. We'll rerun the same initialize/DELETE loop, wait until the session TTL has expired and the session store is empty, then capture the heap profile and post the go tool pprof -top output (plus -list/-traces if one type dominates). No need for a branch on your side.

  7. nilsberberich commented on Nov 20, 2026

    @nilsberberich
    ContributorAuthor

    As promised, here is the heap profile.

    Setup: throwaway build of v0.66.0 (same tag/commit and ldflags as the release, minus -s -w) with net/http/pprof on 127.0.0.1:6060 only, deployed to our test gateway (2 replicas, Redis session storage, 18 backends, ~450 aggregated tools). One correction to the original report: the churn loop sends initialize and then DELETE on the session, without notifications/initialized in between. Every 4 s for 15 min, about 216 sessions in total. The operator recreated the pods once after ~2.5 min (config reconcile, unrelated), so the profiled pods saw ~180 of those sessions (about 90 per pod, assuming even distribution).

    Result: container memory (working set) peaked at ~815 MiB per pod (limit 1 GiB) and settled at ~530–580 MiB. After waiting out the 30 min session TTL, the Redis session store was empty (DBSIZE 0). The heap (?gc=1) was unchanged, though: 324 MB in use before the TTL expired and 324 MB after it. A fresh pod uses ~6–12 MB. That is roughly 3.5 MB retained per session (estimate).

    go tool pprof -sample_index=inuse_space -top (after TTL):

          flat  flat%   sum%        cum   cum%
      147.54MB 45.58% 45.58%   147.54MB 45.58%  reflect.mapassign_faststr0
       46.55MB 14.38% 59.96%    46.55MB 14.38%  encoding/json/v2.makeString
       28.50MB  8.80% 68.77%    28.50MB  8.80%  reflect.makemap
       27.10MB  8.37% 77.14%    27.10MB  8.37%  bytes.Clone
          17MB  5.25% 82.39%       17MB  5.25%  reflect.unsafe_New
       14.54MB  4.49% 86.89%    18.07MB  5.58%  github.com/stacklok/toolhive-core/mcpcompat/server.(*clientSession).SetSessionTools
        5.50MB  1.70% 88.58%   161.56MB 49.91%  github.com/stacklok/toolhive-core/mcpcompat/server.toGoSDKTool
        4.10MB  1.27% 89.85%   167.19MB 51.65%  github.com/stacklok/toolhive-core/mcpcompat/server.(*MCPServer).syncSessionTools
    

    The cumulative view (-top -cum) and -peek show where it comes from:

    • ~66%: sessionDispatchMiddleware.func1.1 → (*MCPServer).registerAndSync
      • syncSessionTools → toGoSDKTool → jsonConvert (syncSessionTools 164 MB, of which jsonConvert 157 MB): per-session copies of all tool schemas as map[string]any
      • (*Hooks).registerSession (48 MB)
    • ~26%: (*defaultMultiSessionFactory).initOneBackend (86 MB) → NewHTTPConnector.func1 → initAndQueryCapabilities → queryBackendTools → conversion.ConvertToolInputSchema (74 MB)
    • setSessionToolsDirect → (*clientSession).SetSessionTools (18 MB)

    So the per-session tool state built during initialize (both the converted go-sdk tools and the backend capability/schema copies) stays reachable after the session is deleted and after it has expired from Redis. Something still holds a reference to it, possibly the in-process session map in mcpcompat or the go-sdk ServerSession/client. I suspected the missing notifications/initialized as the trigger and ran a control:

    Control run: same setup and loop, freshly restarted pods, the only difference being that each new session sends notifications/initialized before DELETE (213 sessions in 15 min). Container memory stayed at ~45–75 MiB per pod under load (~30 MiB idle), with no upward trend. Heap in use (?gc=1) went from 12 → 23 → 22 MB on one pod and from 6 → 17 → 13 MB on the other (fresh → after load → after TTL, Redis empty again). That leaves ~7–10 MB per pod after the TTL, against ~320 MB per pod without notifications/initialized (one control run).

    So the leak seems tied to sessions that are deleted before the client sends notifications/initialized. My guess is that the cleanup only covers fully initialized sessions, but I have not traced it in the code.

    I can share the raw .prof files (two pods, before/after load/after TTL, plus the control run) if that helps, and can test a fix build on the same setup.

  8. HankGrimm commented on Nov 21, 2026

    @HankGrimm
    Contributor

    Thanks for the profile and the control run — the notifications/initialized correlation is the key signal, and the -cum breakdown lines up with the code paths I'd expect.

    I traced the Serve-path lifecycle across toolhive-core (mcpcompat/server) and toolhive (pkg/vmcp/server) and found one concrete gap plus one retention chain worth confirming against your v0.66.0 build:

    1. Per-session tools are added to the shared go-sdk Server and never removed on DELETE. On initialize, registerAndSync → OnRegisterSession → injectCoreSessionCapabilities → SetSessionTools, and syncSessionTools calls srv.AddTool(...) on the single *gosdk.Server the shim builds for the whole server (buildServer). RemoveTools is only called inside syncSessionTools when a live session's overlay shrinks. On DELETE, forgetSessionLocked removes the clientSession from s.sessions and closes its notify channel, but never removes that session's tools from the shared server. So the converted tool schemas (your syncSessionTools → toGoSDKTool → jsonConvert ~157 MB) and their handlers stay reachable on srv.

    2. A clientSession retention chain via the list_changed sink. buildListChangedSink builds per-(session, kind) listChangedResyncWorkers whose run closures capture the ClientSession (plus identity + forwarded headers). The KindTools worker is also registered in healthResync (when health monitoring is on and the optimizer is off); the sink itself is stored in the session's backend connectors inside the MultiSession. So even after forgetSession drops the registry entry, the clientSession — and its cs.tools overlay — stays reachable through those closures until the MultiSession is released and the healthResync entry is pruned.

    What I can't reconcile from code alone: point 1 predicts accumulation regardless of notifications/initialized, since the tool-add path is identical in both cases and notifications/initialized only re-enters registerAndSync behind its once-guard (a no-op for the hook + sync). Your clean control run therefore implies a removal path (or a go-sdk session-scoping detail) I'm missing that is gated on the initialized handshake.

    Two things would let me pin that down: (a) the -list / -traces output for the syncSessionTools / toGoSDKTool inuse objects, to see the exact referring path, and (b) confirmation of whether anything drives a per-session RemoveTools on session close in v0.66.0.

    Proposed fix direction (pending the above): in forgetSessionLocked, remove the session's tools from the shared server (srv.RemoveTools(...) over cs.sdkToolNames) before dropping the registry entry. That change lives in stacklok/toolhive-core, not this repo — if it matches your read I'll open the toolhive-core PR and bump the dependency here. If you're willing to share the raw .prof files, I can also read the exact referring path off them and confirm before writing anything.

  9. HankGrimm commented on Nov 21, 2026

    @HankGrimm
    Contributor

    Correction to my previous comment — I got the server topology wrong, and it changes the fix.

    The tools are not on a shared server. StreamableHTTPServer.build wires getServerFunc, and the go-sdk handler calls it once per new client session, so buildServer produces a fresh *gosdk.Server per session (transports.go: "A fresh go-sdk server per client session lets each session carry its own tool/resource overlay"). Each session's registerAndSync then adds that session's tools to its own server.

    So the leak is not "tools accumulating on a shared server" (and a RemoveTools-on-forget fix would be pointless). The leak is that the whole clientSession — and with it its per-session *gosdk.Server (cs.boundServer), its converted tool schemas, and cs.tools — survives DELETE. Two things hold the clientSession alive after forgetSession drops it from s.sessions:

    1. buildListChangedSink builds per-(session, kind) listChangedResyncWorkers whose run closures capture the ClientSession; the sink is stored in the session's MultiSession backend connectors, and the KindTools worker is also registered in healthResync.
    2. forgetSessionLocked drops the registry entry and closes the notify channel but does not clear cs.boundServer / cs.goSession / cs.owner / cs.tools, so whatever still reaches the clientSession keeps the per-session server reachable.

    Corrected fix direction: release the clientSession on DELETE — break the sink/health-resync capture of it (or prune it eagerly), and/or have forgetSessionLocked nil out cs.boundServer/cs.goSession/cs.tools. I still can't reconcile from code alone why the with-notifications/initialized control run is clean, so I'd rather confirm the exact referring path (the raw .prof files, or a local initialize+DELETE churn profile) before writing anything. Happy to send a branch either way.

  10. nilsberberich commented on Nov 21, 2026

    @nilsberberich
    ContributorAuthor

    Thanks for digging in. Here is the -list / -traces output for (a), taken from the existing profiles: the leak run and the control run, both captured after the session TTL had expired. Same build as before; sources resolved against v0.66.0, toolhive-core v0.0.60, go-sdk v1.8.0. Note that a heap profile only shows where the retained objects were allocated, not what still references them, so it can't show the referring chain directly.

    -list (leak run, after TTL, 323.7 MB in use)

    ROUTINE (*MCPServer).syncSessionTools  mcpcompat/server/session.go
        4.10MB   167.19MB (flat, cum) 51.65% of Total
        4.10MB     4.10MB    438:	newNames := make(map[string]struct{}, len(cs.tools))
             .   161.56MB    440:		gt, err := toGoSDKTool(st.Tool)
             .     1.53MB    447:		if !s.addSessionTool(srv, gt, st.Handler) {
    ROUTINE (*clientSession).SetSessionTools  mcpcompat/server/session.go
       14.54MB    18.07MB (flat, cum)  5.58% of Total
        1.54MB     1.54MB    171:	c.tools = make(map[string]ServerTool, len(tools))
          13MB       13MB    173:		c.tools[k] = v
             .     3.53MB    179:			owner.syncSessionTools(srv, c)
    ROUTINE toGoSDKTool  mcpcompat/server/server.go
        5.50MB   161.56MB (flat, cum) 49.91% of Total
        5.50MB     5.50MB   1220:	out := &gosdk.Tool{}
             .   156.06MB   1221:	if err := jsonConvert(t, out); err != nil {
    

    -traces, condensed (json/reflect/runtime frames dropped, first 6 remaining frames per stack, summed per stack, stacks ≥ 4 MB):

    Leak run, after TTL:

    154.2MB  jsonConvert <- toGoSDKTool <- syncSessionTools <- registerAndSync <- sessionDispatchMiddleware.func1.1 <- mcp.handleReceive
     71.8MB  conversion.ConvertToolInputSchema <- backend.queryBackendTools <- backend.initAndQueryCapabilities <- backend.NewHTTPConnector.func1 <- (*defaultMultiSessionFactory).initOneBackend <- makeBaseSession.func1
     26.7MB  (*Server).coreSessionTools <- serveSessionTools <- injectCoreSessionCapabilities <- handleSessionRegistrationImpl <- handleSessionRegistration <- Serve.func7
     14.5MB  (*clientSession).SetSessionTools <- setSessionToolsDirect <- injectCoreSessionCapabilities <- handleSessionRegistrationImpl <- handleSessionRegistration <- Serve.func7
      5.5MB  toGoSDKTool <- syncSessionTools <- registerAndSync <- ...
      5.1MB  client.modernListAll.func1 <- pagination.ListAll <- client.modernListAll <- (*httpBackendClient).modernEnumerate <- modernListCapabilities <- ListCapabilities.func1
      4.1MB  syncSessionTools <- registerAndSync <- sessionDispatchMiddleware.func1.1 <- mcp.handleReceive <- ...
      4.0MB  mcp.NewClient <- (*Client).Initialize <- backend.initAndQueryCapabilities <- backend.NewHTTPConnector.func1 <- initOneBackend <- makeBaseSession.func1
    

    Control run (with notifications/initialized), after TTL, ~22 MB in use:

      2.6MB  jsonConvert <- toGoSDKTool <- syncSessionTools <- registerAndSync <- ...
      2.6MB  conversion.ConvertToolInputSchema <- backend.queryBackendTools <- ... <- initOneBackend <- makeBaseSession.func1
      1.5MB  jsonConvert <- toGoSDKTool <- syncSessionTools <- (*clientSession).SetSessionTools <- setSessionToolsDirect <- (*Server).lazyInjectSessionTools
      1.0MB  (*Server).coreSessionTools <- serveSessionTools <- lazyInjectSessionTools <- Serve.func9 <- (*Hooks).beforeCallTool
    

    Two observations that may help with the referring path:

    1. About 72 MB (22%) of what survives was allocated while makeBaseSession / initOneBackend built the backend connectors (the per-backend tool lists), not on the clientSession path. That suggests the MultiSession's connectors are retained as well, not only cs.boundServer / cs.tools.
    2. Health monitoring is on in our deployment (the profile has health.(*Monitor).performHealthCheck frames) and the optimizer is off, so every session goes through s.healthResync.add(sessionID, toolsResyncWorker) in handleSessionRegistrationImpl. In v0.66.0 I only find healthResync.remove on the registration error path, in terminateOnBindingFailure, and in the lazy liveness check of runListChangedResync. A client DELETE doesn't seem to remove the entry, and the lazy prune only runs when a resync is triggered (health change or backend list_changed). Our backends were stable during the run, so as far as I can tell nothing triggered it, which would fit the entries (and the captured ClientSession) piling up. It wouldn't explain observation 1, though: the sink is handed to the connectors, not the other way round, so something else may be holding the MultiSession.

    This still doesn't explain why the control run is clean. The only visible difference in the control profile is that tools were injected via lazyInjectSessionTools (beforeCallTool hook) rather than via handleSessionRegistration, but that may just be the few sessions still alive at capture time.

    On (b): in v0.66.0 I don't see anything that calls a per-session RemoveTools on session close; your corrected reading (fresh *gosdk.Server per session) matches what I see in transports.go.

    If it helps, we could run another round on our test gateway with a goroutine profile after the TTL, or test a branch.

  11. HankGrimm commented on Nov 22, 2026

    @HankGrimm
    Contributor

    Thanks — the -traces nails the two allocation sites. Two things:

    On (b): I think the health-resync entry is pruned on DELETE, via pruneOnTerminateSessionIDManager. In v0.66.0 pkg/vmcp/server/server.go, Server.Handler() passes WithSessionIdManager(&pruneOnTerminateSessionIDManager{SessionIdManager: s.vmcpSessionMgr, registry: &s.healthResync}), and its Terminate calls m.registry.remove(sessionID) on a successful terminate. The streamable DELETE drives sessionIDMgr.Terminate, so the entry is removed eagerly — a text search for healthResync.remove misses it because the wrapper calls m.registry.remove (the field is named healthResync). Worth a quick double-check against your build, but I don't think worker-closure pile-up is the cause.

    On (a): the ~72 MB of initOneBackend/ConvertToolInputSchema is the real signal — the MultiSession itself survives DELETE. That's consistent with a Phase-1/Phase-2 termination race: if DELETE lands while the record is still a placeholder, Terminate takes the Phase-1 branch (marks terminated=true, never sm.sessions.Removes), and if CreateSession's second placeholder check has already passed, its storage.Update(sess.GetMetadata()) then overwrites the just-written terminated flag and caches the MultiSession. The notifications/initialized round-trip in the control run would give CreateSession time to finish, which fits the clean control. The syncSessionTools/toGoSDKTool retention is then downstream: the pinned MultiSession's connectors hold the list_changed sink, which captures the ClientSession, which pins the per-session go-sdk server.

    That hypothesis hinges on OnRegisterSession finishing after the initialize response — the test at serve_session_test.go:435 notes it "may complete asynchronously", which is consistent, but I'd rather confirm than assume.

    The goroutine profile after TTL would settle it — unlike the heap, goroutine stacks show live references, so it should name exactly what's holding the MultiSession. A goroutine pprof snapshot (?debug=2) is enough.

    Separately I opened stacklok/toolhive-core#551, a defensive fix that makes forgetSession release the per-session go-sdk server + overlays even when the clientSession is pinned — that's mitigation, not the root cause. Once the goroutine profile confirms the holder, the root-cause fix should be small and in toolhive.

  12. nilsberberich commented on Nov 22, 2026

    @nilsberberich
    ContributorAuthor

    You're right about (b), thanks for the pointer. pruneOnTerminateSessionIDManager removes the health-resync entry on DELETE, and I missed it because I searched for healthResync.remove. Please disregard my observation 2.

    I reran the leak scenario on our test gateway with the same build (v0.66.0 + pprof on loopback), 2 replicas, Redis session storage: initialize → DELETE without notifications/initialized, 204 sessions in 15 min, then waited out the 30 min TTL (Redis db empty afterwards) and took goroutine profiles (debug=1 and debug=2) plus heap profiles. No pod restarts during the run.

    Goroutines per pod (debug=1, both pods identical):

                              idle   after load   after TTL
    total                       76         1766        1415
    streamableClientConn.Read    0         1339        1339
    streamableServerConn.Read    0          103           0
    forgetWhenClosed             0          103           0
    newClientSession.func1       0          103           0
    health.monitorBackend       18           18          18
    

    1339 = 103 × 13: each pod held 102 churn sessions plus one long-lived session from the test client, each with 13 backend connections. After the TTL all 1339 client-side connections are still there (each in [select, 36-51 minutes]):

    goroutine 27008 [select, 51 minutes]:
    github.com/modelcontextprotocol/go-sdk/mcp.(*streamableClientConn).Read(...)
    	github.com/modelcontextprotocol/[email protected]/mcp/streamable.go:2253
    github.com/modelcontextprotocol/go-sdk/internal/jsonrpc2.(*Connection).readIncoming(...)
    	github.com/modelcontextprotocol/[email protected]/internal/jsonrpc2/conn.go:517
    created by github.com/modelcontextprotocol/go-sdk/internal/jsonrpc2.(*Connection).start.func1 in goroutine 27016
    	github.com/modelcontextprotocol/[email protected]/internal/jsonrpc2/conn.go:259
    

    So the MultiSessions survive with their backend connectors open, as you suspected. The server-side go-sdk sessions, on the other hand, are gone after the TTL (the idle timeout from WithSessionIdleTimeout(SessionTTL) reaped them), but the heap didn't move: 390.1 MB in use after load vs. 389.6 MB after the TTL on one pod (409.4 → 408.9 MB on the other), same allocation sites as before (cumulative: syncSessionTools 199 MB / 51%, of which toGoSDKTool 193 MB / 49%; makeBaseSession/initOneBackend 108 MB / 28%, which includes the 72 MB ConvertToolInputSchema stack from last time). That fits your chain: something other than the ServerSession keeps the per-session state alive, and the open connectors with the list_changed sink are the obvious candidate. The goroutine profile can't show the holder directly: the goroutine that created the connections has exited, and the cache that holds the MultiSession has no goroutine of its own.

    But the race isn't needed to explain this run. I matched session IDs in the vMCP logs (session capabilities injected from core vs. Manager.Terminate: session terminated):

    • All 204 churn sessions leaked, not a fraction.
    • No CreateSession errors (no "terminated before/during/between …").
    • In 204 of 204 cases the Terminate was logged on the other replica than the one that registered the session; 0 on the same replica.

    Our load balancer distributes requests round-robin across the two replicas, without session affinity. The test loop sends 3 requests per iteration (a call on an existing session, initialize, DELETE), so initialize and DELETE always land on different replicas. The control run added notifications/initialized, making it 4 requests per iteration, so initialize and DELETE landed on the same replica. That would explain the clean control run without any timing argument.

    Reading v0.66.0 with that in mind: on the replica that receives the DELETE, the go-sdk handler doesn't know the session (404), and Manager.Terminate deletes the Redis key and calls sm.sessions.Remove on its own node-local cache only. The replica that holds the MultiSession is never told. Its ValidatingCache has no time-based sweep, so the entry is only reclaimed via checkSession on the next access (which never comes, because the client is done with the session), LRU capacity (default 1000), or RemoveMatching. The comments in Terminate say as much: "Other replicas still self-heal through checkSession on their next cache access", and in the Phase-2 branch, that the Get that would trigger checkSession "may never come" (#6762), which is what happens here on the other replica.

    So my reading is: a DELETE served by a replica other than the one caching the MultiSession cleans up Redis but leaks the MultiSession (and, through the sink, the ClientSession and the per-session go-sdk server) on the original replica. Since both Terminate branches log the same message and the timestamps have one-second resolution, I can't rule out that your Phase-1/Phase-2 race also happens, but it isn't needed to explain what we see. A run with a single replica (and still no notifications/initialized) should come out clean if this is right; we can do that if it helps.

    If I read toolhive-core#551 correctly, release() on forget (here: when the idle timeout reaps the go-sdk session) would drop the go-sdk server and tool overlays even while the clientSession itself stays pinned through the sink. It wouldn't touch the MultiSession and its backend connections, though (108 MB cumulative here, plus 13 open connections per leaked session). Does that match your intent?

  13. HankGrimm commented on Nov 22, 2026

    @HankGrimm
    Contributor

    That's a really clean explanation — round-robin with 3 requests per iteration in the leak run (so initialize and DELETE land on different replicas) and 4 in the control run (same replica) accounts for the entire notifications/initialized split with no timing argument. Please disregard my Phase-1/Phase-2 race hypothesis; it isn't needed to explain your data.

    And yes, you're reading #551 exactly right. release() fires when the go-sdk session is reaped (here by the idle timeout), and it drops the per-session go-sdk server + the tool/resource/prompt overlays, but it leaves the clientSession itself pinned through the sink, and it does not touch the MultiSession or its backend connections. So it's only a partial mitigation — it should free the ~154 MB of toGoSDKTool/jsonConvert tool schemas and the ~18 MB SetSessionTools overlay, but not the ~108 MB makeBaseSession/initOneBackend state or the 13 open connections per leaked session. The root cause still needs a toolhive fix.

    The gap is exactly what you described: ValidatingCache has no time-based sweep — checkSession runs only on a cache hit, and the LRU cap (1000) is never reached here, so a MultiSession whose Redis key was deleted by Terminate on another replica sits in the node-local cache with its connections open indefinitely. Terminate's own comment even says "Other replicas still self-heal through checkSession on their next cache access" — which never comes for a client that's done with the session.

    The smallest fix is to make that self-heal proactive: add a background sweep to the session Manager that periodically runs the existing checkSession over cached sessions and evicts the ErrExpired ones, which triggers the existing onEvict → MultiSession.Close() and closes the connections. That bounds the leak to one sweep interval and reuses the exact liveness/eviction path already in place. (A Redis pub/sub termination broadcast would be the eager alternative, but it's more machinery than this needs.)

    Two questions before I write it:

    1. Cadence — tie the sweep to SessionTTL, or a fixed shorter interval (e.g. every minute) so leaked sessions are reclaimed quickly? Cost is one Redis Load per cached session per sweep, bounded by cache capacity.
    2. Lifecycle — start/stop the sweep goroutine alongside the Manager so it shuts down cleanly with the server?

    Happy to put that up as a toolhive PR, and I'll mark #551 as partial mitigation in its description.

  14. nilsberberich commented on Nov 23, 2026

    @nilsberberich
    ContributorAuthor

    Thanks, that matches what we see, and the sweep sounds like the right fix to me.

    1. Cadence: I'd go for a fixed, shorter interval rather than SessionTTL, ideally configurable with a sensible default such as 1 minute. With our settings (30 min SessionTTL, 2 replicas), a TTL-based sweep could leave an orphaned MultiSession in place for up to one full sweep interval (30 min) after the DELETE, with its 13 backend connections open. In our test run each pod was already at ~870–886 MiB of its 1 GiB limit after 15 minutes of churn (~103 cached sessions per pod), so at that rate a 30 min window would push a pod past its limit. The Redis cost looks negligible by comparison: with a 1 minute interval that's roughly 100 Loads per pod per minute at our peak, and with the sweep in place the cache should stay much smaller than that.

    2. Lifecycle: Yes, please start and stop it with the Manager, and have it exit cleanly on shutdown.

    Once there's a PR build, we can try it on our test gateway with the same repro (2 replicas, initialize → DELETE without notifications/initialized, then wait out the TTL), and compare goroutine and heap profiles if that helps. If it's useful before that, we could also do the single-replica cross-check.

  15. peppescg commented on Nov 24, 2026

    @peppescg
    Contributor

    Thanks @nilsberberich and @HankGrimm for the thorough troubleshooting here. We ran into the same memory growth. We are reviewing #7259 now and will leave our feedback on the PR.

  16. added a commit that references this issue on Nov 24, 2026
    c188075
  17. nilsberberich commented on Nov 25, 2026

    @nilsberberich
    ContributorAuthor

    As promised, we re-ran the repro on v0.69.0 (with #7259 and #7265), using the regular release image and no pprof build. The setup was the same as before: 2 replicas, initialize → DELETE without notifications/initialized, 224 sessions in 15 minutes. All 224 DELETEs landed on a different replica than the initialize.

    • Backend connections: fixed. We counted established connections from the vMCP pods on the backend side (on v0.66.0 we had counted client goroutines). During the load they stayed flat instead of growing with the session count, and they were back to baseline about 1.5 minutes after the last session. On v0.66.0, 13 connections per session were still open well past the TTL.
    • Memory: much better, but only partly released right away. Under churn it still grows at about the same rate as before, peaking at ~790–820 MiB per pod (v0.66.0: ~870–886 MiB). Shortly after the load it dropped by ~250 MiB per pod, around the time the backend connections closed. It then stayed flat at ~555 MiB and only fell further about 30 minutes after the first sessions, which matches our SessionTTL. It ended at ~70 MiB per pod (v0.66.0: ~627 MiB, no decline after the TTL). No OOM.

    Our guess is that the originating replica keeps the server-side session state, i.e. the per-session tool registration we saw in the earlier heap profile, until the idle timeout, and that the DELETE on the other replica doesn't release it. We didn't profile this run, so that's not confirmed. If it helps, we can pull a heap profile at peak and after the sweep.

    We've rolled v0.69.0 out to production. Thanks @HankGrimm and everyone for the quick fix!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions