Skip to content

fix(server): release a deleted session's runtime and stop its toolsets - #5046

Merged
dgageot merged 3 commits into
docker:mainfrom
keithcroney-rgb:fix/release-runtime-on-session-delete
Nov 26, 2026
Merged

dgageot merged 3 commits into
docker:mainfrom
keithcroney-rgb:fix/release-runtime-on-session-delete

Conversation

@keithcroney-rgb

Copy link
Copy Markdown
Contributor

Supersedes #3884, which was closed as stale after the conflicts it picked up (the diagnosis and design were reviewed there and held up). finishSessionDeletion has changed a lot since, so this is a fresh change against current main, with credit to @EronWright for the original analysis.

Problem

In serve api, every session builds its own team and runtime (runtimeForSession). DeleteSession and BatchDeleteSessions end up in finishSessionDeletion, 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.Close stops background agents, clears the tools-changed handler and closes extraToolsetRuns. That last one only owns the extra toolsets of skill sub-sessions, not the team's agent toolsets.
  • Team.StopToolSets is reached in pkg/server only by GetAgentToolCount, 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

  • activeRuntimes records the *team.Team that RunSession built (runtimeForSession now returns it). It is nil for attached runtimes.
  • When a server-owned runtime (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, as finishSessionDeletion already does for their sinks.
  • The existing deletedSessions cleanup 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:

step bound why
stream wait 5 min same window deletedSessions cleanup already uses
runtime.Close 10 s, own goroutine, panics recovered Close waits on background agents with no timeout of its own
StopToolSets 30 s, own budget, always runs after Close stopping toolsets is what frees the MCP clients, so a hung or panicking Close must not skip it

WaitStopped keeps 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=true timing 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:

  • Teams are not shared between sessions: loadTeamWithConfig calls teamloader.LoadWithConfig for every construction, with no team cache.
  • The process-wide plan toolset is reachable from a team through workspaceToolSet.Unwrap, but it has no Stop, so StopToolSets cannot affect other sessions through it.
  • GetAgentToolCount already loads a team, starts its toolsets and stops them while other sessions are live.
  • Agent.StopToolSets uses StopIfStarted, so toolsets that never started are untouched and a second stop is a no-op. Team.StopToolSets now aggregates errors instead of failing fast.
  • The stream wait follows the existing rule that nothing stops a toolset under a running turn. A new stream cannot start after the delete: RunSession and the other users re-check runtimeSessions under sm.mux, and deleting is set before the store row goes.

I used StopToolSets rather than Team.Dispose (which closeWorktreeRuntime pairs with Close for background worktree teams) on purpose. Dispose walks Unwrap chains into process-wide shared toolsets such as plan's, and its contract assumes nothing else owns them. StopToolSets only stops what the team started. If maintainers prefer Dispose semantics for session teams, it is a one-line swap in releaseRuntimeResourcesWithin.

Logging uses slog.*Context, like the rest of pkg/server. docker-agent discards slog output unless --debug is 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:

  • deleting a server-owned session closes its runtime and stops its team's toolsets
  • batch delete does too
  • an attached runtime is left alone (hand-built entry, and through AttachRuntime)
  • RunSession records 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)
  • a running stream delays the release until it ends
  • a Close that hangs, or one that panics, still gets the toolsets stopped
  • a nil team is skipped and the runtime is still closed

go test -race -shuffle=on ./pkg/server/ passes and go run ./lint . reports no offenses.

Evidence from a running server

On a local serve api instance 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:

build goroutines after 20 sessions
stock v1.150.0 143
stock v1.165.0 145
same fix applied to v1.150.0 26 to 29, flat between measurements

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

  • Closing a TUI tab leaks its runtime, session and context in --listen mode #4909: closing a TUI tab in --listen mode leaves its attached runtime in runtimeSessions. Same area, different owner (the embedder), so it needs a detach path rather than this change.
  • SessionManager has no shutdown hook, so sessions that are never deleted still keep their toolsets until the process exits.
  • The defer run.Close() in runtimeForSession for "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

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>
@keithcroney-rgb
keithcroney-rgb requested a review from a team as a code owner November 26, 2026 20:31
keithcroney-rgb and others added 2 commits November 26, 2026 12:38
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>
@aheritier aheritier added area/api For features/issues/fixes related to the usage of the cagent API kind/fix PR fixes a bug (maps to fix:). Use on PRs only. labels Nov 26, 2026
@dgageot
dgageot added this pull request to the merge queue Nov 26, 2026
Merged via the queue into docker:main with commit 93914a4 Nov 26, 2026
17 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/api For features/issues/fixes related to the usage of the cagent API kind/fix PR fixes a bug (maps to fix:). Use on PRs only.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants