Skip to content

Stop supervisors when their containers have exited - #6960

Open
christensenjairus wants to merge 9 commits into
stacklok:mainfrom
christensenjairus:stop-exited-container-proxy
Open

christensenjairus wants to merge 9 commits into
stacklok:mainfrom
christensenjairus:stop-exited-container-proxy

Conversation

@christensenjairus

@christensenjairus christensenjairus commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

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 thv subcommand 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 or start/restart supervisor 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

  • Bug fix
  • New feature
  • Refactoring (no behavior change)
  • Dependency update
  • Documentation
  • Other (describe):

Test plan

  • task lint-fix (golangci-lint v2.15.0) at e90abd3: 0 issues.
  • task test at e90abd3: all packages passed. task gen left the regenerated mocks unchanged.
  • ad66f89 merged locally with current main: task build and race-enabled tests for pkg/workloads/..., pkg/process/..., pkg/runner/..., and cmd/thv/... passed.
  • Manual: moved a local stack of 28 Podman workloads from Homebrew thv supervisors to this build with thv stop then thv start. About half of the old supervisors were still exiting 5s after SIGTERM; start refused with "still exiting" until they had exited, then started a single supervisor. Where a health watcher ran its own thv start at the same time, each workload still ended with one supervisor.
  • Manual regression scenarios for the initial fix: detached retry backoff, removed container, foreground backoff, foreground normal shutdown, and foreground restart alias. Verified no supervisor respawn, repeated-stop success, saved configuration preservation where applicable, and no recreated status after foreground deletion.
  • Manual at e90abd3 (Podman): thv run → thv stop → thv restart killed the still-exiting supervisor after 5s and the workload reached running; thv rm then left no status, supervisor, container, or network.
  • Before merge: rerun the manual scenarios against e90abd3, plus thv rm nosuchname, stopping a workload in error with an exited container, and thv start on a foreground thv run in backoff.
  • CI on e90abd3: all checks passed. E2E Core failed on ad66f89 because supervisors in CI routinely took longer than 5s to exit, so restart and rm failed; e90abd3 kills them instead.
  • Before merge: applicable CLI E2E tests and Linux/Windows runtime CI.

Changes

File Change
pkg/workloads/manager.go Gate stop status writes on a running container or a live supervisor process, guard runtime removal on delete, keep the supervisor PID through cancellable backoff, stop backoff supervisors on start/restart (except a foreground thv 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/ Add SetWorkloadStoppedIfOwned, which, under one file lock and only when the recorded PID is the caller's, clears the PID and moves a starting/running workload to stopped.
pkg/process/toolhive_proxy.go Verify tracked supervisors from argv: the subcommand is the first non-flag argument, arguments after -- are ignored, and the workload must be named or selected. Add IsForegroundRunSupervisorForWorkload.
pkg/container/docker/client.go Treat an absent workload as already stopped; only delete networks with ToolHive labels.
pkg/process/kill.go Add ForceKillProcess (SIGKILL on Unix, TerminateProcess on Windows).
pkg/process/find_windows.go Distinguish a missing PID from inspection errors.
pkg/runner/runner.go Leave final PID cleanup to the supervisor.
pkg/workloads/*_test.go, pkg/process/*_test.go, pkg/container/docker/*_test.go, pkg/workloads/statuses/*_test.go Regression coverage for each contract above.
pkg/process/mocks/, pkg/workloads/statuses/mocks/ Regenerated mocks.
docs/arch/08-workloads-lifecycle.md Document current stop, delete, start/restart, and proxy termination behavior.

Does this introduce a user-facing change?

Yes.

  • Stop on a workload with nothing live. Before: stop on an exited or missing container returned early with no proxy cleanup, so a supervisor in backoff could recreate it. After: stop always cleans up the proxy and asks the runtime to stop the container. It writes stopping/stopped and removes client config only if the container was running or the recorded supervisor PID belongs to a running process. An error or policy_stopped workload with nothing live keeps its status and reason, even with a stale PID recorded.
  • Delete without a container. Before: delete skipped runtime removal when no container was found. After: delete still skips runtime removal when there is no container and no saved run config (for example thv rm nosuchname). With a saved run config, it attempts removal using the container's runtime name, then ContainerName, then the workload name. If removal fails and the container still doesn't exist, delete logs the error and cleans up saved state.
  • Docker networks. Before: the runtime deleted toolhive-<name>-internal and toolhive-external by name. After: it only deletes networks labelled toolhive=true with a workload name label.
  • Start/restart during backoff. Before: start could spawn a second supervisor next to one waiting in backoff, for container and remote workloads. After: start stops a detached or start/restart supervisor 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 foreground thv run, including one in backoff, start does nothing and returns success, the same as for a running workload.
  • Supervisor that can't be verified. Before: stop could report success while a supervisor it couldn't inspect kept running and restarted the container. After: stop, delete, start, and restart fail with "its recorded supervisor process is running but could not be verified, so it was not stopped". If stop had already written stopping, the status becomes error. A live PID that was inspected and clearly isn't ToolHive's (PID reuse) still doesn't block.
  • Delete while the supervisor is exiting. Before: delete went ahead after signalling the supervisor, even if it hadn't exited. After: if the supervisor hasn't exited within 5s, delete kills it. If it is still alive 5s after the kill, delete fails, sets the status to error, and leaves the container and saved state for a later thv rm. Stop still succeeds in this case.
  • Foreground thv run/start cancelled by a signal or deadline. Before: the command returned the runner's error, and the status stayed starting during backoff. After: the command exits 0, and the workload is marked stopped if the recorded PID is still the caller's.
  • Remote stop also finalizes starting, auth_retrying, unauthenticated, and unhealthy workloads to stopped.

Implementation plan

Implementation plan
  1. Clean up the supervisor before a fresh container stop, including exited and missing containers.
  2. Retain PID ownership across retries and make backoff cancellable.
  3. Preserve saved-state semantics and cover shutdown contracts with regression tests.

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:

  • Start/restart leave a foreground thv run in charge. The review asked start/restart to stop any recorded supervisor before spawning. A non-detached thv run deletes 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 and start/restart supervisors are still stopped, and replaced only once they have exited.
  • Stop lets an exiting supervisor finish; delete, start, and restart kill it. Once signalled, the supervisor is already stopping the workload, which is what stop asked for. Delete, start, and restart act on the container and status that the old supervisor may still touch on its way out, so they kill it after 5s rather than wait: its shutdown stops containers one at a time with a 30s runtime timeout and can take up to a minute. Delete removes the containers itself, and start/restart replace them.
  • Status file locking is unchanged. SetWorkloadStoppedIfOwned uses the existing withFileLock. That helper unlinks the lock file on release, so two callers can lock different inodes and a concurrent delete can still race the guarded stopped write. Every status write uses this helper, so moving it to AcquireTrackedLock belongs 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 thv command can't be told apart. The saved-state recheck and the final status write are not atomic. --all/--group stop still skips starting workloads. Stop sends SIGTERM (TerminateProcess on Windows) without escalation.

Heads-up for #7049: it adds a removeProxyContainers call in pkg/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.

@christensenjairus

Copy link
Copy Markdown
Contributor Author

@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

codecov Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 89.41176% with 45 lines in your changes missing coverage. Please review.
✅ Project coverage is 81.41%. Comparing base (a24f063) to head (e90abd3).
⚠️ Report is 51 commits behind head on main.

Files with missing lines Patch % Lines
pkg/workloads/manager.go 91.34% 25 Missing ⚠️
pkg/container/docker/client.go 80.00% 6 Missing ⚠️
pkg/process/toolhive_proxy.go 94.59% 4 Missing ⚠️
pkg/process/kill.go 62.50% 3 Missing ⚠️
pkg/workloads/statuses/file_status.go 85.00% 3 Missing ⚠️
pkg/workloads/statuses/status.go 0.00% 3 Missing ⚠️
pkg/workloads/statuses/noop.go 0.00% 1 Missing ⚠️
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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@christensenjairus

Copy link
Copy Markdown
Contributor Author

I don't care if you scrap this PR entirely as long as it gets fixed :)

christensenjairus and others added 3 commits November 3, 2026 22:41
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>
@christensenjairus
christensenjairus force-pushed the stop-exited-container-proxy branch from 7c76d9f to c68dcbf Compare November 4, 2026 08:41
@amirejaz

amirejaz commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

Thanks for putting this PR and sorry for the delay in reviewing. I will take a look today

@jhrozek jhrozek left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. thv stop now overwrites error and policy_stopped with stopped, even when there was nothing to stop (inline on stopContainerWorkload).
  2. thv rm now always calls runtime removal. That makes delete fail in cases where it used to succeed, and lets thv rm <name that doesn't exist> delete a network by name (inline on deleteContainerWorkload and Docker RemoveWorkload).
  3. Delete drops the real container name it already looked up (inline).
  4. 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 rm still leaves the workload in starting (inline on finishWorkloadRun). 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.
  • clientManagerFactory adds another nil-checked function hook on DefaultManager (.claude/rules/testing.md asks us not to grow those; portFreer is the existing one). proxyExitTimeout is 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.
  • savedWorkloadStillExists opens 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 small exists(ctx, name) dependency would make those tests simpler.
  • TestDefaultManager_spawnDetached_ReapsOwnedChildren doesn't skip on Windows, unlike startKillableProcess. CI is Linux-only, so this is low priority.
  • docs/arch/08-workloads-lifecycle.md reads 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 the stopContainerWorkload comment is settled, the state diagram near the top may need new transitions into Stopping too; today it only shows Running --> Stopping.
  • The PR body's user-facing section should list items 1 and 2 as before/after, plus the exit code change from the finishWorkloadRun comment, 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 removeProxyContainers in 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.

Comment thread pkg/workloads/manager.go Resolved
Comment thread pkg/workloads/manager.go Resolved
Comment thread pkg/workloads/manager.go Resolved
Comment thread pkg/workloads/manager.go Resolved
Comment thread pkg/container/docker/client.go Resolved
Comment thread pkg/process/toolhive_proxy.go Resolved
Comment thread pkg/workloads/manager.go Resolved
Comment thread docs/arch/08-workloads-lifecycle.md Resolved
@jhrozek

jhrozek commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

@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.
@christensenjairus

christensenjairus commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor Author

I ran an AI-assisted review on the PR

@jhrozek super appreciate this. it looks pretty thorough. Mind throwing it at this PR again?

Codespell ci failure is from existing main btw

christensenjairus and others added 3 commits November 4, 2026 20:49
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
@christensenjairus

Copy link
Copy Markdown
Contributor Author

heads up, I made two decisions (details in the pr description) that I'm fully open to changing

Two deliberate decisions:

  1. Start/restart leave a foreground thv run in charge. The review asked start/restart to stop any recorded supervisor before spawning. A non-detached thv run deletes 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. Detached and start/restart supervisors are still stopped and replaced.
  2. Status file locking is unchanged. SetWorkloadStoppedIfOwned uses the existing withFileLock. That helper unlinks the lock file on release, so two callers can lock different inodes and a concurrent delete can still race the guarded stopped write. Every status write uses this helper, so moving it to AcquireTrackedLock belongs in a separate PR.

@amirejaz amirejaz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 run backoff now returns success without doing anything
  • a run that hits its deadline (not just a signal) now exits 0 and ends up stopped

Comment thread pkg/workloads/manager.go Outdated
if err != nil || pid <= 0 || pid == os.Getpid() {
return
}
d.stopProcess(ctx, name)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread pkg/workloads/statuses/file_status.go Outdated
slog.Debug("skipping stopped mark: status changed", "workload", workloadName, "status", statusFile.Status)
return nil
}
if statusFile.ProcessID != 0 && statusFile.ProcessID != ownerPID {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread pkg/workloads/manager.go Outdated
// 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))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread pkg/workloads/manager.go Outdated
@@ -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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>
@christensenjairus

Copy link
Copy Markdown
Contributor Author

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 run` backoff now returns success without doing anything

* a run that hits its deadline (not just a signal) now exits 0 and ends up `stopped`

Added both to the PR body, plus the new failure cases from this round.

@christensenjairus

Copy link
Copy Markdown
Contributor Author

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:

1. `thv stop` now overwrites `error` and `policy_stopped` with `stopped`, even when there was nothing to stop (inline on `stopContainerWorkload`).

2. `thv rm` now always calls runtime removal. That makes delete fail in cases where it used to succeed, and lets `thv rm <name that doesn't exist>` delete a network by name (inline on `deleteContainerWorkload` and Docker `RemoveWorkload`).

3. Delete drops the real container name it already looked up (inline).

4. 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 rm` still leaves the workload in `starting` (inline on `finishWorkloadRun`). 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.

* `clientManagerFactory` adds another nil-checked function hook on `DefaultManager` (`.claude/rules/testing.md` asks us not to grow those; `portFreer` is the existing one). `proxyExitTimeout` is 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.

* `savedWorkloadStillExists` opens 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 small `exists(ctx, name)` dependency would make those tests simpler.

* `TestDefaultManager_spawnDetached_ReapsOwnedChildren` doesn't skip on Windows, unlike `startKillableProcess`. CI is Linux-only, so this is low priority.

* `docs/arch/08-workloads-lifecycle.md` reads 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 the `stopContainerWorkload` comment is settled, the state diagram near the top may need new transitions into `Stopping` too; today it only shows `Running --> Stopping`.

* The PR body's user-facing section should list items 1 and 2 as before/after, plus the exit code change from the `finishWorkloadRun` comment, 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 `removeProxyContainers` in 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.

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>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants