Repository navigation
Description
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,
VirtualMCPServerwith 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 resolutionprefix, 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:
- one
tools/callon a long-lived session (unrelated to the leak, kept for comparison) - a new session:
initialize(+notifications/initialized), thenDELETE /mcpwith theMcp-Session-Id - 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
Manager.Terminatein v0.55.2 removes the entry from the node-localValidatingCache(fix for vMCP: Terminate() retains backend connections in the node-local cache until eviction #6762) andonEvictcallsMultiSession.Close(). The retained memory therefore seems to live either in somethingClose()does not release, or outside the session cache (per-session state in other components).- Related, closed: vMCP: Terminate() retains backend connections in the node-local cache until eviction #6762 (Terminate retained backend connections until eviction), Proxyrunner memory grows monotonically under streamable-http session churn #4062 (proxyrunner memory growth under streamable-http session churn), vmcp: validating cache discards loaded value without cleanup when losing concurrent Set race #4837 (validating cache discarded a loaded value without cleanup).
- We can provide a heap profile if there is a supported way to enable pprof in vMCP, or test a build with a fix.
- Real clients (IDE agents that reconnect often) can create sessions at a similar rate, so a 512Mi pod would hold only about 65–95 sessions over its lifetime.
Activity
HankGrimm commentedon Nov 19, 2026
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
pprofheap profile (no external dependencies), and will report back withwhat's retained before proposing a fix.
jhrozek commentedon Nov 19, 2026
Thank you @HankGrimm I assigned the issue to you
HankGrimm commentedon Nov 20, 2026
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/pprofon a loopback-only listener, e.g. inStartbefore the main listener binds (or incmd/main):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-list/-alloc_space/-tracesfor itEven just the top ~10
-toplines plus inuse-object counts would be enough to point atServerToolvs the go-sdk per-sessionServervs something else, and I can go from there.nilsberberich commentedon Nov 20, 2026
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/pproflistener, deployed only to our test gateway viapodTemplateSpec. 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 thego tool pprof -topoutput (plus-list/-tracesif one type dominates). No need for a branch on your side.nilsberberich commentedon Nov 20, 2026
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) withnet/http/pprofon 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 sendsinitializeand thenDELETEon the session, withoutnotifications/initializedin 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 (
DBSIZE0). 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):The cumulative view (
-top -cum) and-peekshow where it comes from:sessionDispatchMiddleware.func1.1→(*MCPServer).registerAndSyncsyncSessionTools→toGoSDKTool→jsonConvert(syncSessionTools164 MB, of whichjsonConvert157 MB): per-session copies of all tool schemas asmap[string]any(*Hooks).registerSession(48 MB)(*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-sdkServerSession/client. I suspected the missingnotifications/initializedas 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/initializedbeforeDELETE(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 withoutnotifications/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
.proffiles (two pods, before/after load/after TTL, plus the control run) if that helps, and can test a fix build on the same setup.HankGrimm commentedon Nov 21, 2026
Thanks for the profile and the control run — the
notifications/initializedcorrelation is the key signal, and the-cumbreakdown 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
Serverand never removed on DELETE. Oninitialize,registerAndSync→OnRegisterSession→injectCoreSessionCapabilities→SetSessionTools, andsyncSessionToolscallssrv.AddTool(...)on the single*gosdk.Serverthe shim builds for the whole server (buildServer).RemoveToolsis only called insidesyncSessionToolswhen a live session's overlay shrinks. On DELETE,forgetSessionLockedremoves theclientSessionfroms.sessionsand closes its notify channel, but never removes that session's tools from the shared server. So the converted tool schemas (yoursyncSessionTools → toGoSDKTool → jsonConvert~157 MB) and their handlers stay reachable onsrv.2. A
clientSessionretention chain via the list_changed sink.buildListChangedSinkbuilds per-(session, kind)listChangedResyncWorkers whoserunclosures capture theClientSession(plus identity + forwarded headers). TheKindToolsworker is also registered inhealthResync(when health monitoring is on and the optimizer is off); the sink itself is stored in the session's backend connectors inside theMultiSession. So even afterforgetSessiondrops the registry entry, theclientSession— and itscs.toolsoverlay — stays reachable through those closures until theMultiSessionis released and thehealthResyncentry 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 andnotifications/initializedonly re-entersregisterAndSyncbehind 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/-tracesoutput for thesyncSessionTools/toGoSDKToolinuse objects, to see the exact referring path, and (b) confirmation of whether anything drives a per-sessionRemoveToolson 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(...)overcs.sdkToolNames) before dropping the registry entry. That change lives instacklok/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.proffiles, I can also read the exact referring path off them and confirm before writing anything.HankGrimm commentedon Nov 21, 2026
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.buildwiresgetServerFunc, and the go-sdk handler calls it once per new client session, sobuildServerproduces a fresh*gosdk.Serverper session (transports.go: "A fresh go-sdk server per client session lets each session carry its own tool/resource overlay"). Each session'sregisterAndSyncthen 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 wholeclientSession— and with it its per-session*gosdk.Server(cs.boundServer), its converted tool schemas, andcs.tools— survives DELETE. Two things hold theclientSessionalive afterforgetSessiondrops it froms.sessions:buildListChangedSinkbuilds per-(session, kind)listChangedResyncWorkers whoserunclosures capture theClientSession; the sink is stored in the session'sMultiSessionbackend connectors, and theKindToolsworker is also registered inhealthResync.forgetSessionLockeddrops the registry entry and closes the notify channel but does not clearcs.boundServer/cs.goSession/cs.owner/cs.tools, so whatever still reaches theclientSessionkeeps the per-session server reachable.Corrected fix direction: release the
clientSessionon DELETE — break the sink/health-resync capture of it (or prune it eagerly), and/or haveforgetSessionLockednil outcs.boundServer/cs.goSession/cs.tools. I still can't reconcile from code alone why the with-notifications/initializedcontrol run is clean, so I'd rather confirm the exact referring path (the raw.proffiles, or a localinitialize+DELETEchurn profile) before writing anything. Happy to send a branch either way.nilsberberich commentedon Nov 21, 2026
Thanks for digging in. Here is the
-list/-tracesoutput 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)-traces, condensed (json/reflect/runtime frames dropped, first 6 remaining frames per stack, summed per stack, stacks ≥ 4 MB):Leak run, after TTL:
Control run (with
notifications/initialized), after TTL, ~22 MB in use:Two observations that may help with the referring path:
makeBaseSession/initOneBackendbuilt the backend connectors (the per-backend tool lists), not on theclientSessionpath. That suggests theMultiSession's connectors are retained as well, not onlycs.boundServer/cs.tools.health.(*Monitor).performHealthCheckframes) and the optimizer is off, so every session goes throughs.healthResync.add(sessionID, toolsResyncWorker)inhandleSessionRegistrationImpl. In v0.66.0 I only findhealthResync.removeon the registration error path, interminateOnBindingFailure, and in the lazy liveness check ofrunListChangedResync. A clientDELETEdoesn'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 capturedClientSession) 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 theMultiSession.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(beforeCallToolhook) rather than viahandleSessionRegistration, 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
RemoveToolson session close; your corrected reading (fresh*gosdk.Serverper session) matches what I see intransports.go.If it helps, we could run another round on our test gateway with a goroutine profile after the TTL, or test a branch.
HankGrimm commentedon Nov 22, 2026
Thanks — the
-tracesnails the two allocation sites. Two things:On (b): I think the health-resync entry is pruned on DELETE, via
pruneOnTerminateSessionIDManager. In v0.66.0pkg/vmcp/server/server.go,Server.Handler()passesWithSessionIdManager(&pruneOnTerminateSessionIDManager{SessionIdManager: s.vmcpSessionMgr, registry: &s.healthResync}), and itsTerminatecallsm.registry.remove(sessionID)on a successful terminate. The streamable DELETE drivessessionIDMgr.Terminate, so the entry is removed eagerly — a text search forhealthResync.removemisses it because the wrapper callsm.registry.remove(the field is namedhealthResync). 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/ConvertToolInputSchemais the real signal — theMultiSessionitself survives DELETE. That's consistent with a Phase-1/Phase-2 termination race: ifDELETElands while the record is still a placeholder,Terminatetakes the Phase-1 branch (marksterminated=true, neversm.sessions.Removes), and ifCreateSession's second placeholder check has already passed, itsstorage.Update(sess.GetMetadata())then overwrites the just-writtenterminatedflag and caches theMultiSession. Thenotifications/initializedround-trip in the control run would giveCreateSessiontime to finish, which fits the clean control. ThesyncSessionTools/toGoSDKToolretention is then downstream: the pinnedMultiSession's connectors hold thelist_changedsink, which captures theClientSession, which pins the per-session go-sdk server.That hypothesis hinges on
OnRegisterSessionfinishing after theinitializeresponse — the test atserve_session_test.go:435notes 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. Agoroutinepprof snapshot (?debug=2) is enough.Separately I opened
stacklok/toolhive-core#551, a defensive fix that makesforgetSessionrelease the per-session go-sdk server + overlays even when theclientSessionis pinned — that's mitigation, not the root cause. Once the goroutine profile confirms the holder, the root-cause fix should be small and intoolhive.nilsberberich commentedon Nov 22, 2026
You're right about (b), thanks for the pointer.
pruneOnTerminateSessionIDManagerremoves the health-resync entry on DELETE, and I missed it because I searched forhealthResync.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→DELETEwithoutnotifications/initialized, 204 sessions in 15 min, then waited out the 30 min TTL (Redis db empty afterwards) and tookgoroutineprofiles (debug=1anddebug=2) plus heap profiles. No pod restarts during the run.Goroutines per pod (
debug=1, both pods identical):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]):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 fromWithSessionIdleTimeout(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:syncSessionTools199 MB / 51%, of whichtoGoSDKTool193 MB / 49%;makeBaseSession/initOneBackend108 MB / 28%, which includes the 72 MBConvertToolInputSchemastack from last time). That fits your chain: something other than theServerSessionkeeps the per-session state alive, and the open connectors with thelist_changedsink 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 theMultiSessionhas 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 corevs.Manager.Terminate: session terminated):CreateSessionerrors (no "terminated before/during/between …").Terminatewas 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), soinitializeandDELETEalways land on different replicas. The control run addednotifications/initialized, making it 4 requests per iteration, soinitializeandDELETElanded 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.Terminatedeletes the Redis key and callssm.sessions.Removeon its own node-local cache only. The replica that holds theMultiSessionis never told. ItsValidatingCachehas no time-based sweep, so the entry is only reclaimed viacheckSessionon the next access (which never comes, because the client is done with the session), LRU capacity (default 1000), orRemoveMatching. The comments inTerminatesay as much: "Other replicas still self-heal through checkSession on their next cache access", and in the Phase-2 branch, that theGetthat would triggercheckSession"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
MultiSessioncleans up Redis but leaks theMultiSession(and, through the sink, theClientSessionand the per-session go-sdk server) on the original replica. Since bothTerminatebranches 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 nonotifications/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 theclientSessionitself stays pinned through the sink. It wouldn't touch theMultiSessionand its backend connections, though (108 MB cumulative here, plus 13 open connections per leaked session). Does that match your intent?HankGrimm commentedon Nov 22, 2026
That's a really clean explanation — round-robin with 3 requests per iteration in the leak run (so
initializeandDELETEland on different replicas) and 4 in the control run (same replica) accounts for the entirenotifications/initializedsplit 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 theclientSessionitself pinned through the sink, and it does not touch theMultiSessionor its backend connections. So it's only a partial mitigation — it should free the ~154 MB oftoGoSDKTool/jsonConverttool schemas and the ~18 MBSetSessionToolsoverlay, but not the ~108 MBmakeBaseSession/initOneBackendstate or the 13 open connections per leaked session. The root cause still needs atoolhivefix.The gap is exactly what you described:
ValidatingCachehas no time-based sweep —checkSessionruns only on a cache hit, and the LRU cap (1000) is never reached here, so aMultiSessionwhose Redis key was deleted byTerminateon 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
Managerthat periodically runs the existingcheckSessionover cached sessions and evicts theErrExpiredones, which triggers the existingonEvict→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:
SessionTTL, or a fixed shorter interval (e.g. every minute) so leaked sessions are reclaimed quickly? Cost is one RedisLoadper cached session per sweep, bounded by cache capacity.Managerso it shuts down cleanly with the server?Happy to put that up as a
toolhivePR, and I'll mark #551 as partial mitigation in its description.nilsberberich commentedon Nov 23, 2026
Thanks, that matches what we see, and the sweep sounds like the right fix to me.
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 minSessionTTL, 2 replicas), a TTL-based sweep could leave an orphanedMultiSessionin place for up to one full sweep interval (30 min) after theDELETE, 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 100Loads per pod per minute at our peak, and with the sweep in place the cache should stay much smaller than that.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→DELETEwithoutnotifications/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.peppescg commentedon Nov 24, 2026
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.
Sweep terminated sessions from the node-local cache (stacklok#7259)
nilsberberich commentedon Nov 25, 2026
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→DELETEwithoutnotifications/initialized, 224 sessions in 15 minutes. All 224DELETEs landed on a different replica than theinitialize.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
DELETEon 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!