Repository navigation
fix(server): release a deleted session's runtime and stop its toolsets - #5046
Merged
dgageot merged 3 commits intoNov 26, 2026
Merged
Conversation
Deleting a session in `serve api` dropped its runtime from the session manager but never closed it or stopped its team's toolsets. LocalRuntime.Close does not stop the team's toolsets (extraToolsetRuns only owns skill sub-session extras), and StopToolSets was reached only through the throwaway team in GetAgentToolCount. Every deleted session therefore kept its MCP client sessions, supervisors and connections alive until the process exited. Record the team RunSession builds on activeRuntimes. When a server-owned runtime (done == nil) is deleted, by DeleteSession or BatchDeleteSessions, wait for its stream to end, then close the runtime and stop the team's toolsets in the background. Attached runtimes (AttachRuntime) belong to their embedder and are left alone. The wait is bounded to 5 minutes. Close is bounded to 10 seconds, runs with panic recovery, and never prevents the toolsets from being stopped (30 second budget). WaitStopped keeps its meaning (the stream has ended). The existing deletedSessions cleanup shares the single wait with the release. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Signed-off-by: Keith Croney <keith.croney@docker.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Signed-off-by: Keith Croney <keith.croney@docker.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Signed-off-by: Keith Croney <keith.croney@docker.com>
dgageot
approved these changes
Nov 26, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Supersedes #3884, which was closed as stale after the conflicts it picked up (the diagnosis and design were reviewed there and held up).
finishSessionDeletionhas changed a lot since, so this is a fresh change against currentmain, with credit to @EronWright for the original analysis.Problem
In
serve api, every session builds its own team and runtime (runtimeForSession).DeleteSessionandBatchDeleteSessionsend up infinishSessionDeletion, which clears the sinks, cancels the context and drops the map entry. It never closes the runtime and never stops the team's toolsets:LocalRuntime.Closestops background agents, clears the tools-changed handler and closesextraToolsetRuns. That last one only owns the extra toolsets of skill sub-sessions, not the team's agent toolsets.Team.StopToolSetsis reached inpkg/serveronly byGetAgentToolCount, on a throwaway team.So each deleted session keeps its toolsets running until the process exits. For a remote MCP toolset that is the client session, the supervisor, the held-open connection and the decoded tool schemas. For a stdio MCP toolset it is the subprocess (the case #3884 measured). In a long-running API server that creates and deletes many sessions, goroutines and memory grow with every session.
Fix
activeRuntimesrecords the*team.TeamthatRunSessionbuilt (runtimeForSessionnow returns it). It is nil for attached runtimes.done == nil) is deleted, by either delete path, a background goroutine waits for the stream to end, then closes the runtime and stops the team's toolsets. Attached runtimes (AttachRuntime) belong to their embedder and are left alone, asfinishSessionDeletionalready does for their sinks.deletedSessionscleanup goroutine and the release share one stream wait, so there is still one goroutine per deleted session.Bounds, so a wedged session cannot hold things forever or starve the stop:
deletedSessionscleanup already usesruntime.CloseClosewaits on background agents with no timeout of its ownStopToolSetsCloseClosemust not skip itWaitStoppedkeeps its meaning (the stream has ended) and does not wait for the release. #3884 reworked it to wait for teardown; I left it alone to keep this change small and the?wait=truetiming unchanged. Happy to follow #3884 here if maintainers prefer.Why this should be safe
I re-checked the points raised in the #3884 review against
main:loadTeamWithConfigcallsteamloader.LoadWithConfigfor every construction, with no team cache.plantoolset is reachable from a team throughworkspaceToolSet.Unwrap, but it has noStop, soStopToolSetscannot affect other sessions through it.GetAgentToolCountalready loads a team, starts its toolsets and stops them while other sessions are live.Agent.StopToolSetsusesStopIfStarted, so toolsets that never started are untouched and a second stop is a no-op.Team.StopToolSetsnow aggregates errors instead of failing fast.RunSessionand the other users re-checkruntimeSessionsundersm.mux, anddeletingis set before the store row goes.I used
StopToolSetsrather thanTeam.Dispose(whichcloseWorktreeRuntimepairs withClosefor background worktree teams) on purpose.DisposewalksUnwrapchains into process-wide shared toolsets such asplan's, and its contract assumes nothing else owns them.StopToolSetsonly stops what the team started. If maintainers preferDisposesemantics for session teams, it is a one-line swap inreleaseRuntimeResourcesWithin.Logging uses
slog.*Context, like the rest ofpkg/server.docker-agentdiscards slog output unless--debugis set, so a failed release is visible only in debug logs.Tests
pkg/server/session_release_test.go, each checked by removing the corresponding change and watching it fail:AttachRuntime)RunSessionrecords the team it built (this is the review finding from fix(server): stop per-session toolsets on session delete #3884: the one line that closes the leak was asserted nowhere)Closethat hangs, or one that panics, still gets the toolsets stoppedgo test -race -shuffle=on ./pkg/server/passes andgo run ./lint .reports no offenses.Evidence from a running server
On a local
serve apiinstance running a multi-tool agent with a remote MCP toolset, I replayed 20 sessions (create, run, delete) and recorded the goroutine count after the last one:On the stock builds the goroutine profile shows exactly 20 goroutines in each of six MCP client stack groups, one per session. With the fix there are none, and no close or stop errors are logged. I have not re-run that end-to-end replay on this branch (it was measured on the v1.150.0 backport of the same change), only the unit tests above.
Related, not fixed here
--listenmode leaves its attached runtime inruntimeSessions. Same area, different owner (the embedder), so it needs a detach path rather than this change.SessionManagerhas no shutdown hook, so sessions that are never deleted still keep their toolsets until the process exits.defer run.Close()inruntimeForSessionfor "any later construction step fails" currently guards no failing step, and would not stop the team's toolsets if one were added.🤖 Generated with Claude Code