Repository navigation
Description
Bug description
All VirtualMCPServer (vmcp) instances we run grow 2-3x in RSS memory over
roughly 24 hours, independent of client connection activity, eventually
threatening node memory headroom (this drove a node-wide OOM incident for
us). A prior working theory - that this was client-side reconnect churn -
is falsified by continued growth measured well after fixing that churn
cause on the client side.
Steps to reproduce
- Deploy 2+ VirtualMCPServer instances with different backend counts (we
ran 4, with 12/13/14/19 backends respectively). - Measure RSS via
kubectl top podat two points ~23h apart, with the
deployments not restarted and no client-driven reconnect storms in
between. - Compare growth against the backend MCPServer/MCPRemoteProxy Deployments
in the same namespace (control group) over the same window.
Expected behavior
Memory should stabilize/plateau. The control-group backend Deployments
show exactly this behavior (flat over the same 23h window).
Actual behavior
| instance | backends | RSS T+0h | RSS T+23h | growth | rate |
|---|---|---|---|---|---|
| A | 19 | 476Mi | 1476Mi | 3.1x | ~43 Mi/h |
| B | 14 | 349Mi | 683Mi | 2.0x | ~14.5 Mi/h |
| C | 13 | 184Mi | 446Mi | 2.4x | ~11.4 Mi/h |
| D | 12 | 172Mi | 343Mi | 2.0x | ~7.4 Mi/h |
Growth rate scales roughly with backend count, consistent with a
per-backend resource retained per some recurring operation (health-check
tick, session-scoped init, etc.) rather than one fixed leak. A clean pod
restart drops each instance back to a ~35-100Mi baseline immediately.
Control group (same namespace, same 23h window, unrestarted): three
backend proxy Deployments stayed flat (264Mi / 249Mi / 175Mi at both
measurement points).
Environment
- ToolHive operator + vmcp: v0.34.0
- Single-node Kubernetes (Talos), 4 independent VirtualMCPServer instances
Additional context
- Related but distinct: Proxyrunner memory grows monotonically under streamable-http session churn #4062 (closed) fixed a monotonic memory leak in
thv-proxyrunnerunder streamable-http session churn - that's the
individual-backend-proxy component. Our observation is in the
vmcp/VirtualMCPServer aggregator process itself; our control-group
backend proxy pods stayed flat over the same window, so this does not
look like the same code path re-surfacing. - We have not isolated which internal resource is growing (no profiling
access in this deployment). Happy to gather a pprof heap profile across
a multi-hour window if vmcp exposes one, or to test against specific
config knobs if pointed at likely candidates.
Activity
ChrisJBurns commentedon Jul 30, 2026
Thanks for the detailed report, @RaviTharuma. The flat control group is a useful control, and growth scaling with backend count does point at something retained per backend on a recurring operation rather than a single fixed leak.
One correction on your profiling offer: vmcp does not expose a pprof endpoint today, so there is no heap profile for you to collect. Three things would help more:
healthCheckIntervalset to on these instances, or are they on compiled-in defaults? If you can raise it substantially on one instance, does the Mi/h rate fall roughly in proportion?Once we have that we can take a proper look. Leaving this open in the meantime.
RaviTharuma commentedon Aug 10, 2026
Follow-up (still open on v0.42.1)
Updating the original report with current environment. No credentials or private hostnames included.
Environment (now)
vmcpimage: v0.42.1 (was v0.34.0 when filed)VirtualMCPServerinstances, backend counts 12 / 13 / 17 / 17Current RSS sample (
kubectl top pod, ~2.5h after last nightly restart)We have not re-run a full 23h pair of samples on v0.42.1 yet; the original table still stands as the multi-hour growth evidence. If growth continues on 0.42.1 we will post a second 23h table.
Answers to your questions (2026-07-30)
spec.config.telemetry.enablePrometheusMetricsPath: trueon these VirtualMCPServers so Go runtime metrics are available for a multi-hour series. Will share series once scraped (no private labels).healthCheckInterval: not set on our CRs (compiled-in defaults). Happy to raise it on one instance once we know the field path / default value.Still happy to help isolate this. Thanks for the earlier guidance.
RaviTharuma commentedon Aug 10, 2026
Follow-up: why telemetry was not scrapable (v0.42.1)
We enabled what the CRD documents as:
Observed:
*-vmcp-config) had notelemetry:blockGET /metricswithAccept: text/plain/*/*/ openmetrics → HTTP 406 JSON-RPC:Not Acceptable: Client must accept text/event-streamGET /health→ 200{"status":"ok"}(health is registered; metrics is not)Cause: operator converter only honors
spec.telemetryConfigRef→MCPTelemetryConfig. Inlinespec.config.telemetrywas a silent no-op after #4819,while docs still suggested the inline path. Full write-up: #6276. Fix PR:
restores deprecated inline fallback + documents preferred
MCPTelemetryConfig.Workaround (works on v0.42.1 without a new operator):
Once scrape works we will post a multi-hour
go_*/ process memory series(no private labels). Still happy to raise
healthCheckIntervalon one idleinstance if you can confirm the field path defaults (compiled-in default appears
to be 30s under
config.operational.failureHandling.healthCheckInterval).No credentials or private hostnames in this comment.
RaviTharuma commentedon Aug 15, 2026
Follow-up on v0.43.0 (29h sample)
Environment now: operator +
vmcpv0.43.0. Nightly restart CronJob has been removed.kubectl top pod~29h after the last operator/proxy bounce (2026-08-14 ~16:37 UTC):This is not a 23h growth pair, so it does not clear or confirm the original leak. It does show that after ~29h on 0.43.0 we are not in the 1+ Gi crisis from the original report. Still happy to post a real
go_*series once scrape is stable viaMCPTelemetryConfig(#6276).Related operational gaps that make mitigation ugly, filed separately:
kubectl rollout restartis reverted; onlykubectl delete pod -l toolhive-name=…actually bounces a vMCPstatusReportingIntervalcauses a Deployment Update event every interval (noise, not a leak)No credentials or private hostnames.
fix(ai): graceful vmcp shutdown and stagger the two embedder recycles
fix(llmkube): kv_load_failure_policy was inert; document 09-03 findings
fix(reliability): eviction priority, disruption budgets, backup alert…
alex-feel commentedon Sep 24, 2026
On the 2026-07-30 question: on v0.47.1 our instances stay flat without client sessions and grow as clients open them. Two VirtualMCPServers, two backends each, default 30 s health checks (each lists a backend's tools, resources and prompts); cAdvisor working set, no Go metrics scraped.
Sessions get no resources injected (
resource_count0 on every injection log line; authz permits tool calls only), yet the cost tracks the backends' resource count. In v0.47.1makeBaseSessionkeeps each backend's raw tools, resources and prompts per session, and the session cache evicts an entry only when a later lookup finds it expired or the 1000-entry LRU fills. Nothing looked those entries up here (no eviction, health change or backend removal logged), and v0.51.1 adds no idle eviction. #6667 prunes the resync registry at the health-change fan-out, which already evicts the expired sessions it looks up, so I don't expect it to change these curves. If it closes this issue I can open one for the session cache; hourly series and log counts are available.RaviTharuma commentedon Sep 25, 2026
@alex-feel thanks — this is exactly the signal we were missing.
Your v0.47.1 picture (flat idle weekends, growth tied to client sessions / large resource backends, ~0.8–1.3 GiB/day on the ~6,200-resource case with default 30s health listing tools/resources/prompts) matches a session- or catalog-retained path much better than a pure idle leak.
I will dig next on: (1) whether health-check tool/resource/prompt listing retains catalogs across ticks, (2) session teardown vs open-client growth, and (3) whether Go/
pprofheap deltas line up with the cAdvisor working-set curve. Will report back with a redacted repro recipe once I have a tight loop.RaviTharuma commentedon Oct 2, 2026
@ChrisJBurns @alex-feel — alex-feel's v0.47.1 data (flat idle weekends; growth tied to client sessions / large resource catalogs; clients never DELETE) looks like a strong session-cache / catalog-retention signal rather than a pure idle leak.
If that framing is enough to drop
needs_more_info, I am happy to take a focused follow-up PR for idle session-cache eviction (or whatever direction you prefer). Otherwise, please say what remaining measurement you still need and I will prioritize that.alex-feel commentedon Oct 6, 2026
@RaviTharuma one layer of this already has a PR: stacklok/toolhive-core#306 (for stacklok/toolhive-core#305) adds an opt-in
WithSessionIdleTimeoutto the mcpcompat shim, which closes and drops sessions whose clients never send DELETE. It is open and waiting for review. The vmcp would still need to pass its session TTL to it. That covers only the shim's own session map; the vmcp's per-session state on top of it is a separate matter, so a session-cache eviction PR on the vmcp side would not duplicate that PR. On main, the vmcp's node-local session cache (ValidatingCacheinpkg/cache) drops an entry only when that session is read again and found expired, when LRU capacity pushes it out, or when its backend is removed; nothing sweeps idle entries. The makeBaseSession and session-cache reading I posted above comes from reading the source. I have not taken a heap profile, so I have not confirmed where that memory sits.RaviTharuma commentedon Oct 7, 2026
@alex-feel thanks, that split is really helpful. So toolhive-core#306 covers the shim's own session map (once vmcp passes its session TTL into
WithSessionIdleTimeout), and the vmcp side still has nothing that sweeps idleValidatingCacheentries inpkg/cache, since they only go on re-read, LRU pressure, or backend removal.If maintainers are fine with that direction, I'd scope a vmcp follow-up to (1) a periodic idle sweep of the node-local session cache and (2) passing the session TTL through to the shim after #306 lands, so it complements that PR instead of duplicating it. @ChrisJBurns does that work for you, or would you rather see a heap profile first?
hellouz818 commentedon Oct 12, 2026
@RaviTharuma, following @alex-feel's suggestion on #6762, I'd like to confirm the scope split with your proposed follow-up.
My proposed fix is limited to explicitly terminated sessions: adding
ValidatingCache.Remove(key)and calling it fromTerminate()after deleting the storage record, so the local backend connections are closed immediately.The periodic sweep of cache entries whose storage records have expired (including sessions abandoned without DELETE), as well as passing the session TTL to the mcpcompat shim, would remain in your proposed follow-up here.
Since both changes touch
ValidatingCache, I'm happy to coordinate on the API surface so they don't conflict. Does that scope split match your plan?JAORMX commentedon Oct 12, 2026
@RaviTharuma @alex-feel @hellouz818, I dug through the current code and the earlier cache changes to double-check this. The scope split makes sense: @hellouz818 is assigned the explicit-termination fix in #6762, while abandoned-session cleanup stays separate here. Thanks for connecting the two reports and for the workload measurements.
There is some history worth bringing back into the discussion. #4727 called for removing imperative cache deletion and adding a background sweep. The reapplication in #4731 removed the eager cleanup, but the replacement sweep did not land, despite the issue being closed as implemented. So we left a gap between removing one cleanup path and adding the other. That explains why this is coming up again.
The biggest implementation trap is that our current liveness checks renew the session TTL.
checkSessioncallsDataStorage.Load: Redis usesGETEX, and local storage refreshes its last-access timestamp. A periodic sweep through that path could keep abandoned sessions alive indefinitely. Going through cacheGetis also unsuitable, since a miss can restore a session and open backend connections.We already have a non-renewing
LoadMetadataoperation on the ordinary transportStorageinterface, so there is a precedent to follow. vMCP uses the separateDataStorageinterface, which does not expose an equivalent operation. We should also define what a non-renewing read means for local entries that are past their TTL but have not yet been removed by the storage cleanup worker.There is a cache-locking detail to account for too:
RemoveMatchingcurrently evaluates its predicate under the cache mutex. We should not put Redis calls there. An off-lock check needs to remove only the entry it inspected, without accidentally deleting a replacement inserted while the check was running. That requires coordinating with the cache-miss insertion path as well.On the shim side, stacklok/toolhive-core#306 has landed and is already included in our pinned core v0.0.51. vMCP does not enable its idle timeout yet. Note that this timeout measures POST inactivity on one replica: an in-flight POST pauses it, but an open GET stream does not keep it alive. Shared metadata can therefore remain valid after the local shim session is closed. Our current lazy reinjection covers tools, so I would want coverage for resources/prompts and notification bindings when a session is rehydrated before treating TTL wiring as a complete fix.
So, I would start by making the intended guarantee explicit: reclaim local cached objects once their authoritative metadata has expired or been deleted, without refreshing that metadata or treating a temporary storage error as expiry. Evicting a locally idle copy while another replica still uses the session is a different policy, and we should not mix the two accidentally.
None of this needs to hold up the focused DELETE fix. For this follow-up, cache/connection counts and before-and-after heap profiles would help us distinguish backend-session retention from shim and resync-worker retention; RSS alone cannot tell us which objects were reclaimed.
@RaviTharuma, are you still interested in taking this on, and does metadata-expiry-based cleanup match the scope you had in mind?
RaviTharuma commentedon Oct 15, 2026
@hellouz818 @JAORMX yes — that scope split matches my plan.
ValidatingCache.Remove(key)fromTerminate()after the storage delete, so local backend connections close immediately.Happy to align on the
ValidatingCacheAPI surface so the Remove path and the sweep do not fight. The #4727 / #4731 history (eager cleanup removed, replacement sweep never landed) is exactly the gap I want the follow-up to close.JAORMX commentedon Oct 15, 2026
Thanks @RaviTharuma! I’ve assigned this to you. The DELETE fix has now landed in #6807, so please build on current main for the metadata-expiry sweep.
Let’s keep shim timeout wiring in a separate PR because of the replica-local expiry and rehydration concerns from my earlier comment. Otherwise, we’re aligned on the scope.
alex-feel commentedon Oct 23, 2026
@RaviTharuma a point for the sweep design, read at main 7970d58: a sweep that reclaims cache entries through the existing eviction path leaves the session's health-resync worker registered.
healthResyncRegistry(pkg/vmcp/server/serve_health_resync.go:51) loses an entry only on registration failure (server.go:1350), binding failure (serve_handlers.go:570), DELETE viapruneOnTerminateSessionIDManager(serve_health_resync.go:63-74), or a triggered worker finding the session gone (serve_list_changed.go:219-220); the cache's eviction closure (sessionmanager/session_manager.go:161-173) only closes the session, and nothing under pkg/cache or sessionmanager references the registry. That lazy prune runs only inside the health fan-out, which fires only on an advertisability flip or a backend-set change (health/monitor.go:552, :463), so with healthy, unchanging backends a swept session's worker closure (shimClientSession, registration-time identity and forwarded headers) stays until restart, as the comments at serve_health_resync.go:44-50 and server.go:1408-1414 note. Today the shim's own session map holds thatClientSessionanyway until DELETE; once the idle timeout is wired, the registry entry would be the last reference to it. CallinghealthResync.removefrom the sweep, or from the eviction closure, closes the gap. Whether this holds any of the measured growth I have not confirmed; no heap profile.chore(ai): restart vmcp every 3 days instead of 4 (#6301)
alex-feel commentedon Nov 16, 2026
A data point from v0.63.0: the 848-resource aggregate from my earlier numbers grew to its 2 GiB memory limit and was OOM-killed about three days after a restart. #6932 reports per-session growth surviving DELETE on v0.55.2, which may matter for the sweep's scope.
@RaviTharuma, is the metadata-expiry sweep still planned on your side, or would it help if I took it over?