Repository navigation
Stop supervisors when their containers have exited - #6960
christensenjairus wants to merge 9 commits into
Conversation
|
@amirejaz could you take a look at this? This fixes an issue I've seen for a while where resources aren't cleaned up properly and almost always (currently) needs manual intervention when it happens. |
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #6960 +/- ##
==========================================
+ Coverage 80.88% 81.41% +0.52%
==========================================
Files 863 878 +15
Lines 88513 90182 +1669
==========================================
+ Hits 71592 73418 +1826
+ Misses 16916 16759 -157
Partials 5 5 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
|
I don't care if you scrap this PR entirely as long as it gets fixed :) |
Clean up the supervisor even when its container has exited or disappeared. Keep its PID through retry backoff and cancel retries during shutdown so explicit stop does not leave it recreating the container. Verify proxy identity before signaling and preserve saved-state semantics during foreground cleanup. Add regression coverage for shutdown ordering, identity, timeouts, retry cancellation, and remote stop states. Signed-off-by: Jairus Christensen <christensenjairus@gmail.com>
Signed-off-by: Jairus Christensen <christensenjairus@gmail.com>
Stop the workload supervisor before fresh runtime removal so automatic restart cannot race normal teardown. Use saved physical names when the primary is missing and tolerate concurrent not-found results. Restrict orphan helper cleanup to exact-name ToolHive auxiliary containers. Cover deletion ordering, absent primaries, cleanup ownership, and preserved auxiliary state. Signed-off-by: Jairus Christensen <jchristensen@moveworks.ai>
7c76d9f to
c68dcbf
Compare
|
Thanks for putting this PR and sorry for the delay in reviewing. I will take a look today |
jhrozek
left a comment
There was a problem hiding this comment.
Thanks for digging into this. A supervisor that survives thv stop and brings the container back is a real bug, and the core of the fix is the right shape: the supervisor (not each runner attempt) owns the PID, the backoff can be cancelled, and the PID is checked before we signal it. Please keep all of that.
We ran a review focused on what else changes for users, because stop and rm sit under the CLI, thv serve (which ToolHive Studio uses), and group operations. A few side effects showed up that break flows which work on main today. I've left inline comments with a way to reproduce each one, a suggested fix, and a test that would catch it. Roughly in priority order:
thv stopnow overwriteserrorandpolicy_stoppedwithstopped, even when there was nothing to stop (inline onstopContainerWorkload).thv rmnow always calls runtime removal. That makes delete fail in cases where it used to succeed, and letsthv rm <name that doesn't exist>delete a network by name (inline ondeleteContainerWorkloadand DockerRemoveWorkload).- Delete drops the real container name it already looked up (inline).
- The foreground identity check doesn't do what its comment says (inline in
toolhive_proxy.go).
One more that I couldn't leave inline because the code isn't in the diff: thv restart / thv start while a supervisor is in restart backoff still starts a second supervisor. maybeSetupContainerWorkload only calls stopProcess when the status is running or the container is running (the shouldStop block, manager.go around line 1626-1635). During backoff the status is starting and the container has exited, so neither is true. The new supervisor overwrites the PID and the old one wakes up later and recreates the container. This happens on main too, but it's the same bug this PR is about, and now that the PID stays recorded during backoff the fix is small: when a PID is recorded and it isn't our own, stop it before spawning, whatever the status. The "isn't our own" part matters. A detached supervisor is thv start <name> --foreground, which runs this same function, and its parent has already recorded its PID, so without an os.Getpid() check the freshly spawned supervisor would find itself and SIGTERM itself. Keep the existing auxiliary-workload guard too. Two tests would cover it: status starting, container exited, live verified PID recorded, and restart signals that PID before spawning; and the recorded PID is os.Getpid(), so restart doesn't signal it.
Smaller things, no need to block on these:
- A cancel that doesn't come from
thv stop/thv rmstill leaves the workload instarting(inline onfinishWorkloadRun). This isn't new, main ends up in the same place, but your change is a natural spot to close it. - Stop and rm now wait up to 5 seconds for the proxy to exit, and then possibly another 5 through the port fallback (inline on
stopVerifiedProxy). Only servers that are slow to stop are affected, but they'll print a warning. clientManagerFactoryadds another nil-checked function hook onDefaultManager(.claude/rules/testing.mdasks us not to grow those;portFreeris the existing one).proxyExitTimeoutis less of a concern since it's really config with a default. For the client manager, a small interface seam would avoid the nil check in production code.savedWorkloadStillExistsopens the run-config store directly, which is why the new tests have to reset XDG dirs and the config singleton and can't run in parallel. Injecting a smallexists(ctx, name)dependency would make those tests simpler.TestDefaultManager_spawnDetached_ReapsOwnedChildrendoesn't skip on Windows, unlikestartKillableProcess. CI is Linux-only, so this is low priority.docs/arch/08-workloads-lifecycle.mdreads like a changelog in places ("The unchanged--all…", "still excludes", "Terminal status handling is unchanged"). It's easier to maintain if it describes how things work now. Once the stop behaviour from thestopContainerWorkloadcomment is settled, the state diagram near the top may need new transitions intoStoppingtoo; today it only showsRunning --> Stopping.- The PR body's user-facing section should list items 1 and 2 as before/after, plus the exit code change from the
finishWorkloadRuncomment, so the release notes are right. - Heads-up: open PR #7049, "fix(docker): clean up isolation resources when workload setup fails", adds a new call to
removeProxyContainersin client.go. Besides a likely merge conflict, the label filter you added changes what that call removes, so whichever PR lands second should check the two still fit together.
|
@amirejaz I ran an AI-assisted review on the PR, but because you know this area of code the best, your review would be appreciated! |
Stop only rewrites status and client config when a container or supervisor was live, so error and policy_stopped reasons survive. Delete skips runtime removal for unknown names, tolerates removal errors for containers that are already gone, and uses the runtime container name. Docker only deletes ToolHive-labelled networks. Tracked supervisor identity now parses argv and requires the workload name for start, restart, and named run. Start and restart stop a recorded supervisor in backoff before spawning, a cancelled run marks its workload stopped under the status lock, and a proxy that is still exiting is not signalled again by the port fallback.
@jhrozek super appreciate this. it looks pretty thorough. Mind throwing it at this PR again? Codespell ci failure is from existing main btw |
Identify the thv subcommand as the first non-flag argument and ignore MCP server arguments after --, so another command's flag values can't pass for a supervisor. Accept the -a/-g shorthands, --all=, and --from-config runs. Start and restart leave a live foreground thv run in charge instead of stopping it, because its exit cleanup deletes the workload. Stop only treats a recorded PID as live when its process exists, and handles a container that disappears between list and inspect.
…nsenjairus/toolhive into stop-exited-container-proxy
|
heads up, I made two decisions (details in the pr description) that I'm fully open to changing
|
amirejaz
left a comment
There was a problem hiding this comment.
Thanks for working on this, and for addressing Jakub's review. The gated status writes, the delete guard, the runtime name and the argv check all look good now, so I won't repeat any of that.
I went through it with the earlier fixes in this area in mind (#2306, #4325, #3422, #4857, #6076, #2927), and the PID ownership through backoff holds up against them. My remaining concerns are all about handing over from one supervisor to the next. I left three inline comments on that, plus a smaller one on the remote path.
Separate from this PR, and fine as a follow-up: the running early return in maybeSetupContainerWorkload still uses isSupervisorProcessAlive, which doesn't check whether the process exists. After a kill -9, restart is still a no-op. hasLiveSupervisorPID could be used there.
Could you also add these behaviour changes to the PR body?
- start during a foreground
thv runbackoff now returns success without doing anything - a run that hits its deadline (not just a signal) now exits 0 and ends up
stopped
| if err != nil || pid <= 0 || pid == os.Getpid() { | ||
| return | ||
| } | ||
| d.stopProcess(ctx, name) |
There was a problem hiding this comment.
This ignores the result of stopProcess, so if the old supervisor is still exiting after 5s (or can't be verified), we spawn a new one anyway. If the old one was mid-attempt, for example during a slow pull, its stopMCPServer stops the container by name and can take down the new supervisor's container. I think start should return an error unless the old one is confirmed gone. Delete has the same gap when it hits proxyExiting.
There was a problem hiding this comment.
Fixed in ad66f89. Start/restart now error out unless the old supervisor is actually gone ("still exiting, retry") or fail if it can't be verified. rm does the same, sets Error, and leaves the container alone. Stop still lets a supervisor that's still exiting through, since it's already stopping.
I actually hit this moving my local stack onto this build: about half the old supervisors took more than 5s to exit, and start correctly refused until they were gone.
There was a problem hiding this comment.
Still waits for the old supervisor to be gone, but CI showed shutdown routinely takes well over 5s, so delete/start/restart now SIGKILL it after 5s and only fail if it survives that (e90abd3). Stop still lets it exit on its own.
| slog.Debug("skipping stopped mark: status changed", "workload", workloadName, "status", statusFile.Status) | ||
| return nil | ||
| } | ||
| if statusFile.ProcessID != 0 && statusFile.ProcessID != ownerPID { |
There was a problem hiding this comment.
By the time this runs, finishWorkloadRun has already reset our PID to 0, so "PID 0" can also mean a replacement that has written starting but hasn't recorded its PID yet. Combined with the overlap above, the old supervisor can flip the new one to stopped. Could we only accept ProcessID == ownerPID, and do the reset and this write under one lock?
There was a problem hiding this comment.
Done. It only matches ProcessID == ownerPID now, and the PID reset and the status write happen under one lock. finishWorkloadRun no longer clears the PID first.
| // something to report. Otherwise the existing status (for example error or | ||
| // policy_stopped) and client configuration stay as they are. Read the PID | ||
| // before cleanup, because a successful proxy stop clears it. | ||
| live := (found && container.IsRunning()) || d.hasLiveSupervisorPID(ctx, labels.GetContainerBaseName(container.Labels)) |
There was a problem hiding this comment.
hasLiveSupervisorPID treats an unverifiable PID as live, but stopProcess won't signal it. So stop writes stopped, the supervisor sees the container exit and restarts it, and the status is now wrong. If the PID is alive but can't be verified, I'd rather stop/rm fail with a clear message than report success.
There was a problem hiding this comment.
Agreed. stop/rm (and start) now fail with a clear error if the PID is alive but can't be verified. A PID that's clearly someone else's (reuse) still doesn't block, so a recycled PID can't make a workload undeletable.
| @@ -1379,7 +1640,7 @@ func (d *DefaultManager) maybeSetupRemoteWorkload( | |||
| slog.Debug("failed to set workload status to stopping", "workload", name, "error", err) | |||
| } | |||
| d.stopProxyIfNeeded(ctx, name, runConfig.BaseName) | |||
There was a problem hiding this comment.
The container path leaves a foreground thv run in charge, but this path will still SIGTERM it, and it then deletes the workload mid-restart. Main does the same, so this isn't a regression, but it would be good to either add the same guard here or note why remote is different.
There was a problem hiding this comment.
Added the same check to the remote path, and remote start also requires the old supervisor to be gone before starting a new one now. There's a test in manager_supervisor_test.go.
Start, restart, and delete now fail unless the previous supervisor is confirmed gone. A supervisor still exiting after SIGTERM would otherwise stop the replacement's container or act on a deleted workload. A recorded PID that is alive but cannot be inspected now makes stop, delete, start, and restart fail instead of reporting success while that process may still restart the container. An inspected process that is not the supervisor, such as after PID reuse, is still left alone. A cancelled supervisor clears its PID and writes stopped in one locked write, and only when the recorded PID is its own, so a replacement that has written starting without a PID keeps its status. Remote start and restart follow the same rules, including leaving a foreground thv run in charge. Signed-off-by: Jairus Christensen <christensenjairus@gmail.com>
Added both to the PR body, plus the new failure cases from this round. |
Fixed in d3ee667/ad66f89 |
A SIGTERMed supervisor can take up to a minute to stop its containers, so requiring it to exit within 5s made start, restart, and rm fail routinely. Delete, start, and restart now kill a verified supervisor that is still exiting after 5s and fail only if it survives the kill. Stop keeps tolerating an exiting supervisor. Signed-off-by: Jairus Christensen <christensenjairus@gmail.com>
Summary
An explicit
thv stop <name>can return success while the supervisor survives and recreates an exited or missing container. Stop currently returns before proxy cleanup in those cases, and the supervisor drops its recorded PID between restart attempts.The supervisor now keeps its PID through backoff and cancels retries on shutdown. Stop and delete always try proxy cleanup, and they verify the supervisor from its
thvsubcommand and arguments before they signal it. Stop only rewrites status when something was live. Delete only reaches the runtime when there is a container or saved configuration. Start and restart stop a detached orstart/restartsupervisor that is waiting in backoff, and kill it if it is still exiting after 5s, failing only if it survives the kill. Delete does the same. Stop, delete, start, and restart fail instead of reporting success when the recorded supervisor is alive but can't be verified.Related to #5393; this covers exited or missing containers rather than only missing status files.
Type of change
Test plan
task lint-fix(golangci-lint v2.15.0) at e90abd3: 0 issues.task testat e90abd3: all packages passed.task genleft the regenerated mocks unchanged.main:task buildand race-enabled tests forpkg/workloads/...,pkg/process/...,pkg/runner/..., andcmd/thv/...passed.thvsupervisors to this build withthv stopthenthv start. About half of the old supervisors were still exiting 5s after SIGTERM;startrefused with "still exiting" until they had exited, then started a single supervisor. Where a health watcher ran its ownthv startat the same time, each workload still ended with one supervisor.restartalias. Verified no supervisor respawn, repeated-stop success, saved configuration preservation where applicable, and no recreated status after foreground deletion.thv run→thv stop→thv restartkilled the still-exiting supervisor after 5s and the workload reachedrunning;thv rmthen left no status, supervisor, container, or network.thv rm nosuchname, stopping a workload inerrorwith an exited container, andthv starton a foregroundthv runin backoff.restartandrmfailed; e90abd3 kills them instead.Changes
pkg/workloads/manager.gothv run) and kill them if they are still exiting after 5s, apply the same handoff to remote workloads, fail stop/delete/start on a live supervisor that can't be verified, kill a signalled supervisor that is still exiting on delete and fail only if it survives, skip the port fallback while a signalled proxy exits.pkg/workloads/statuses/SetWorkloadStoppedIfOwned, which, under one file lock and only when the recorded PID is the caller's, clears the PID and moves astarting/runningworkload tostopped.pkg/process/toolhive_proxy.go--are ignored, and the workload must be named or selected. AddIsForegroundRunSupervisorForWorkload.pkg/container/docker/client.gopkg/process/kill.goForceKillProcess(SIGKILL on Unix, TerminateProcess on Windows).pkg/process/find_windows.gopkg/runner/runner.gopkg/workloads/*_test.go,pkg/process/*_test.go,pkg/container/docker/*_test.go,pkg/workloads/statuses/*_test.gopkg/process/mocks/,pkg/workloads/statuses/mocks/docs/arch/08-workloads-lifecycle.mdDoes this introduce a user-facing change?
Yes.
stopping/stoppedand removes client config only if the container was running or the recorded supervisor PID belongs to a running process. Anerrororpolicy_stoppedworkload with nothing live keeps its status and reason, even with a stale PID recorded.thv rm nosuchname). With a saved run config, it attempts removal using the container's runtime name, thenContainerName, then the workload name. If removal fails and the container still doesn't exist, delete logs the error and cleans up saved state.toolhive-<name>-internalandtoolhive-externalby name. After: it only deletes networks labelledtoolhive=truewith a workload name label.start/restartsupervisor first If it is still exiting after 5s, start kills it (SIGKILL on Unix) and fails with "its supervisor process is still exiting; retry once it has stopped" only if it is still alive 5s after that. If the recorded supervisor is a live foregroundthv run, including one in backoff, start does nothing and returns success, the same as for a running workload.stopping, the status becomeserror. A live PID that was inspected and clearly isn't ToolHive's (PID reuse) still doesn't block.error, and leaves the container and saved state for a laterthv rm. Stop still succeeds in this case.thv run/startcancelled by a signal or deadline. Before: the command returned the runner's error, and the status stayedstartingduring backoff. After: the command exits 0, and the workload is markedstoppedif the recorded PID is still the caller's.starting,auth_retrying,unauthenticated, andunhealthyworkloads tostopped.Implementation plan
Implementation plan
Special notes for reviewers
The production diff is about 1,130 changed lines across 9 files, which is over the 400-line guideline. Most of it is the stop/delete gating, the argv identity check, and the supervisor handoff on start/restart/delete, which share one shutdown contract. Tests use small interface seams for client config and saved run config checks instead of filesystem state.
Deliberate decisions:
thv runin charge. The review asked start/restart to stop any recorded supervisor before spawning. A non-detachedthv rundeletes its container, saved config, and status when it exits, so stopping it would delete the workload and then fail to start it. Start and restart treat that case as already running instead, for both container and remote workloads. Detached andstart/restartsupervisors are still stopped, and replaced only once they have exited.SetWorkloadStoppedIfOwneduses the existingwithFileLock. That helper unlinks the lock file on release, so two callers can lock different inodes and a concurrent delete can still race the guardedstoppedwrite. Every status write uses this helper, so moving it toAcquireTrackedLockbelongs in a separate PR.Cleanup is bounded and best-effort, so it can leave a proxy or port active. There is no process start-time check, so a reused PID running a matching
thvcommand can't be told apart. The saved-state recheck and the final status write are not atomic.--all/--groupstop still skipsstartingworkloads. Stop sends SIGTERM (TerminateProcess on Windows) without escalation.Heads-up for #7049: it adds a
removeProxyContainerscall inpkg/container/docker/client.go, and this PR changes which networks and proxy containers the label filters match. Whichever PR lands second should recheck that path.