From fd643ff0f695a1f9ea6f716aacd02fd63998435a Mon Sep 17 00:00:00 2001 From: Jairus Christensen Date: Tue, 27 Oct 2026 09:35:55 -0600 Subject: [PATCH 1/7] Stop exited workloads and their supervisors 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 --- docs/arch/08-workloads-lifecycle.md | 22 +- pkg/container/docker/client.go | 2 +- pkg/container/docker/client_stop_test.go | 25 + pkg/process/find_windows.go | 14 +- pkg/process/toolhive_proxy.go | 37 +- pkg/process/toolhive_proxy_test.go | 122 ++++ pkg/runner/runner.go | 16 +- pkg/workloads/manager.go | 330 +++++++--- pkg/workloads/manager_test.go | 767 +++++++++++++++++++++-- 9 files changed, 1156 insertions(+), 179 deletions(-) diff --git a/docs/arch/08-workloads-lifecycle.md b/docs/arch/08-workloads-lifecycle.md index e3288960e2..e13914cebf 100644 --- a/docs/arch/08-workloads-lifecycle.md +++ b/docs/arch/08-workloads-lifecycle.md @@ -81,8 +81,22 @@ thv stop my-server **Container workload**: Stops proxy process → stops container → preserves state +Explicit named stop attempts proxy cleanup even when the primary container has +exited or disappeared. After cleanup, it makes a fresh attempt to stop the +container by name. For an existing saved workload, successful stop writes +`Stopped`, replacing prior `Error` or `PolicyStopped` status and context. +Auxiliary workloads skip proxy cleanup. + +The unchanged `--all` and `--group` selection still excludes `Starting` workloads, +including supervisors waiting in restart backoff. This recovery applies to +explicit named stop, not all stop forms. + +Stop preserves saved run configuration, but a foreground `run` still deletes its workload during normal exit cleanup. The bounded five-second exit wait means explicit stop can return before the foreground owner's cleanup completes. Stop rechecks saved configuration before writing final status and skips that write if configuration is already gone. This recheck and the status write are not atomic against concurrent deletion, so deletion races remain. Stop does not create status for an unknown missing name. + **Remote workload**: Stops proxy → preserves state +Successful explicit stop transitions a remote workload from `Running`, `Starting`, `AuthRetrying`, `Unauthenticated`, or `Unhealthy` to `Stopped`, subject to the saved-state recheck above. Terminal status handling is unchanged. + **Implementation**: `pkg/workloads/manager.go` ### Start @@ -136,9 +150,13 @@ The same `Applier` backs both the CLI (`thv upgrade apply`) and the API (`POST / ### Proxy termination -Stop and delete terminate the proxy using its recorded PID. When PID-based termination is unavailable or fails (for example, the status file is missing, records no PID, or the process is already gone), they fall back to port-based cleanup: the process holding the proxy port is terminated only after it is confirmed to be this workload's proxy. This prevents an orphaned proxy from continuing to hold the port after the container has been stopped or removed. +Stop and delete verify that the PID recorded in workload status belongs to a ToolHive process. Non-detached supervisors must also have a `run`, `start`, or `restart` token in their arguments. An unnamed `run` may omit its derived workload name from arguments. Foreground `start` and `restart` include the name, but all three use only the recorded PID for workload binding, without a process-birth-time check. Detached supervisors must match the exact workload name. A live PID whose identity cannot be verified remains recorded and is not signaled. -**Implementation**: `pkg/workloads/manager.go` +On Unix, termination uses SIGTERM without escalation. On Windows, it uses TerminateProcess, a hard stop. Both paths wait up to five seconds for exit. If PID-based termination is unavailable or incomplete, they attempt port-based cleanup when saved configuration permits it. This fallback requires an exact workload identity match for the port holder and also waits up to five seconds for exit. Cleanup is best-effort and can leave a proxy running or its port occupied. + +The supervisor keeps its PID registered across container restart attempts, including backoff. Shutdown cancels the backoff. On final exit, PID cleanup clears the recorded PID only if it still matches the exiting process. + +**Implementation**: `pkg/workloads/manager.go`, `pkg/runner/runner.go` ### List diff --git a/pkg/container/docker/client.go b/pkg/container/docker/client.go index 05482a6d4a..b16d4ebd04 100644 --- a/pkg/container/docker/client.go +++ b/pkg/container/docker/client.go @@ -447,7 +447,7 @@ func (c *Client) StopWorkload(ctx context.Context, workloadName string) error { info, err := c.GetWorkloadInfo(ctx, workloadName) if err != nil { // If the container doesn't exist, that's fine - it's already "stopped" - if errors.Is(err, ErrContainerNotFound) { + if errors.Is(err, ErrContainerNotFound) || errors.Is(err, runtime.ErrWorkloadNotFound) { return nil } return err diff --git a/pkg/container/docker/client_stop_test.go b/pkg/container/docker/client_stop_test.go index 4bc00df183..f3f2dcccf5 100644 --- a/pkg/container/docker/client_stop_test.go +++ b/pkg/container/docker/client_stop_test.go @@ -139,6 +139,31 @@ func TestStopWorkload_NotFound_ReturnsNil(t *testing.T) { require.NoError(t, err) } +func TestStopWorkload_EmptyContainerListIsAlreadyStopped(t *testing.T) { + t.Parallel() + + stopCalls := 0 + inspectCalls := 0 + api := &fakeDockerAPI{ + listFunc: func(_ context.Context, _ mobyclient.ContainerListOptions) ([]container.Summary, error) { + return nil, nil + }, + inspectFunc: func(_ context.Context, _ string) (container.InspectResponse, error) { + inspectCalls++ + return container.InspectResponse{}, nil + }, + stopFunc: func(_ context.Context, _ string, _ mobyclient.ContainerStopOptions) error { + stopCalls++ + return nil + }, + } + c := &Client{api: api} + + require.NoError(t, c.StopWorkload(t.Context(), "already-removed")) + assert.Zero(t, inspectCalls, "a missing workload has no container to inspect") + assert.Zero(t, stopCalls, "missing workloads must not call the container stop API") +} + // TestStopProxyContainer_HandlesEnvoyAndSquidTopologies exercises the building // block of the shared cleanup path. StopWorkload iterates the fixed proxy // suffixes (-egress, -ingress, -dns) and calls stopProxyContainer for each; this diff --git a/pkg/process/find_windows.go b/pkg/process/find_windows.go index 1a0326066b..c875066d3e 100644 --- a/pkg/process/find_windows.go +++ b/pkg/process/find_windows.go @@ -6,6 +6,7 @@ package process import ( + "errors" "fmt" "syscall" "unsafe" @@ -13,8 +14,9 @@ import ( // Windows API constants const ( - processQueryInformation = 0x0400 - stillActive = 259 + processQueryInformation = 0x0400 + stillActive = 259 + errorInvalidParameter syscall.Errno = 87 ) // Windows API functions @@ -42,8 +44,12 @@ func FindProcess(pid int) (bool, error) { ) if handle == 0 { - // Process doesn't exist or cannot be opened - return false, nil + // With these valid access/inheritance arguments, ERROR_INVALID_PARAMETER + // means the PID does not exist. Access denial leaves its state unknown. + if errors.Is(err, errorInvalidParameter) { + return false, nil + } + return false, fmt.Errorf("failed to open process: %w", err) } // Don't forget to close the handle when we're done diff --git a/pkg/process/toolhive_proxy.go b/pkg/process/toolhive_proxy.go index 837772add9..baf2844ef9 100644 --- a/pkg/process/toolhive_proxy.go +++ b/pkg/process/toolhive_proxy.go @@ -4,6 +4,7 @@ package process import ( + "slices" "strings" gopsutilprocess "github.com/shirou/gopsutil/v4/process" @@ -66,6 +67,38 @@ func IsToolHiveProxyForWorkload(pid int, workloadName string) (bool, error) { return true, nil } +// IsTrackedToolHiveProxyForWorkload verifies a PID read from a workload's status. +// Detached supervisors must match the workload name. Non-detached ToolHive +// run/start/restart supervisors use recorded-PID binding without a process-birth-time check. +// An unnamed run may omit its derived workload name; start/restart include the name. +// Port-discovered PIDs must use IsToolHiveProxyForWorkload instead. +func IsTrackedToolHiveProxyForWorkload(pid int, workloadName string) (bool, error) { + if pid <= 0 || workloadName == "" { + return false, nil + } + p, err := gopsutilprocess.NewProcess(int32(pid)) //nolint:gosec // G115: supported platform PIDs fit int32. + if err != nil { + return false, err + } + env, err := p.Environ() + if err != nil { + return false, err + } + if slices.Contains(env, ToolHiveDetachedEnv+"="+ToolHiveDetachedValue) { + cmdline, err := p.Cmdline() + if err != nil { + return false, err + } + return cmdlineContainsWorkload(cmdline, workloadName), nil + } + cmdline, err := p.Cmdline() + if err != nil { + return false, err + } + return isToolHiveProcess(p) && (strings.Contains(cmdline, " run ") || strings.Contains(cmdline, " start ") || + strings.Contains(cmdline, " restart ")), nil +} + // isToolHiveProcess returns true if p is a ToolHive process (TOOLHIVE_DETACHED // or thv binary in exe/cmdline). func isToolHiveProcess(p *gopsutilprocess.Process) bool { @@ -105,12 +138,12 @@ func cmdlineContainsWorkload(cmdline, workloadName string) bool { if !strings.Contains(cmdline, pattern) { return false } - // Ensure workloadName is not a prefix of a longer word: next char must be space, -, or end + // A hyphen continues the workload name; it is not a token boundary. idx := strings.Index(cmdline, pattern) end := idx + len(pattern) if end >= len(cmdline) { return true } next := cmdline[end] - return next == ' ' || next == '-' + return next == ' ' } diff --git a/pkg/process/toolhive_proxy_test.go b/pkg/process/toolhive_proxy_test.go index 2f126ba6cc..3de4df7b32 100644 --- a/pkg/process/toolhive_proxy_test.go +++ b/pkg/process/toolhive_proxy_test.go @@ -4,7 +4,15 @@ package process import ( + "bufio" + "fmt" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" "testing" + "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -35,6 +43,119 @@ func TestIsToolHiveProxyForWorkload_NonToolHiveProcess(t *testing.T) { assert.False(t, isToolHive) } +func TestIsTrackedToolHiveProxyForWorkload_DetachedRequiresExactWorkload(t *testing.T) { + t.Parallel() + pid := startIdentityProcess(t, true, "start", "github-extra", "--foreground") + + matched, err := IsTrackedToolHiveProxyForWorkload(pid, "github-extra") + require.NoError(t, err) + assert.True(t, matched, "detached supervisor must match its complete workload name") + matched, err = IsTrackedToolHiveProxyForWorkload(pid, "github") + require.NoError(t, err) + assert.False(t, matched, "a hyphen continues the workload name, not a token boundary") +} + +func TestIsTrackedToolHiveProxyForWorkload_ForegroundDoesNotRelaxPortIdentity(t *testing.T) { + t.Parallel() + + for _, tt := range []struct { + name string + args []string + }{ + {name: "unnamed run", args: []string{"run", "--foreground", "example/server"}}, + {name: "named run", args: []string{"run", "--foreground", "--name", "derived-workload-name", "example/server"}}, + {name: "start", args: []string{"start", "derived-workload-name", "--foreground"}}, + {name: "restart", args: []string{"restart", "derived-workload-name", "--foreground"}}, + } { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + pid := startIdentityProcess(t, false, tt.args...) + matched, err := IsTrackedToolHiveProxyForWorkload(pid, "derived-workload-name") + require.NoError(t, err) + assert.True(t, matched, "tracked foreground supervisors must remain stoppable") + if tt.args[0] != "start" { + matched, err = IsToolHiveProxyForWorkload(pid, "derived-workload-name") + require.NoError(t, err) + assert.False(t, matched, "port-discovered foreground supervisor still requires start-workload identity") + } + }) + } +} + +func TestIsTrackedToolHiveProxyForWorkload_RejectsForegroundServe(t *testing.T) { + t.Parallel() + pid := startIdentityProcess(t, false, "serve") + + toolHive, err := IsToolHiveProxyForWorkload(pid, "") + require.NoError(t, err) + require.True(t, toolHive, "fixture must have ToolHive binary identity without a detached marker") + matched, err := IsTrackedToolHiveProxyForWorkload(pid, "stale-workload") + require.NoError(t, err) + assert.False(t, matched, "a stale supervisor PID must not identify ToolHive serve as a workload supervisor") +} + +func TestToolHiveIdentityProcess(t *testing.T) { + t.Parallel() + if os.Getenv("TOOLHIVE_TEST_IDENTITY_HELPER") != "1" { + return + } + fmt.Println("ready") + <-time.After(time.Minute) + os.Exit(1) +} + +func startIdentityProcess(t *testing.T, detached bool, args ...string) int { + t.Helper() + if runtime.GOOS == "windows" { + t.Skip("process identity fixture requires Unix symlinks and process inspection") + } + executable, err := os.Executable() + require.NoError(t, err) + if !detached { + thv := filepath.Join(t.TempDir(), "thv") + require.NoError(t, os.Symlink(executable, thv)) + executable = thv + } + cmd := exec.Command(executable, append([]string{"-test.run=^TestToolHiveIdentityProcess$", "--"}, args...)...) + for _, entry := range os.Environ() { + if !strings.HasPrefix(entry, ToolHiveDetachedEnv+"=") { + cmd.Env = append(cmd.Env, entry) + } + } + cmd.Env = append(cmd.Env, "TOOLHIVE_TEST_IDENTITY_HELPER=1") + if detached { + cmd.Env = append(cmd.Env, ToolHiveDetachedEnv+"="+ToolHiveDetachedValue) + } + stdout, err := cmd.StdoutPipe() + require.NoError(t, err) + require.NoError(t, cmd.Start()) + exited := make(chan struct{}) + go func() { + _ = cmd.Wait() + close(exited) + }() + t.Cleanup(func() { + _ = cmd.Process.Kill() + select { + case <-exited: + case <-time.After(5 * time.Second): + t.Error("identity helper was not reaped") + } + }) + ready := make(chan string, 1) + go func() { + line, _ := bufio.NewReader(stdout).ReadString('\n') + ready <- line + }() + select { + case line := <-ready: + require.Equal(t, "ready\n", line) + case <-time.After(5 * time.Second): + t.Fatal("identity helper did not start") + } + return cmd.Process.Pid +} + func TestContainsThvBinary(t *testing.T) { t.Parallel() tests := []struct { @@ -74,6 +195,7 @@ func TestCmdlineContainsWorkload(t *testing.T) { {"matches at end", "thv start myworkload", "myworkload", true}, {"rejects different workload", "/usr/bin/thv start slack --foreground", "github", false}, {"rejects partial match", "thv start github --foreground", "git", false}, + {"rejects hyphenated name prefix", "thv start github-extra --foreground", "github", false}, {"rejects suffix match", "thv start github --foreground", "hub", false}, {"empty workload", "thv start github --foreground", "", false}, } diff --git a/pkg/runner/runner.go b/pkg/runner/runner.go index 6fa54cddc4..d14162aaaf 100644 --- a/pkg/runner/runner.go +++ b/pkg/runner/runner.go @@ -718,13 +718,6 @@ func (r *Runner) Run(ctx context.Context) error { slog.Warn("failed to cleanup telemetry", "error", err) } - // Remove the PID file if it exists. Use PID-guarded reset so that a - // dying process does not clobber the PID of a replacement process that - // started in the meantime (e.g. during thv rm + thv run). - if err := r.statusManager.ResetWorkloadPIDIfMatch(cleanupCtx, r.Config.BaseName, os.Getpid()); err != nil { - slog.Warn("failed to reset workload PID", "container", r.Config.ContainerName, "error", err) - } - slog.Debug("mcp server stopped", "container", r.Config.ContainerName) } @@ -799,12 +792,6 @@ func (r *Runner) Run(ctx context.Context) error { stopMCPServer("Context cancelled") case <-doneCh: // The transport has already been stopped (likely by the container exit) - // Remove the old PID from the state file. Use PID-guarded reset to - // avoid clobbering a replacement process's PID. - if err := r.statusManager.ResetWorkloadPIDIfMatch(ctx, r.Config.BaseName, os.Getpid()); err != nil { - slog.Warn("failed to reset workload PID", "workload", r.Config.BaseName, "error", err) - } - // Check if workload still exists (using status manager and runtime) // If it doesn't exist, it was removed - clean up client config // If it exists, it exited unexpectedly - signal restart needed @@ -834,7 +821,8 @@ func (r *Runner) Run(ctx context.Context) error { return nil // Exit gracefully, no restart } - // Workload still exists - signal restart needed + // Keep the PID: the same supervisor handles the restart and must remain + // stoppable even while its transport is down during retry backoff. slog.Debug("MCP server stopped, restart needed", "container", r.Config.ContainerName) return ErrContainerExitedRestartNeeded } diff --git a/pkg/workloads/manager.go b/pkg/workloads/manager.go index 644abef2fb..131dd4fd8e 100644 --- a/pkg/workloads/manager.go +++ b/pkg/workloads/manager.go @@ -6,10 +6,12 @@ package workloads import ( + "cmp" "context" "errors" "fmt" "log/slog" + "maps" "os" "os/exec" "path/filepath" @@ -98,10 +100,11 @@ type DefaultManager struct { statuses statuses.StatusManager configProvider config.Provider - retryConfig *retryConfig - newRunner mcpRunnerFactory - detachedSpawner detachedProcessSpawner - portFreer portFreer + retryConfig *retryConfig + newRunner mcpRunnerFactory + detachedSpawner detachedProcessSpawner + portFreer portFreer + proxyExitTimeout time.Duration } // mcpRunner is the subset of *runner.Runner that RunWorkload's retry loop @@ -172,6 +175,18 @@ func withPortFreer(f portFreer) managerOption { return func(d *DefaultManager) { d.portFreer = f } } +// withProxyExitTimeout bounds proxy-exit waits during stop and restart port cleanup. +func withProxyExitTimeout(timeout time.Duration) managerOption { + return func(d *DefaultManager) { d.proxyExitTimeout = timeout } +} + +func (d *DefaultManager) proxyExitTimeoutOrDefault() time.Duration { + if d.proxyExitTimeout > 0 { + return d.proxyExitTimeout + } + return defaultProxyExitTimeout +} + // retryConfigOrDefault returns the manager's retryConfig if set, otherwise defaults. func (d *DefaultManager) retryConfigOrDefault() retryConfig { if d.retryConfig == nil { @@ -212,6 +227,9 @@ func (d *DefaultManager) portFreerOrDefault() portFreer { var ErrWorkloadNotRunning = fmt.Errorf("workload not running") const ( + defaultProxyExitTimeout = 5 * time.Second + workloadPIDCleanupTimeout = 5 * time.Second + // AsyncOperationTimeout is the timeout for async workload operations AsyncOperationTimeout = 5 * time.Minute ) @@ -458,22 +476,24 @@ func (d *DefaultManager) stopRemoteWorkload(ctx context.Context, name string, ru // A remote workload's proxy can outlive its recorded status (e.g. the status // file went missing), so we always try to free an orphaned proxy below — only // the status transitions and client-config cleanup are gated on the workload - // actually running. + // running, starting, retrying authentication, unauthenticated, or unhealthy. workload, err := d.statuses.GetWorkload(ctx, name) if err != nil && !errors.Is(err, rt.ErrWorkloadNotFound) { return fmt.Errorf("failed to find workload %s: %w", name, err) } - running := err == nil && workload.Status == rt.WorkloadStatusRunning + stoppable := err == nil && (workload.Status == rt.WorkloadStatusRunning || workload.Status == rt.WorkloadStatusStarting || + workload.Status == rt.WorkloadStatusAuthRetrying || workload.Status == rt.WorkloadStatusUnauthenticated || + workload.Status == rt.WorkloadStatusUnhealthy) switch { case err != nil: // Status is gone (e.g. a missing status file); don't fail the operation, // but still free an orphaned proxy below. slog.Warn("failed to stop workload", "workload", name, "error", err) - case !running: + case !stoppable: slog.Warn("Failed to stop workload", "workload", name, "error", ErrWorkloadNotRunning) } - if running { + if stoppable { if err := d.statuses.SetWorkloadStatus(ctx, name, rt.WorkloadStatusStopping, ""); err != nil { slog.Debug("failed to set workload status to stopping", "workload", name, "error", err) } @@ -485,41 +505,78 @@ func (d *DefaultManager) stopRemoteWorkload(ctx context.Context, name string, ru d.ensureProxyStopped(ctx, name, runConfig.BaseName, runConfig) } - if running { - // For remote workloads we only need to clean up client configurations; the - // saved state is preserved for restart capability. - if err := removeClientConfigurations(name, false); err != nil { - slog.Warn("failed to remove client configurations", "error", err) - } else { - slog.Debug("client configurations removed", "workload", name) - } - if err := d.statuses.SetWorkloadStatus(ctx, name, rt.WorkloadStatusStopped, ""); err != nil { - slog.Debug("failed to set workload status to stopped", "workload", name, "error", err) - } - slog.Debug("remote workload stopped", "workload", name) + if stoppable { + return d.finishRemoteWorkloadStop(ctx, name, runConfig) + } + return nil +} + +func (d *DefaultManager) finishRemoteWorkloadStop(ctx context.Context, name string, runConfig *runner.RunConfig) error { + exists, err := savedWorkloadStillExists(ctx, name, runConfig, false) + if err != nil { + return err + } + if !exists { + return nil + } + if err := removeClientConfigurations(name, false); err != nil { + slog.Warn("failed to remove client configurations", "error", err) + } else { + slog.Debug("client configurations removed", "workload", name) + } + if err := d.statuses.SetWorkloadStatus(ctx, name, rt.WorkloadStatusStopped, ""); err != nil { + slog.Debug("failed to set workload status to stopped", "workload", name, "error", err) } + slog.Debug("remote workload stopped", "workload", name) return nil } +// Foreground shutdown can delete saved state before the proxy process exits. +// Recheck after cleanup so stop does not recreate its status or repeat client +// cleanup for a deleted workload. Auxiliary/no-config paths retain +// their existing behavior because they need not have their own saved state. +func savedWorkloadStillExists(ctx context.Context, name string, runConfig *runner.RunConfig, isAuxiliary bool) (bool, error) { + if runConfig == nil || isAuxiliary { + return true, nil + } + store, err := state.NewRunConfigStore(state.DefaultAppName) + if err != nil { + return false, fmt.Errorf("failed to open run configuration store after stop: %w", err) + } + exists, err := store.Exists(ctx, cmp.Or(runConfig.BaseName, name)) + if err != nil { + return false, fmt.Errorf("failed to check saved workload after stop: %w", err) + } + return exists, nil +} + // stopContainerWorkload stops a container-based workload. runConfig may be nil -// when the run config could not be loaded; it is used only for port-based proxy -// cleanup when the tracked PID is unavailable. +// when the run config could not be loaded; otherwise it provides saved labels +// if the container is missing and enables port-based proxy cleanup. func (d *DefaultManager) stopContainerWorkload(ctx context.Context, name string, runConfig *runner.RunConfig) error { container, err := d.runtime.GetWorkloadInfo(ctx, name) if err != nil { - if errors.Is(err, rt.ErrWorkloadNotFound) { - // Log but don't fail the entire operation for not found containers - slog.Warn("failed to stop workload", "workload", name, "error", err) + if !errors.Is(err, rt.ErrWorkloadNotFound) { + return fmt.Errorf("failed to find workload %s: %w", name, err) + } + slog.Debug("container not found, proceeding with proxy cleanup", "workload", name) + if runConfig == nil { + // Without saved state, attempt cleanup by the requested name without + // creating a status entry or changing client configurations. + d.ensureProxyStopped(ctx, name, name, nil) + if err := d.runtime.StopWorkload(ctx, name); err != nil { + return fmt.Errorf("failed to stop container: %w", err) + } return nil } - return fmt.Errorf("failed to find workload %s: %w", name, err) - } - running := container.IsRunning() - if !running { - // Log but don't fail the entire operation for not running containers - slog.Warn("Failed to stop workload", "workload", name, "error", ErrWorkloadNotRunning) - return nil + container = rt.ContainerInfo{Name: cmp.Or(runConfig.ContainerName, name), Labels: maps.Clone(runConfig.ContainerLabels)} + if container.Labels == nil { + container.Labels = make(map[string]string) + } + if labels.GetContainerBaseName(container.Labels) == "" { + container.Labels[labels.LabelBaseName] = cmp.Or(runConfig.BaseName, name) + } } // Transition workload to `stopping` state. @@ -527,12 +584,22 @@ func (d *DefaultManager) stopContainerWorkload(ctx context.Context, name string, slog.Debug("failed to set workload status to stopping", "workload", name, "error", err) } - // Use the existing stopWorkloads method for container workloads + // Clean up the proxy before stopping by name, even if the initial container + // was exited or missing: its supervisor may have recreated it since inspection. return d.stopSingleContainerWorkload(ctx, &container, runConfig) } // RunWorkload runs a workload in the foreground with automatic restart on container exit. -func (d *DefaultManager) RunWorkload(ctx context.Context, runConfig *runner.RunConfig) error { +func (d *DefaultManager) RunWorkload(ctx context.Context, runConfig *runner.RunConfig) (runErr error) { + // The supervisor owns its PID across runner attempts, including backoff. + // Final cleanup must survive cancellation without clearing a replacement PID. + defer func() { + runErr = d.finishWorkloadRun(ctx, runConfig.BaseName, runErr) + }() + + if ctx.Err() != nil { + return nil + } // Ensure that the workload has a status entry before starting the process. if err := d.statuses.SetWorkloadStatus(ctx, runConfig.BaseName, rt.WorkloadStatusStarting, ""); err != nil { // Failure to create the initial state is a fatal error. @@ -549,19 +616,28 @@ func (d *DefaultManager) RunWorkload(ctx context.Context, runConfig *runner.RunC for attempt <= maxRetries { if attempt > 1 { slog.Info("restart attempt", "attempt", attempt, "maxRetries", maxRetries, "workload", runConfig.BaseName, "delay", retryDelay) - time.Sleep(retryDelay) + timer := time.NewTimer(retryDelay) + select { + case <-ctx.Done(): + timer.Stop() + return nil + case <-timer.C: + } // Exponential backoff: 5s, 10s, 20s, 40s, 60s (capped) - retryDelay *= 2 - if retryDelay > cfg.maxBackoff { - retryDelay = cfg.maxBackoff - } + retryDelay = min(retryDelay*2, cfg.maxBackoff) } + if ctx.Err() != nil { + return nil + } mcpRunner := newRunner(runConfig, d.statuses) runStartTime := time.Now() err := mcpRunner.Run(ctx) runDuration := time.Since(runStartTime) + if ctx.Err() != nil { + return nil + } if err != nil { // Check if this is a "container exited, restart needed" error @@ -570,33 +646,14 @@ func (d *DefaultManager) RunWorkload(ctx context.Context, runConfig *runner.RunC "workload", runConfig.BaseName, "attempt", attempt, "maxRetries", maxRetries, "runDuration", runDuration) - // Remove from client config so clients notice the restart - clientManager, clientErr := client.NewManager(ctx) - if clientErr == nil { - slog.Debug("removing from client configurations before restart", "workload", runConfig.BaseName) - if removeErr := clientManager.RemoveServerFromClients(ctx, runConfig.BaseName, runConfig.Group); removeErr != nil { - slog.Warn("failed to remove from client config", "error", removeErr) - } - } - // A "stable" run reached at least stableRunThreshold of runtime before // failing — long enough that we treat the next attempt as a fresh // failure rather than another tick of the current retry sequence. stable := runDuration >= cfg.stableRunThreshold - // Set status to starting (since we're restarting) - statusReason := "Container exited, restarting" - if stable { - statusReason = "Container exited after stable run, restarting" - } - statusErr := d.statuses.SetWorkloadStatus( - ctx, - runConfig.BaseName, - rt.WorkloadStatusStarting, - statusReason, - ) - if statusErr != nil { - slog.Warn("failed to set workload status to starting", "workload", runConfig.BaseName, "error", statusErr) + d.prepareWorkloadRestart(ctx, runConfig, stable) + if ctx.Err() != nil { + return nil } // Without this reset of the attempt count, sustained external @@ -620,23 +677,13 @@ func (d *DefaultManager) RunWorkload(ctx context.Context, runConfig *runner.RunC // Exhausted all retries slog.Error("failed to restart after max attempts, giving up", "workload", runConfig.BaseName, "maxRetries", maxRetries) - statusErr = d.statuses.SetWorkloadStatus( - ctx, - runConfig.BaseName, - rt.WorkloadStatusError, - "Failed to restart after container exit", - ) - if statusErr != nil { - slog.Warn("failed to set workload status to error", "workload", runConfig.BaseName, "error", statusErr) - } + d.recordWorkloadRunFailure(ctx, runConfig.BaseName, "Failed to restart after container exit") return fmt.Errorf("container restart failed after %d attempts", maxRetries) } // Some other error - don't retry slog.Error("workload failed with error", "workload", runConfig.BaseName, "error", err) - if statusErr := d.statuses.SetWorkloadStatus(ctx, runConfig.BaseName, rt.WorkloadStatusError, err.Error()); statusErr != nil { - slog.Warn("Failed to set workload status to error", "workload", runConfig.BaseName, "error", statusErr) - } + d.recordWorkloadRunFailure(ctx, runConfig.BaseName, err.Error()) return err } @@ -648,6 +695,50 @@ func (d *DefaultManager) RunWorkload(ctx context.Context, runConfig *runner.RunC return fmt.Errorf("unexpected end of retry loop for %s", runConfig.BaseName) } +func (d *DefaultManager) finishWorkloadRun(ctx context.Context, name string, runErr error) error { + cleanupCtx, cancel := context.WithTimeout(context.Background(), workloadPIDCleanupTimeout) + defer cancel() + if err := d.statuses.ResetWorkloadPIDIfMatch(cleanupCtx, name, os.Getpid()); err != nil { + slog.Warn("failed to reset workload PID", "workload", name, "error", err) + } + if ctx.Err() != nil { + return nil + } + return runErr +} + +func (d *DefaultManager) recordWorkloadRunFailure(ctx context.Context, name, reason string) { + if ctx.Err() != nil { + return + } + if err := d.statuses.SetWorkloadStatus(ctx, name, rt.WorkloadStatusError, reason); err != nil { + slog.Warn("failed to set workload status to error", "workload", name, "error", err) + } +} + +// prepareWorkloadRestart removes stale client configuration and records that +// the workload is restarting, unless shutdown interrupted client cleanup. +func (d *DefaultManager) prepareWorkloadRestart(ctx context.Context, runConfig *runner.RunConfig, stable bool) { + clientManager, err := client.NewManager(ctx) + if err == nil { + slog.Debug("removing from client configurations before restart", "workload", runConfig.BaseName) + if err := clientManager.RemoveServerFromClients(ctx, runConfig.BaseName, runConfig.Group); err != nil { + slog.Warn("failed to remove from client config", "error", err) + } + } + if ctx.Err() != nil { + return + } + + statusReason := "Container exited, restarting" + if stable { + statusReason = "Container exited after stable run, restarting" + } + if err := d.statuses.SetWorkloadStatus(ctx, runConfig.BaseName, rt.WorkloadStatusStarting, statusReason); err != nil { + slog.Warn("failed to set workload status to starting", "workload", runConfig.BaseName, "error", err) + } +} + // validateSecretParameters validates the secret parameters for a workload. func (d *DefaultManager) validateSecretParameters(ctx context.Context, runConfig *runner.RunConfig) error { // If there are run secrets, validate them @@ -799,6 +890,13 @@ func (d *DefaultManager) spawnDetached(ctx context.Context, runConfig *runner.Ru return 0, err } + // A long-lived parent (thv serve) must reap its detached children too. + go func() { + if err := detachedCmd.Wait(); err != nil { + slog.Debug("detached proxy exited with error", "pid", detachedCmd.Process.Pid, "error", err) + } + }() + return detachedCmd.Process.Pid, nil } @@ -1016,39 +1114,57 @@ func (d *DefaultManager) isSupervisorProcessAlive(ctx context.Context, name stri } // stopProcess stops the proxy process associated with the container. It reports -// whether a tracked proxy process was actually stopped: true only when a valid -// PID was found and killed. A false return (no PID recorded, e.g. a missing -// status file, or the kill failed) signals callers to fall back to port-based -// cleanup so an orphaned proxy does not keep holding the workload's port. +// whether a verified proxy exited after termination. A false return signals +// callers to try port-based cleanup. Unverified PIDs are cleared only if the +// process is confirmed gone; otherwise they remain available for a later retry. func (d *DefaultManager) stopProcess(ctx context.Context, name string) bool { if name == "" { slog.Warn("could not find base container name in labels") return false } - // Try to read the PID and kill the process pid, err := d.statuses.GetWorkloadPID(ctx, name) - if err != nil { + if err != nil || pid <= 0 { slog.Debug("no PID found, proxy may not be running in detached mode", "workload", name) return false } - // PID found, try to kill the process - slog.Debug("stopping proxy process", "pid", pid) - stopped := false + // Foreground runs rely on the status entry for workload binding; detached + // supervisors additionally have a verifiable workload name in their command. + isToolHiveProxy, err := process.IsTrackedToolHiveProxyForWorkload(pid, name) + if err != nil || !isToolHiveProxy { + alive, findErr := process.FindProcess(pid) + if findErr != nil || alive { + slog.Warn("could not verify tracked proxy identity, preserving PID without signaling", + "workload", name, "pid", pid, "identityError", err, "error", findErr) + return false + } + slog.Debug("tracked proxy is gone, clearing PID", "workload", name, "pid", pid) + if err := d.statuses.ResetWorkloadPIDIfMatch(ctx, name, pid); err != nil { + slog.Warn("failed to reset workload PID", "workload", name, "error", err) + } + return false + } + + slog.Debug("stopping proxy process", "workload", name, "pid", pid) if err := process.KillProcess(pid); err != nil { slog.Debug("failed to kill proxy process", "error", err) - } else { - slog.Debug("proxy process stopped") - stopped = true + return false } - // Remove the PID of the terminated process - if err := d.statuses.ResetWorkloadPID(ctx, name); err != nil { + waitCtx, cancel := context.WithTimeout(ctx, d.proxyExitTimeoutOrDefault()) + defer cancel() + if err := process.WaitForExit(waitCtx, pid); err != nil { + slog.Warn("failed waiting for proxy process to exit", "workload", name, "pid", pid, "error", err) + return false + } + + slog.Debug("proxy process stopped", "workload", name, "pid", pid) + if err := d.statuses.ResetWorkloadPIDIfMatch(ctx, name, pid); err != nil { slog.Warn("failed to reset workload PID", "workload", name, "error", err) } - return stopped + return true } // stopProxyIfNeeded stops the proxy process if the workload has a base name. It @@ -1062,11 +1178,14 @@ func (d *DefaultManager) stopProxyIfNeeded(ctx context.Context, name, baseName s return d.stopProcess(ctx, baseName) } -// ensureProxyStopped stops the workload's proxy and guarantees its port is freed. +// ensureProxyStopped makes a best-effort attempt to stop the workload's proxy +// and free its port. // It first stops the tracked PID (stopProxyIfNeeded); if that does not stop a -// proxy — no PID is recorded (e.g. the status file is missing) or the kill fails -// (e.g. a stale PID whose process is already gone) — it falls back to port-based -// cleanup, which only kills a process verified to be this workload's own proxy. +// proxy — no PID is recorded, identity verification fails, or termination does +// not complete — it falls back to port-based cleanup, which only kills a process +// verified to be this workload's own proxy. +// On Unix, a timed-out wait can result in another SIGTERM via the fallback, but +// neither path escalates to SIGKILL. Windows uses hard TerminateProcess instead. // runConfig may be nil (no port fallback then). Used by the stop and delete // paths; the restart path instead frees the port itself, just before the child // re-binds. @@ -1083,7 +1202,7 @@ func (d *DefaultManager) ensureProxyStopped(ctx context.Context, name, baseName // "address already in use"), and // - stop/delete, as a fallback when PID-based termination is unavailable or // fails, so an orphaned proxy does not keep holding the port. -func (*DefaultManager) freePortHolderIfNeeded(ctx context.Context, runConfig *runner.RunConfig) { +func (d *DefaultManager) freePortHolderIfNeeded(ctx context.Context, runConfig *runner.RunConfig) { if runConfig == nil || runConfig.Port <= 0 { return } @@ -1126,7 +1245,7 @@ func (*DefaultManager) freePortHolderIfNeeded(ctx context.Context, runConfig *ru return } - waitCtx, cancel := context.WithTimeout(ctx, 5*time.Second) + waitCtx, cancel := context.WithTimeout(ctx, d.proxyExitTimeoutOrDefault()) defer cancel() if err := process.WaitForExit(waitCtx, portPID); err != nil { slog.Warn("timeout waiting for process to exit", "pid", portPID, "error", err) @@ -1652,8 +1771,9 @@ func (d *DefaultManager) stopSingleContainerWorkload( defer cancel() name := labels.GetContainerBaseName(workload.Labels) + isAuxiliary := labels.IsAuxiliaryWorkload(workload.Labels) // Stop the proxy process (skip for auxiliary workloads like inspector) - if labels.IsAuxiliaryWorkload(workload.Labels) { + if isAuxiliary { slog.Debug("skipping proxy stop for auxiliary workload", "workload", name) } else { d.ensureProxyStopped(ctx, name, name, runConfig) @@ -1661,14 +1781,24 @@ func (d *DefaultManager) stopSingleContainerWorkload( slog.Debug("stopping containers", "workload", name) // Stop the container - if err := d.runtime.StopWorkload(childCtx, workload.Name); err != nil { - if statusErr := d.statuses.SetWorkloadStatus(childCtx, name, rt.WorkloadStatusError, err.Error()); statusErr != nil { - slog.Warn("Failed to set workload status to error", "workload", name, "error", statusErr) + stopErr := d.runtime.StopWorkload(childCtx, workload.Name) + exists, err := savedWorkloadStillExists(childCtx, name, runConfig, isAuxiliary) + if err != nil { + return errors.Join(err, stopErr) + } + if stopErr != nil { + if exists { + if statusErr := d.statuses.SetWorkloadStatus(childCtx, name, rt.WorkloadStatusError, stopErr.Error()); statusErr != nil { + slog.Warn("Failed to set workload status to error", "workload", name, "error", statusErr) + } } - return fmt.Errorf("failed to stop container: %w", err) + return fmt.Errorf("failed to stop container: %w", stopErr) + } + if !exists { + return nil } - if err := removeClientConfigurations(name, labels.IsAuxiliaryWorkload(workload.Labels)); err != nil { + if err := removeClientConfigurations(name, isAuxiliary); err != nil { slog.Warn("failed to remove client configurations", "error", err) } else { slog.Debug("client configurations removed", "workload", name) diff --git a/pkg/workloads/manager_test.go b/pkg/workloads/manager_test.go index c828e0e6bb..6a160ea355 100644 --- a/pkg/workloads/manager_test.go +++ b/pkg/workloads/manager_test.go @@ -4,11 +4,18 @@ package workloads import ( + "bufio" "context" "errors" "fmt" + "maps" + "os" "os/exec" + "os/signal" + "path/filepath" goruntime "runtime" + "strings" + "syscall" "testing" "time" @@ -22,7 +29,10 @@ import ( "github.com/stacklok/toolhive/pkg/container/runtime" runtimeMocks "github.com/stacklok/toolhive/pkg/container/runtime/mocks" "github.com/stacklok/toolhive/pkg/core" + "github.com/stacklok/toolhive/pkg/labels" + "github.com/stacklok/toolhive/pkg/process" "github.com/stacklok/toolhive/pkg/runner" + "github.com/stacklok/toolhive/pkg/state" "github.com/stacklok/toolhive/pkg/transport/types" "github.com/stacklok/toolhive/pkg/vmcp" "github.com/stacklok/toolhive/pkg/workloads/statuses" @@ -955,7 +965,6 @@ func TestDefaultManager_restartLogicConsistency(t *testing.T) { statusMgr.EXPECT().GetWorkloadPID(gomock.Any(), "test-base").Return(0, nil) // stopProxyIfNeeded also calls GetWorkloadPID (via stopProcess) statusMgr.EXPECT().GetWorkloadPID(gomock.Any(), "test-base").Return(0, nil) - statusMgr.EXPECT().ResetWorkloadPID(gomock.Any(), "test-base").Return(nil) statusMgr.EXPECT().SetWorkloadStatus(gomock.Any(), "test-workload", runtime.WorkloadStatusStopping, "").Return(nil) statusMgr.EXPECT().SetWorkloadStatus(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).AnyTimes().Return(nil) statusMgr.EXPECT().SetWorkloadPID(gomock.Any(), gomock.Any(), gomock.Any()).AnyTimes().Return(nil) @@ -1083,7 +1092,6 @@ func TestDefaultManager_restartLogicConsistency(t *testing.T) { // When supervisor is treated as dead, expect stop logic statusMgr.EXPECT().SetWorkloadStatus(gomock.Any(), "test-workload", runtime.WorkloadStatusStopping, "").Return(nil) statusMgr.EXPECT().GetWorkloadPID(gomock.Any(), "test-workload").Return(0, nil) - statusMgr.EXPECT().ResetWorkloadPID(gomock.Any(), "test-workload").Return(nil) runtimeMgr.EXPECT().StopWorkload(gomock.Any(), "test-workload").Return(nil) statusMgr.EXPECT().SetWorkloadStatus(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).AnyTimes().Return(nil) @@ -1144,6 +1152,7 @@ func TestDefaultManager_RunWorkload(t *testing.T) { mockStatusMgr := statusMocks.NewMockStatusManager(ctrl) tt.setupMocks(mockStatusMgr) + expectSupervisorPIDCleanup(t, mockStatusMgr, tt.runConfig.BaseName) manager := &DefaultManager{ statuses: mockStatusMgr, @@ -1207,9 +1216,89 @@ func (f *fakeRunnerFactory) factory() mcpRunnerFactory { } } -func TestDefaultManager_RunWorkload_RetryCounterReset(t *testing.T) { +func expectSupervisorPIDCleanup(t *testing.T, sm *statusMocks.MockStatusManager, name string) { + t.Helper() + sm.EXPECT().ResetWorkloadPIDIfMatch(gomock.Any(), name, os.Getpid()). + DoAndReturn(func(ctx context.Context, _ string, _ int) error { + assert.NoError(t, ctx.Err(), "PID cleanup must survive supervisor cancellation") + _, bounded := ctx.Deadline() + assert.True(t, bounded, "PID cleanup must not wait indefinitely") + return nil + }) +} + +//nolint:paralleltest // client configuration isolation uses t.Setenv +func TestDefaultManager_RunWorkload_CancellationInterruptsBackoff(t *testing.T) { + isolateWorkloadStopState(t) + + ctrl := gomock.NewController(t) + sm := statusMocks.NewMockStatusManager(ctrl) + const name = "cancel-retrying-supervisor" + restarting := make(chan struct{}) + sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusStarting, "").Return(nil) + sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusStarting, "Container exited, restarting"). + DoAndReturn(func(context.Context, string, runtime.WorkloadStatus, string) error { + close(restarting) + return nil + }) + // No Error status write is allowed after a user requests shutdown. + expectSupervisorPIDCleanup(t, sm, name) + factory := &fakeRunnerFactory{outcomes: []fakeRunOutcome{{err: runner.ErrContainerExitedRestartNeeded}}} + manager := &DefaultManager{statuses: sm} + withRunnerFactory(factory.factory())(manager) + withRetryConfig(retryConfig{ + maxRetries: 3, initialDelay: 30 * time.Second, + maxBackoff: time.Minute, stableRunThreshold: time.Minute, + })(manager) + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + done := make(chan error, 1) + go func() { done <- manager.RunWorkload(ctx, &runner.RunConfig{BaseName: name}) }() + select { + case <-restarting: + case <-time.After(5 * time.Second): + t.Fatal("supervisor did not schedule its retry") + } + // The retry status is written just before entering backoff. Leave enough + // time to enter the wait rather than only testing cancellation before it. + select { + case err := <-done: + t.Fatalf("supervisor returned before cancellation: %v", err) + case <-time.After(100 * time.Millisecond): + } + cancel() + select { + case err := <-done: + require.NoError(t, err) + case <-time.After(2 * time.Second): + t.Fatal("cancellation did not interrupt retry backoff") + } + assert.Equal(t, 1, factory.callCount, "shutdown must not start another runner") +} + +func TestDefaultManager_RunWorkload_CancelledSupervisorClearsOnlyItsOwnPID(t *testing.T) { t.Parallel() + const name = "replaced-supervisor" + ctrl := gomock.NewController(t) + sm := statusMocks.NewMockStatusManager(ctrl) + // The guarded API must receive this supervisor's PID, never a replacement's + // PID read from storage or an unconditional reset. + expectSupervisorPIDCleanup(t, sm, name) + manager := &DefaultManager{statuses: sm} + withRunnerFactory(func(*runner.RunConfig, statuses.StatusManager) mcpRunner { + t.Error("cancelled supervisor must not create a runner") + return &fakeRunner{} + })(manager) + ctx, cancel := context.WithCancel(context.Background()) + cancel() + require.NoError(t, manager.RunWorkload(ctx, &runner.RunConfig{BaseName: name})) +} + +//nolint:paralleltest // client configuration isolation uses t.Setenv +func TestDefaultManager_RunWorkload_RetryCounterReset(t *testing.T) { + isolateWorkloadStopState(t) + // Test thresholds: short enough to keep the test fast, but with a wide // margin between "short" and "stable" run durations so scheduler jitter // on a busy CI host does not flip a "short" run to "stable". Production @@ -1283,8 +1372,6 @@ func TestDefaultManager_RunWorkload_RetryCounterReset(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - t.Parallel() - ctrl := gomock.NewController(t) defer ctrl.Finish() @@ -1294,6 +1381,7 @@ func TestDefaultManager_RunWorkload_RetryCounterReset(t *testing.T) { Return(nil). AnyTimes() + expectSupervisorPIDCleanup(t, mockStatusMgr, "retry-test") factory := &fakeRunnerFactory{outcomes: tt.outcomes} manager := &DefaultManager{statuses: mockStatusMgr} withRetryConfig(testCfg)(manager) @@ -1912,8 +2000,9 @@ func TestDefaultManager_UpdateWorkload(t *testing.T) { } } +//nolint:paralleltest // saved-workload fixtures use t.Setenv func TestDefaultManager_updateSingleWorkload(t *testing.T) { - t.Parallel() + isolateWorkloadStopState(t) // fakeSpawnerPID is the fake PID returned by the test-injected spawner. // It must be > 0 so SetWorkloadPID treats it as a real PID. @@ -1936,7 +2025,7 @@ func TestDefaultManager_updateSingleWorkload(t *testing.T) { name string workloadName string runConfig *runner.RunConfig - setupMocks func(*runtimeMocks.MockRuntime, *statusMocks.MockStatusManager) + setupMocks func(*testing.T, *runtimeMocks.MockRuntime, *statusMocks.MockStatusManager) expectError bool errorMsg string }{ @@ -1948,7 +2037,8 @@ func TestDefaultManager_updateSingleWorkload(t *testing.T) { BaseName: "test-workload", Group: "default", }, - setupMocks: func(rt *runtimeMocks.MockRuntime, sm *statusMocks.MockStatusManager) { + setupMocks: func(t *testing.T, rt *runtimeMocks.MockRuntime, sm *statusMocks.MockStatusManager) { + t.Helper() // Mock the stop operation - return error for GetWorkloadInfo rt.EXPECT().GetWorkloadInfo(gomock.Any(), "test-workload"). Return(runtime.ContainerInfo{}, errors.New("container lookup failed")).AnyTimes() @@ -1967,7 +2057,8 @@ func TestDefaultManager_updateSingleWorkload(t *testing.T) { BaseName: "test-workload", Group: "default", }, - setupMocks: func(rt *runtimeMocks.MockRuntime, sm *statusMocks.MockStatusManager) { + setupMocks: func(t *testing.T, rt *runtimeMocks.MockRuntime, sm *statusMocks.MockStatusManager) { + t.Helper() // Mock stop operation - workload exists and can be stopped rt.EXPECT().GetWorkloadInfo(gomock.Any(), "test-workload"). Return(runtime.ContainerInfo{ @@ -1975,10 +2066,11 @@ func TestDefaultManager_updateSingleWorkload(t *testing.T) { State: "running", Labels: map[string]string{"toolhive-basename": "test-workload"}, }, nil) - // Mock GetWorkloadPID call from stopProcess - sm.EXPECT().GetWorkloadPID(gomock.Any(), "test-workload").Return(1234, nil) + // Stop only an owned proxy child, never an arbitrary host PID. + pid := startVerifiedProxyProcess(t, "test-workload").pid + sm.EXPECT().GetWorkloadPID(gomock.Any(), "test-workload").Return(pid, nil) rt.EXPECT().StopWorkload(gomock.Any(), "test-workload").Return(nil) - sm.EXPECT().ResetWorkloadPID(gomock.Any(), "test-workload").Return(nil) + sm.EXPECT().ResetWorkloadPIDIfMatch(gomock.Any(), "test-workload", pid).Return(nil) // Mock delete operation - workload exists and can be deleted rt.EXPECT().GetWorkloadInfo(gomock.Any(), "test-workload"). @@ -2009,7 +2101,8 @@ func TestDefaultManager_updateSingleWorkload(t *testing.T) { BaseName: "test-workload", Group: "default", }, - setupMocks: func(rt *runtimeMocks.MockRuntime, sm *statusMocks.MockStatusManager) { + setupMocks: func(t *testing.T, rt *runtimeMocks.MockRuntime, sm *statusMocks.MockStatusManager) { + t.Helper() // Mock successful stop rt.EXPECT().GetWorkloadInfo(gomock.Any(), "test-workload"). Return(runtime.ContainerInfo{ @@ -2017,10 +2110,11 @@ func TestDefaultManager_updateSingleWorkload(t *testing.T) { State: "running", Labels: map[string]string{"toolhive-basename": "test-workload"}, }, nil) - // Mock GetWorkloadPID call from stopProcess - sm.EXPECT().GetWorkloadPID(gomock.Any(), "test-workload").Return(1234, nil) + // Stop only an owned proxy child, never an arbitrary host PID. + pid := startVerifiedProxyProcess(t, "test-workload").pid + sm.EXPECT().GetWorkloadPID(gomock.Any(), "test-workload").Return(pid, nil) rt.EXPECT().StopWorkload(gomock.Any(), "test-workload").Return(nil) - sm.EXPECT().ResetWorkloadPID(gomock.Any(), "test-workload").Return(nil) + sm.EXPECT().ResetWorkloadPIDIfMatch(gomock.Any(), "test-workload", pid).Return(nil) // Mock failed delete rt.EXPECT().GetWorkloadInfo(gomock.Any(), "test-workload"). @@ -2040,7 +2134,6 @@ func TestDefaultManager_updateSingleWorkload(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - t.Parallel() ctx := context.Background() ctrl := gomock.NewController(t) @@ -2051,7 +2144,7 @@ func TestDefaultManager_updateSingleWorkload(t *testing.T) { mockConfigProvider := configMocks.NewMockProvider(ctrl) if tt.setupMocks != nil { - tt.setupMocks(mockRuntime, mockStatusManager) + tt.setupMocks(t, mockRuntime, mockStatusManager) } manager := &DefaultManager{ @@ -2064,6 +2157,7 @@ func TestDefaultManager_updateSingleWorkload(t *testing.T) { // process that recursively reruns the entire test suite. See #5344. withDetachedSpawner(noopSpawnerFor(mockStatusManager))(manager) + persistStopRunConfig(t, tt.workloadName, tt.runConfig) err := manager.updateSingleWorkload(ctx, tt.workloadName, tt.runConfig) if tt.expectError { @@ -2113,6 +2207,8 @@ func TestDefaultManager_RunWorkload_ContainerExitHandling(t *testing.T) { Group: "default", } + expectSupervisorPIDCleanup(t, mockStatusMgr, runConfig.BaseName) + // RunWorkload will fail because the runner can't actually run // This tests that the status is properly set err := manager.RunWorkload(context.Background(), runConfig) @@ -2264,11 +2360,11 @@ func TestGetRemoteWorkloadsFromState_AuthRetryingVisibleWithoutAll(t *testing.T) } // startKillableProcess starts a real, long-lived child process and returns its -// PID. The process is killed and reaped on test cleanup. It is used to exercise -// the path where stopProcess finds a valid PID and KillProcess succeeds. The +// PID and an exit notification. The process is killed and reaped on test cleanup. It represents an +// unrelated process that must not be killed as a proxy. The // helper relies on the Unix `sleep` command, so it skips on Windows (the CI unit // test matrix is Linux-only) and if the process cannot be started. -func startKillableProcess(t *testing.T) int { +func startKillableProcess(t *testing.T) (int, <-chan struct{}) { t.Helper() if goruntime.GOOS == "windows" { t.Skip("startKillableProcess relies on the Unix sleep command") @@ -2277,17 +2373,509 @@ func startKillableProcess(t *testing.T) int { if err := cmd.Start(); err != nil { t.Skipf("could not start helper process: %v", err) } + exited := make(chan struct{}) + go func() { + _ = cmd.Wait() + close(exited) + }() t.Cleanup(func() { _ = cmd.Process.Kill() - _ = cmd.Wait() + select { + case <-exited: + case <-time.After(5 * time.Second): + t.Error("unrelated helper process was not reaped") + } + }) + return cmd.Process.Pid, exited +} + +func isolateWorkloadStopState(t *testing.T) { + t.Helper() + t.Cleanup(xdg.Reload) + t.Setenv("XDG_STATE_HOME", t.TempDir()) + t.Setenv("XDG_DATA_HOME", t.TempDir()) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + // NewManager fails before runtime auto-detection or client discovery. XDG + // isolation alone is insufficient: DefaultProvider caches registered clients + // in a singleton, so also seed an empty config rather than reuse a prior load. + t.Setenv("TOOLHIVE_RUNTIME", "disabled-for-test") + xdg.Reload() + config.SetSingletonConfig(&config.Config{}) + t.Cleanup(config.ResetSingleton) +} + +func persistStopRunConfig(t *testing.T, name string, rc *runner.RunConfig) { + t.Helper() + copied := *rc + copied.SchemaVersion = runner.CurrentSchemaVersion + if copied.BaseName == "" { + copied.BaseName = name + } + require.NoError(t, copied.SaveState(context.Background())) +} + +type workloadProxyProcess struct { + pid int + exited chan struct{} + waitErr error // Read only after exited is closed by the Wait goroutine. +} + +func TestWorkloadProxyProcess(t *testing.T) { + t.Parallel() + + mode := os.Getenv("TOOLHIVE_TEST_PROXY_HELPER") + if mode == "" { + return + } + terminated := make(chan os.Signal, 1) + if mode == "ignore-term" { + signal.Ignore(syscall.SIGTERM) + } else { + signal.Notify(terminated, syscall.SIGTERM) + } + fmt.Println("ready") + select { + case <-terminated: + os.Exit(0) + case <-time.After(time.Minute): + os.Exit(1) + } +} + +func startVerifiedProxyProcess(t *testing.T, name string, args ...string) *workloadProxyProcess { + t.Helper() + return startProxyProcess(t, name, false, args...) +} + +func startProxyProcess(t *testing.T, name string, ignoreSIGTERM bool, args ...string) *workloadProxyProcess { + t.Helper() + if goruntime.GOOS == "windows" { + t.Skip("proxy helper requires SIGTERM") + } + executable, err := os.Executable() + require.NoError(t, err) + detached := len(args) == 0 + if detached { + args = []string{"start", name, "--foreground"} + } else { + thv := filepath.Join(t.TempDir(), "thv") + require.NoError(t, os.Symlink(executable, thv)) + executable = thv + } + cmd := exec.Command(executable, append([]string{"-test.run=^TestWorkloadProxyProcess$", "--"}, args...)...) + for _, entry := range os.Environ() { + if !strings.HasPrefix(entry, "TOOLHIVE_DETACHED=") { + cmd.Env = append(cmd.Env, entry) + } + } + mode := "1" + if ignoreSIGTERM { + mode = "ignore-term" + } + cmd.Env = append(cmd.Env, "TOOLHIVE_TEST_PROXY_HELPER="+mode) + if detached { + cmd.Env = append(cmd.Env, "TOOLHIVE_DETACHED=1") + } + stdout, err := cmd.StdoutPipe() + require.NoError(t, err) + require.NoError(t, cmd.Start()) + proxy := &workloadProxyProcess{pid: cmd.Process.Pid, exited: make(chan struct{})} + ready := make(chan string, 1) + go func() { + line, _ := bufio.NewReader(stdout).ReadString('\n') + ready <- line + }() + go func() { + proxy.waitErr = cmd.Wait() + close(proxy.exited) + }() + t.Cleanup(func() { + _ = cmd.Process.Kill() + select { + case <-proxy.exited: + case <-time.After(5 * time.Second): + t.Error("proxy helper was not reaped") + } }) - return cmd.Process.Pid + select { + case line := <-ready: + require.Equal(t, "ready\n", line) + case <-time.After(5 * time.Second): + t.Fatal("proxy helper did not start") + } + verified, err := process.IsToolHiveProxyForWorkload(proxy.pid, name) + require.NoError(t, err) + require.True(t, verified, "helper must satisfy production proxy identity checks") + return proxy +} + +//nolint:paralleltest // t.Setenv is incompatible with t.Parallel +func TestDefaultManager_stopContainerWorkload_ExitedContainerWaitsForTrackedProxy(t *testing.T) { + isolateWorkloadStopState(t) + + for _, tt := range []struct { + name string + startProxy func(*testing.T) *workloadProxyProcess + }{ + { + name: "detached start uses workload base name", + startProxy: func(t *testing.T) *workloadProxyProcess { + t.Helper() + return startVerifiedProxyProcess(t, "requested-container") + }, + }, + { + name: "foreground run without detached environment uses thv binary identity", + startProxy: func(t *testing.T) *workloadProxyProcess { + t.Helper() + return startVerifiedProxyProcess(t, "", "run", "--foreground", "example/server") + }, + }, + } { + t.Run(tt.name, func(t *testing.T) { + proxy := tt.startProxy(t) + ctrl := gomock.NewController(t) + sm := statusMocks.NewMockStatusManager(ctrl) + rtMock := runtimeMocks.NewMockRuntime(ctrl) + rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), "requested-container").Return(runtime.ContainerInfo{ + Name: "requested-container-1730000000", State: "exited", + Labels: map[string]string{labels.LabelBaseName: "requested-container"}, + }, nil) + sm.EXPECT().SetWorkloadStatus(gomock.Any(), "requested-container", runtime.WorkloadStatusStopping, "").Return(nil) + sm.EXPECT().GetWorkloadPID(gomock.Any(), "requested-container").Return(proxy.pid, nil) + sm.EXPECT().ResetWorkloadPIDIfMatch(gomock.Any(), "requested-container", proxy.pid).Return(nil) + rtMock.EXPECT().StopWorkload(gomock.Any(), "requested-container-1730000000").DoAndReturn(func(context.Context, string) error { + select { + case <-proxy.exited: + assert.NoError(t, proxy.waitErr, "proxy must handle SIGTERM before runtime stop") + default: + t.Error("runtime stop called before tracked proxy exited") + } + return nil + }) + sm.EXPECT().SetWorkloadStatus(gomock.Any(), "requested-container", runtime.WorkloadStatusStopped, "").Return(nil) + manager := &DefaultManager{statuses: sm, runtime: rtMock} + withPortFreer(func(context.Context, *runner.RunConfig) { + t.Error("verified proxy exit must not require port fallback") + })(manager) + + rc := &runner.RunConfig{BaseName: "requested-container", ContainerName: "requested-container-1730000000"} + persistStopRunConfig(t, "requested-container", rc) + require.NoError(t, manager.stopContainerWorkload(context.Background(), "requested-container", rc)) + }) + } +} + +//nolint:paralleltest // t.Setenv is incompatible with t.Parallel +func TestDefaultManager_stopContainerWorkload_MissingContainerUsesSavedLabels(t *testing.T) { + isolateWorkloadStopState(t) + + for _, tt := range []struct { + name string + runConfig *runner.RunConfig + wantContainerName string + }{ + { + name: "saved base fills missing label without mutating config", + runConfig: &runner.RunConfig{ + BaseName: "requested-container", + ContainerName: "requested-container-1730000000", + ContainerLabels: map[string]string{"custom-label": "preserved"}, + }, + wantContainerName: "requested-container-1730000000", + }, + { + name: "saved base label is preserved without mutating config", + runConfig: &runner.RunConfig{ + BaseName: "requested-container", + ContainerName: "requested-container-1730000000", + ContainerLabels: map[string]string{labels.LabelBaseName: "requested-container"}, + }, + wantContainerName: "requested-container-1730000000", + }, + { + name: "missing saved container name falls back to workload base", + runConfig: &runner.RunConfig{BaseName: "requested-container"}, + wantContainerName: "requested-container", + }, + } { + t.Run(tt.name, func(t *testing.T) { + persistStopRunConfig(t, "requested-container", tt.runConfig) + original := *tt.runConfig + original.ContainerLabels = maps.Clone(tt.runConfig.ContainerLabels) + ctrl := gomock.NewController(t) + sm := statusMocks.NewMockStatusManager(ctrl) + rtMock := runtimeMocks.NewMockRuntime(ctrl) + rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), "requested-container").Return(runtime.ContainerInfo{}, + fmt.Errorf("inspect: %w", runtime.ErrWorkloadNotFound)) + sm.EXPECT().SetWorkloadStatus(gomock.Any(), "requested-container", runtime.WorkloadStatusStopping, "").Return(nil) + sm.EXPECT().GetWorkloadPID(gomock.Any(), "requested-container").Return(0, runtime.ErrWorkloadNotFound) + fallbackCalls := 0 + rtMock.EXPECT().StopWorkload(gomock.Any(), tt.wantContainerName).DoAndReturn(func(context.Context, string) error { + assert.Equal(t, 1, fallbackCalls, "proxy cleanup must precede the fresh runtime stop") + return nil + }) + sm.EXPECT().SetWorkloadStatus(gomock.Any(), "requested-container", runtime.WorkloadStatusStopped, "").Return(nil) + manager := &DefaultManager{statuses: sm, runtime: rtMock} + withPortFreer(func(_ context.Context, rc *runner.RunConfig) { + assert.Same(t, tt.runConfig, rc) + fallbackCalls++ + })(manager) + + require.NoError(t, manager.stopContainerWorkload(context.Background(), "requested-container", tt.runConfig)) + assert.Equal(t, &original, tt.runConfig) + }) + } +} + +func TestDefaultManager_stopContainerWorkload_MissingConfigStopsTrackedProxyWithoutStatusWrites(t *testing.T) { + t.Parallel() + + const name = "missing-container" + proxy := startVerifiedProxyProcess(t, name) + ctrl := gomock.NewController(t) + sm := statusMocks.NewMockStatusManager(ctrl) + rtMock := runtimeMocks.NewMockRuntime(ctrl) + rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), name).Return(runtime.ContainerInfo{}, runtime.ErrWorkloadNotFound) + sm.EXPECT().GetWorkloadPID(gomock.Any(), name).Return(proxy.pid, nil) + sm.EXPECT().ResetWorkloadPIDIfMatch(gomock.Any(), name, proxy.pid).Return(nil) + rtMock.EXPECT().StopWorkload(gomock.Any(), name).DoAndReturn(func(context.Context, string) error { + select { + case <-proxy.exited: + assert.NoError(t, proxy.waitErr) + default: + t.Error("runtime stop called before tracked proxy exited") + } + return nil + }) + manager := &DefaultManager{statuses: sm, runtime: rtMock} + + require.NoError(t, manager.stopContainerWorkload(context.Background(), name, nil)) +} + +func TestDefaultManager_stopContainerWorkload_InspectionFailureDoesNotStopProxy(t *testing.T) { + t.Parallel() + + ctrl := gomock.NewController(t) + sm := statusMocks.NewMockStatusManager(ctrl) + rtMock := runtimeMocks.NewMockRuntime(ctrl) + inspectErr := errors.New("runtime inspection failed") + rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), "container").Return(runtime.ContainerInfo{}, inspectErr) + manager := &DefaultManager{statuses: sm, runtime: rtMock} + + require.ErrorIs(t, manager.stopContainerWorkload(context.Background(), "container", + &runner.RunConfig{BaseName: "saved-base"}), inspectErr) +} + +//nolint:paralleltest // saved-workload fixtures use t.Setenv +func TestDefaultManager_stopContainerWorkload_RuntimeStopFailureRecordsErrorAfterProxyCleanup(t *testing.T) { + isolateWorkloadStopState(t) + + ctrl := gomock.NewController(t) + sm := statusMocks.NewMockStatusManager(ctrl) + rtMock := runtimeMocks.NewMockRuntime(ctrl) + stopErr := errors.New("runtime stop failed") + rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), "container").Return(runtime.ContainerInfo{}, runtime.ErrWorkloadNotFound) + sm.EXPECT().SetWorkloadStatus(gomock.Any(), "container", runtime.WorkloadStatusStopping, "").Return(nil) + sm.EXPECT().GetWorkloadPID(gomock.Any(), "container").Return(0, runtime.ErrWorkloadNotFound) + cleanupComplete := false + rtMock.EXPECT().StopWorkload(gomock.Any(), "container").DoAndReturn(func(context.Context, string) error { + assert.True(t, cleanupComplete, "runtime stop must follow proxy cleanup even on failure") + return stopErr + }) + sm.EXPECT().SetWorkloadStatus(gomock.Any(), "container", runtime.WorkloadStatusError, stopErr.Error()).Return(nil) + manager := &DefaultManager{statuses: sm, runtime: rtMock} + withPortFreer(func(context.Context, *runner.RunConfig) { cleanupComplete = true })(manager) + + rc := &runner.RunConfig{BaseName: "container"} + persistStopRunConfig(t, "container", rc) + require.ErrorIs(t, manager.stopContainerWorkload(context.Background(), "container", rc), stopErr) +} + +func TestDefaultManager_stopContainerWorkload_MissingConfigPropagatesRuntimeStopFailure(t *testing.T) { + t.Parallel() + + ctrl := gomock.NewController(t) + sm := statusMocks.NewMockStatusManager(ctrl) + rtMock := runtimeMocks.NewMockRuntime(ctrl) + stopErr := errors.New("runtime stop failed") + rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), "container").Return(runtime.ContainerInfo{}, runtime.ErrWorkloadNotFound) + sm.EXPECT().GetWorkloadPID(gomock.Any(), "container").Return(0, runtime.ErrWorkloadNotFound) + rtMock.EXPECT().StopWorkload(gomock.Any(), "container").Return(stopErr) + manager := &DefaultManager{statuses: sm, runtime: rtMock} + + require.ErrorIs(t, manager.stopContainerWorkload(context.Background(), "container", nil), stopErr) +} + +//nolint:paralleltest // t.Setenv is incompatible with t.Parallel +func TestDefaultManager_StopWorkloads_MissingContainerStopsSavedContainerNameAndPreservesConfig(t *testing.T) { + isolateWorkloadStopState(t) + + ctx := context.Background() + const name = "missing-container" + runConfig := &runner.RunConfig{ + SchemaVersion: runner.CurrentSchemaVersion, + Name: "saved-container-name", + ContainerName: "saved-container-name-1730000000", + BaseName: name, + ContainerLabels: map[string]string{"custom-label": "preserved"}, + Transport: types.TransportTypeStreamableHTTP, + Group: "default", + } + require.NoError(t, runConfig.SaveState(ctx)) + before, err := runner.LoadState(ctx, name) + require.NoError(t, err) + + ctrl := gomock.NewController(t) + sm := statusMocks.NewMockStatusManager(ctrl) + rtMock := runtimeMocks.NewMockRuntime(ctrl) + rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), name).Return(runtime.ContainerInfo{}, runtime.ErrWorkloadNotFound) + sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusStopping, "").Return(nil) + sm.EXPECT().GetWorkloadPID(gomock.Any(), name).Return(0, runtime.ErrWorkloadNotFound) + sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusStopped, "").Return(nil) + cleanupComplete := false + rtMock.EXPECT().StopWorkload(gomock.Any(), runConfig.ContainerName).DoAndReturn(func(context.Context, string) error { + assert.True(t, cleanupComplete) + return nil + }) + manager := &DefaultManager{statuses: sm, runtime: rtMock} + withPortFreer(func(_ context.Context, rc *runner.RunConfig) { + assert.Equal(t, before, rc) + cleanupComplete = true + })(manager) + + complete, err := manager.StopWorkloads(ctx, []string{name}) + require.NoError(t, err) + require.NoError(t, complete()) + after, err := runner.LoadState(ctx, name) + require.NoError(t, err) + assert.Equal(t, before, after) +} + +//nolint:paralleltest // saved-workload fixtures use t.Setenv +func TestDefaultManager_StopWorkload_ForegroundDeletionIsNotResurrected(t *testing.T) { + isolateWorkloadStopState(t) + + for _, kind := range []string{"container", "remote"} { + remote := kind == "remote" + t.Run(kind, func(t *testing.T) { + ctx := context.Background() + name := "deleted-foreground-" + kind + rc := &runner.RunConfig{BaseName: name, ContainerName: name} + if remote { + rc.RemoteURL = "https://example.com/mcp" + } + persistStopRunConfig(t, name, rc) + store, err := state.NewRunConfigStore(state.DefaultAppName) + require.NoError(t, err) + ctrl := gomock.NewController(t) + rtMock := runtimeMocks.NewMockRuntime(ctrl) + fileStatuses, err := statuses.NewFileStatusManager(rtMock) + require.NoError(t, err) + require.NoError(t, fileStatuses.SetWorkloadStatus(ctx, name, runtime.WorkloadStatusRunning, "")) + proxy := startVerifiedProxyProcess(t, "", "run", "--foreground", "example/server") + require.NoError(t, fileStatuses.SetWorkloadPID(ctx, name, proxy.pid)) + statusPath := filepath.Join(xdg.DataHome, "toolhive", "statuses", name+".json") + sm := statusMocks.NewMockStatusManager(ctrl) + if remote { + sm.EXPECT().GetWorkload(gomock.Any(), name).Return(core.Workload{ + Name: name, Status: runtime.WorkloadStatusRunning, + }, nil) + } else { + rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), name).Return(runtime.ContainerInfo{ + Name: name, State: "exited", Labels: map[string]string{labels.LabelBaseName: name}, + }, nil) + rtMock.EXPECT().StopWorkload(gomock.Any(), name).DoAndReturn(func(context.Context, string) error { + select { + case <-proxy.exited: + assert.NoError(t, proxy.waitErr) + default: + t.Error("runtime stop preceded foreground supervisor exit") + } + return nil + }) + } + // Only Stopping is permitted: neither path may write Stopped after deletion. + sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusStopping, ""). + DoAndReturn(fileStatuses.SetWorkloadStatus) + sm.EXPECT().GetWorkloadPID(gomock.Any(), name). + DoAndReturn(func(ctx context.Context, name string) (int, error) { + pid, err := fileStatuses.GetWorkloadPID(ctx, name) + require.NoError(t, err) + // Model the owner deleting both files before exit, not during the + // later runtime stop. PID reset must tolerate the deleted status. + require.NoError(t, store.Delete(ctx, name)) + require.NoError(t, fileStatuses.DeleteWorkloadStatus(ctx, name)) + return pid, nil + }) + sm.EXPECT().ResetWorkloadPIDIfMatch(gomock.Any(), name, proxy.pid). + DoAndReturn(func(ctx context.Context, name string, pid int) error { + _, err := os.Stat(statusPath) + require.ErrorIs(t, err, os.ErrNotExist, "owner deletion must precede guarded PID reset") + return fileStatuses.ResetWorkloadPIDIfMatch(ctx, name, pid) + }) + manager := &DefaultManager{runtime: rtMock, statuses: sm} + withPortFreer(func(context.Context, *runner.RunConfig) { + t.Error("foreground exit must not require port fallback") + })(manager) + + if remote { + require.NoError(t, manager.stopRemoteWorkload(ctx, name, rc)) + } else { + require.NoError(t, manager.stopContainerWorkload(ctx, name, rc)) + } + exists, err := store.Exists(ctx, name) + require.NoError(t, err) + assert.False(t, exists, "stop must not recreate a deleted foreground run config") + _, err = os.Stat(statusPath) + assert.ErrorIs(t, err, os.ErrNotExist, "stop must not recreate status after foreground deletion") + }) + } +} + +//nolint:paralleltest // saved-workload fixtures use t.Setenv +func TestDefaultManager_stopRemoteWorkload_LiveProxyStatusesEndStopped(t *testing.T) { + isolateWorkloadStopState(t) + for _, status := range []runtime.WorkloadStatus{ + runtime.WorkloadStatusStarting, + runtime.WorkloadStatusAuthRetrying, + runtime.WorkloadStatusUnauthenticated, + runtime.WorkloadStatusUnhealthy, + } { + t.Run(string(status), func(t *testing.T) { + const name = "remote-retry-backoff" + rc := &runner.RunConfig{BaseName: name, RemoteURL: "https://example.com/mcp"} + persistStopRunConfig(t, name, rc) + proxy := startVerifiedProxyProcess(t, name) + ctrl := gomock.NewController(t) + sm := statusMocks.NewMockStatusManager(ctrl) + gomock.InOrder( + sm.EXPECT().GetWorkload(gomock.Any(), name).Return(core.Workload{ + Name: name, Status: status, + }, nil), + sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusStopping, "").Return(nil), + sm.EXPECT().GetWorkloadPID(gomock.Any(), name).Return(proxy.pid, nil), + sm.EXPECT().ResetWorkloadPIDIfMatch(gomock.Any(), name, proxy.pid).Return(nil), + sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusStopped, "").Return(nil), + ) + manager := &DefaultManager{statuses: sm} + withPortFreer(func(context.Context, *runner.RunConfig) { t.Error("tracked supervisor exit must not need fallback") })(manager) + + require.NoError(t, manager.stopRemoteWorkload(context.Background(), name, rc)) + select { + case <-proxy.exited: + assert.NoError(t, proxy.waitErr) + default: + t.Error("remote stop returned while supervisor was still alive") + } + }) + } } // TestDefaultManager_stopProcess verifies the boolean contract that the // stop/delete port-cleanup fallback relies on: stopProcess reports true only -// when it found a tracked PID and killed it. A false return (no PID recorded — -// e.g. a missing status file — or a failed kill) is what triggers the +// when a tracked, identity-verified proxy exits. A false return (no PID recorded — +// e.g. a missing status file — or an unverified PID) is what triggers the // port-based cleanup fallback in stopSingleContainerWorkload/deleteContainerWorkload. func TestDefaultManager_stopProcess(t *testing.T) { t.Parallel() @@ -2318,21 +2906,20 @@ func TestDefaultManager_stopProcess(t *testing.T) { name: "missing status file (pid 0) returns false", workload: "test-workload", setupMocks: func(_ *testing.T, sm *statusMocks.MockStatusManager) { - // A missing status file yields PID 0 with no error; KillProcess(0) fails, - // so no proxy is stopped. The PID is still reset. + // A missing status file yields PID 0 with no error; identity validation + // rejects it without a PID update. sm.EXPECT().GetWorkloadPID(gomock.Any(), "test-workload").Return(0, nil) - sm.EXPECT().ResetWorkloadPID(gomock.Any(), "test-workload").Return(nil) }, want: false, }, { - name: "valid running PID returns true", + name: "verified proxy exits and returns true", workload: "test-workload", setupMocks: func(t *testing.T, sm *statusMocks.MockStatusManager) { t.Helper() - pid := startKillableProcess(t) + pid := startVerifiedProxyProcess(t, "test-workload").pid sm.EXPECT().GetWorkloadPID(gomock.Any(), "test-workload").Return(pid, nil) - sm.EXPECT().ResetWorkloadPID(gomock.Any(), "test-workload").Return(nil) + sm.EXPECT().ResetWorkloadPIDIfMatch(gomock.Any(), "test-workload", pid).Return(nil) }, want: true, }, @@ -2356,14 +2943,90 @@ func TestDefaultManager_stopProcess(t *testing.T) { } } +func TestDefaultManager_ensureProxyStopped_UnverifiedLivePIDIsPreservedWithoutSignaling(t *testing.T) { + t.Parallel() + + for _, tt := range []struct { + name string + start func(*testing.T) (int, <-chan struct{}) + }{ + {name: "unrelated executable", start: startKillableProcess}, + {name: "detached supervisor of hyphen-suffixed workload", start: func(t *testing.T) (int, <-chan struct{}) { + t.Helper() + proxy := startVerifiedProxyProcess(t, "github-extra") + return proxy.pid, proxy.exited + }}, + } { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + const name = "github" + pid, exited := tt.start(t) + ctrl := gomock.NewController(t) + sm := statusMocks.NewMockStatusManager(ctrl) + sm.EXPECT().GetWorkloadPID(gomock.Any(), name).Return(pid, nil) + // No reset expectation: an unverifiable live process must remain tracked. + manager := &DefaultManager{statuses: sm} + rc := &runner.RunConfig{BaseName: name, Port: 54321} + fallbackCalls := 0 + withPortFreer(func(_ context.Context, got *runner.RunConfig) { + assert.Same(t, rc, got) + fallbackCalls++ + })(manager) + + manager.ensureProxyStopped(context.Background(), name, name, rc) + assert.Equal(t, 1, fallbackCalls, "unverified PID must not suppress port cleanup") + select { + case <-exited: + t.Error("unverified live process was terminated") + case <-time.After(100 * time.Millisecond): + } + }) + } +} + +func TestDefaultManager_ensureProxyStopped_ExitTimeoutPreservesVerifiedPIDAndFallsBackOnce(t *testing.T) { + t.Parallel() + + const name = "slow-shutdown-supervisor" + proxy := startProxyProcess(t, name, true) + ctrl := gomock.NewController(t) + sm := statusMocks.NewMockStatusManager(ctrl) + sm.EXPECT().GetWorkloadPID(gomock.Any(), name).Return(proxy.pid, nil) + // No reset expectation: timeout must not drop the only supervisor handle. + manager := &DefaultManager{statuses: sm} + withProxyExitTimeout(100 * time.Millisecond)(manager) + runConfig := &runner.RunConfig{BaseName: name, Port: 54321} + fallbackCalls := 0 + withPortFreer(func(_ context.Context, rc *runner.RunConfig) { + assert.Same(t, runConfig, rc) + fallbackCalls++ + })(manager) + + manager.ensureProxyStopped(context.Background(), name, name, runConfig) + assert.Equal(t, 1, fallbackCalls, "verified timeout must run port fallback once") + select { + case <-proxy.exited: + t.Error("SIGTERM-ignoring proxy unexpectedly exited") + default: + } +} + // TestDefaultManager_orphanProxyPortCleanup verifies that stop and rm fall back // to port-based proxy cleanup when the tracked PID is unavailable (the missing // status-file scenario), and that the fallback does not run on the normal path // where the proxy was stopped by PID. +// +//nolint:paralleltest // saved-workload fixtures use t.Setenv func TestDefaultManager_orphanProxyPortCleanup(t *testing.T) { - t.Parallel() + isolateWorkloadStopState(t) const workloadName = "test-workload" + savedRunConfig := func(t *testing.T) *runner.RunConfig { + t.Helper() + rc := &runner.RunConfig{BaseName: workloadName, Port: 54321} + persistStopRunConfig(t, workloadName, rc) + return rc + } containerInfo := func() runtime.ContainerInfo { return runtime.ContainerInfo{ Name: workloadName, @@ -2373,7 +3036,6 @@ func TestDefaultManager_orphanProxyPortCleanup(t *testing.T) { } t.Run("stop frees orphan proxy port when status file missing", func(t *testing.T) { - t.Parallel() ctrl := gomock.NewController(t) defer ctrl.Finish() @@ -2383,12 +3045,12 @@ func TestDefaultManager_orphanProxyPortCleanup(t *testing.T) { // Missing status file: no tracked PID, so the proxy is not killed by PID. sm.EXPECT().GetWorkloadPID(gomock.Any(), workloadName).Return(0, nil) - sm.EXPECT().ResetWorkloadPID(gomock.Any(), workloadName).Return(nil) rtMock.EXPECT().StopWorkload(gomock.Any(), workloadName).Return(nil) sm.EXPECT().SetWorkloadStatus(gomock.Any(), workloadName, runtime.WorkloadStatusStopped, "").Return(nil) var freed []*runner.RunConfig runConfig := &runner.RunConfig{BaseName: workloadName, Port: 54321} + persistStopRunConfig(t, workloadName, runConfig) manager := &DefaultManager{statuses: sm, runtime: rtMock} withPortFreer(func(_ context.Context, rc *runner.RunConfig) { freed = append(freed, rc) @@ -2404,7 +3066,6 @@ func TestDefaultManager_orphanProxyPortCleanup(t *testing.T) { }) t.Run("stop does not free port on normal shutdown", func(t *testing.T) { - t.Parallel() ctrl := gomock.NewController(t) defer ctrl.Finish() @@ -2413,9 +3074,9 @@ func TestDefaultManager_orphanProxyPortCleanup(t *testing.T) { rtMock := runtimeMocks.NewMockRuntime(ctrl) // A valid, killable PID: the proxy is stopped by PID, so no fallback. - pid := startKillableProcess(t) + pid := startVerifiedProxyProcess(t, workloadName).pid sm.EXPECT().GetWorkloadPID(gomock.Any(), workloadName).Return(pid, nil) - sm.EXPECT().ResetWorkloadPID(gomock.Any(), workloadName).Return(nil) + sm.EXPECT().ResetWorkloadPIDIfMatch(gomock.Any(), workloadName, pid).Return(nil) rtMock.EXPECT().StopWorkload(gomock.Any(), workloadName).Return(nil) sm.EXPECT().SetWorkloadStatus(gomock.Any(), workloadName, runtime.WorkloadStatusStopped, "").Return(nil) @@ -2427,7 +3088,7 @@ func TestDefaultManager_orphanProxyPortCleanup(t *testing.T) { ci := containerInfo() err := manager.stopSingleContainerWorkload( - context.Background(), &ci, &runner.RunConfig{BaseName: workloadName, Port: 54321}, + context.Background(), &ci, savedRunConfig(t), ) require.NoError(t, err) @@ -2435,7 +3096,6 @@ func TestDefaultManager_orphanProxyPortCleanup(t *testing.T) { }) t.Run("delete frees orphan proxy port when status file missing", func(t *testing.T) { - t.Parallel() ctrl := gomock.NewController(t) defer ctrl.Finish() @@ -2451,11 +3111,11 @@ func TestDefaultManager_orphanProxyPortCleanup(t *testing.T) { rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), workloadName).Return(runtime.ContainerInfo{}, runtime.ErrWorkloadNotFound) // Missing status file: no tracked PID, so the proxy is not killed by PID. sm.EXPECT().GetWorkloadPID(gomock.Any(), workloadName).Return(0, nil) - sm.EXPECT().ResetWorkloadPID(gomock.Any(), workloadName).Return(nil) sm.EXPECT().DeleteWorkloadStatus(gomock.Any(), workloadName).Return(nil) var freed []*runner.RunConfig runConfig := &runner.RunConfig{BaseName: workloadName, Port: 54321} + persistStopRunConfig(t, workloadName, runConfig) manager := &DefaultManager{statuses: sm, runtime: rtMock} withPortFreer(func(_ context.Context, rc *runner.RunConfig) { freed = append(freed, rc) @@ -2470,7 +3130,6 @@ func TestDefaultManager_orphanProxyPortCleanup(t *testing.T) { }) t.Run("delete does not free port on normal shutdown", func(t *testing.T) { - t.Parallel() ctrl := gomock.NewController(t) defer ctrl.Finish() @@ -2483,9 +3142,9 @@ func TestDefaultManager_orphanProxyPortCleanup(t *testing.T) { rtMock.EXPECT().RemoveWorkload(gomock.Any(), workloadName).Return(nil) rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), workloadName).Return(runtime.ContainerInfo{}, runtime.ErrWorkloadNotFound) // A valid, killable PID: the proxy is stopped by PID, so no fallback. - pid := startKillableProcess(t) + pid := startVerifiedProxyProcess(t, workloadName).pid sm.EXPECT().GetWorkloadPID(gomock.Any(), workloadName).Return(pid, nil) - sm.EXPECT().ResetWorkloadPID(gomock.Any(), workloadName).Return(nil) + sm.EXPECT().ResetWorkloadPIDIfMatch(gomock.Any(), workloadName, pid).Return(nil) sm.EXPECT().DeleteWorkloadStatus(gomock.Any(), workloadName).Return(nil) freedCalls := 0 @@ -2495,7 +3154,7 @@ func TestDefaultManager_orphanProxyPortCleanup(t *testing.T) { })(manager) err := manager.deleteContainerWorkload( - context.Background(), workloadName, &runner.RunConfig{BaseName: workloadName, Port: 54321}, + context.Background(), workloadName, savedRunConfig(t), ) require.NoError(t, err) @@ -2503,7 +3162,6 @@ func TestDefaultManager_orphanProxyPortCleanup(t *testing.T) { }) t.Run("remote stop frees orphan proxy port when status file missing", func(t *testing.T) { - t.Parallel() ctrl := gomock.NewController(t) defer ctrl.Finish() @@ -2517,10 +3175,10 @@ func TestDefaultManager_orphanProxyPortCleanup(t *testing.T) { sm.EXPECT().GetWorkload(gomock.Any(), workloadName).Return(core.Workload{}, runtime.ErrWorkloadNotFound) // No tracked PID, so the proxy is not killed by PID. sm.EXPECT().GetWorkloadPID(gomock.Any(), workloadName).Return(0, nil) - sm.EXPECT().ResetWorkloadPID(gomock.Any(), workloadName).Return(nil) var freed []*runner.RunConfig runConfig := &runner.RunConfig{BaseName: workloadName, Port: 54321} + persistStopRunConfig(t, workloadName, runConfig) manager := &DefaultManager{statuses: sm} withPortFreer(func(_ context.Context, rc *runner.RunConfig) { freed = append(freed, rc) @@ -2535,7 +3193,6 @@ func TestDefaultManager_orphanProxyPortCleanup(t *testing.T) { }) t.Run("remote delete frees orphan proxy port when status file missing", func(t *testing.T) { - t.Parallel() ctrl := gomock.NewController(t) defer ctrl.Finish() @@ -2545,11 +3202,11 @@ func TestDefaultManager_orphanProxyPortCleanup(t *testing.T) { sm.EXPECT().SetWorkloadStatus(gomock.Any(), workloadName, runtime.WorkloadStatusRemoving, "").Return(nil) // Missing status file: no tracked PID, so the proxy is not killed by PID. sm.EXPECT().GetWorkloadPID(gomock.Any(), workloadName).Return(0, nil) - sm.EXPECT().ResetWorkloadPID(gomock.Any(), workloadName).Return(nil) sm.EXPECT().DeleteWorkloadStatus(gomock.Any(), workloadName).Return(nil) var freed []*runner.RunConfig runConfig := &runner.RunConfig{BaseName: workloadName, Port: 54321} + persistStopRunConfig(t, workloadName, runConfig) manager := &DefaultManager{statuses: sm} withPortFreer(func(_ context.Context, rc *runner.RunConfig) { freed = append(freed, rc) @@ -2564,7 +3221,6 @@ func TestDefaultManager_orphanProxyPortCleanup(t *testing.T) { }) t.Run("remote stop does not free port on normal shutdown", func(t *testing.T) { - t.Parallel() ctrl := gomock.NewController(t) defer ctrl.Finish() @@ -2577,9 +3233,9 @@ func TestDefaultManager_orphanProxyPortCleanup(t *testing.T) { }, nil) sm.EXPECT().SetWorkloadStatus(gomock.Any(), workloadName, runtime.WorkloadStatusStopping, "").Return(nil) // A valid, killable PID: the proxy is stopped by PID, so no fallback. - pid := startKillableProcess(t) + pid := startVerifiedProxyProcess(t, workloadName).pid sm.EXPECT().GetWorkloadPID(gomock.Any(), workloadName).Return(pid, nil) - sm.EXPECT().ResetWorkloadPID(gomock.Any(), workloadName).Return(nil) + sm.EXPECT().ResetWorkloadPIDIfMatch(gomock.Any(), workloadName, pid).Return(nil) sm.EXPECT().SetWorkloadStatus(gomock.Any(), workloadName, runtime.WorkloadStatusStopped, "").Return(nil) freedCalls := 0 @@ -2589,7 +3245,7 @@ func TestDefaultManager_orphanProxyPortCleanup(t *testing.T) { })(manager) err := manager.stopRemoteWorkload( - context.Background(), workloadName, &runner.RunConfig{BaseName: workloadName, Port: 54321}, + context.Background(), workloadName, savedRunConfig(t), ) require.NoError(t, err) @@ -2597,7 +3253,6 @@ func TestDefaultManager_orphanProxyPortCleanup(t *testing.T) { }) t.Run("remote delete does not free port on normal shutdown", func(t *testing.T) { - t.Parallel() ctrl := gomock.NewController(t) defer ctrl.Finish() @@ -2606,9 +3261,9 @@ func TestDefaultManager_orphanProxyPortCleanup(t *testing.T) { sm.EXPECT().SetWorkloadStatus(gomock.Any(), workloadName, runtime.WorkloadStatusRemoving, "").Return(nil) // A valid, killable PID: the proxy is stopped by PID, so no fallback. - pid := startKillableProcess(t) + pid := startVerifiedProxyProcess(t, workloadName).pid sm.EXPECT().GetWorkloadPID(gomock.Any(), workloadName).Return(pid, nil) - sm.EXPECT().ResetWorkloadPID(gomock.Any(), workloadName).Return(nil) + sm.EXPECT().ResetWorkloadPIDIfMatch(gomock.Any(), workloadName, pid).Return(nil) sm.EXPECT().DeleteWorkloadStatus(gomock.Any(), workloadName).Return(nil) freedCalls := 0 @@ -2618,7 +3273,7 @@ func TestDefaultManager_orphanProxyPortCleanup(t *testing.T) { })(manager) err := manager.deleteRemoteWorkload( - context.Background(), workloadName, &runner.RunConfig{BaseName: workloadName, Port: 54321}, + context.Background(), workloadName, savedRunConfig(t), ) require.NoError(t, err) From 98758754fd8f4bf9402db1a6463b9dcd4847a443 Mon Sep 17 00:00:00 2001 From: Jairus Christensen Date: Tue, 27 Oct 2026 11:00:43 -0600 Subject: [PATCH 2/7] Cover shutdown cleanup error paths Signed-off-by: Jairus Christensen --- pkg/process/mocks/mock_process_metadata.go | 85 +++++ pkg/process/toolhive_proxy.go | 16 +- pkg/process/toolhive_proxy_test.go | 79 +++++ pkg/workloads/main_test.go | 34 ++ pkg/workloads/manager.go | 59 ++-- pkg/workloads/manager_coverage_test.go | 244 ++++++++++++++ pkg/workloads/manager_test.go | 353 ++++++++++++++++++++- 7 files changed, 841 insertions(+), 29 deletions(-) create mode 100644 pkg/process/mocks/mock_process_metadata.go create mode 100644 pkg/workloads/main_test.go create mode 100644 pkg/workloads/manager_coverage_test.go diff --git a/pkg/process/mocks/mock_process_metadata.go b/pkg/process/mocks/mock_process_metadata.go new file mode 100644 index 0000000000..68855bb50d --- /dev/null +++ b/pkg/process/mocks/mock_process_metadata.go @@ -0,0 +1,85 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: toolhive_proxy.go +// +// Generated by this command: +// +// mockgen -destination=mocks/mock_process_metadata.go -package=mocks -source=toolhive_proxy.go -mock_names=processMetadata=MockProcessMetadata +// + +// Package mocks is a generated GoMock package. +package mocks + +import ( + reflect "reflect" + + gomock "go.uber.org/mock/gomock" +) + +// MockProcessMetadata is a mock of processMetadata interface. +type MockProcessMetadata struct { + ctrl *gomock.Controller + recorder *MockProcessMetadataMockRecorder + isgomock struct{} +} + +// MockProcessMetadataMockRecorder is the mock recorder for MockProcessMetadata. +type MockProcessMetadataMockRecorder struct { + mock *MockProcessMetadata +} + +// NewMockProcessMetadata creates a new mock instance. +func NewMockProcessMetadata(ctrl *gomock.Controller) *MockProcessMetadata { + mock := &MockProcessMetadata{ctrl: ctrl} + mock.recorder = &MockProcessMetadataMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockProcessMetadata) EXPECT() *MockProcessMetadataMockRecorder { + return m.recorder +} + +// Cmdline mocks base method. +func (m *MockProcessMetadata) Cmdline() (string, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Cmdline") + ret0, _ := ret[0].(string) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Cmdline indicates an expected call of Cmdline. +func (mr *MockProcessMetadataMockRecorder) Cmdline() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Cmdline", reflect.TypeOf((*MockProcessMetadata)(nil).Cmdline)) +} + +// Environ mocks base method. +func (m *MockProcessMetadata) Environ() ([]string, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Environ") + ret0, _ := ret[0].([]string) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Environ indicates an expected call of Environ. +func (mr *MockProcessMetadataMockRecorder) Environ() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Environ", reflect.TypeOf((*MockProcessMetadata)(nil).Environ)) +} + +// Exe mocks base method. +func (m *MockProcessMetadata) Exe() (string, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Exe") + ret0, _ := ret[0].(string) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Exe indicates an expected call of Exe. +func (mr *MockProcessMetadataMockRecorder) Exe() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Exe", reflect.TypeOf((*MockProcessMetadata)(nil).Exe)) +} diff --git a/pkg/process/toolhive_proxy.go b/pkg/process/toolhive_proxy.go index baf2844ef9..f42e54e95b 100644 --- a/pkg/process/toolhive_proxy.go +++ b/pkg/process/toolhive_proxy.go @@ -16,6 +16,14 @@ const ( toolHiveBinaryName = "thv" ) +//go:generate mockgen -destination=mocks/mock_process_metadata.go -package=mocks -source=toolhive_proxy.go -mock_names=processMetadata=MockProcessMetadata + +type processMetadata interface { + Environ() ([]string, error) + Cmdline() (string, error) + Exe() (string, error) +} + // containsThvBinary returns true if s appears to reference the thv binary // (e.g. /usr/bin/thv, thv start, thv.exe), avoiding false positives like "toolhive". func containsThvBinary(s string) bool { @@ -80,6 +88,10 @@ func IsTrackedToolHiveProxyForWorkload(pid int, workloadName string) (bool, erro if err != nil { return false, err } + return isTrackedToolHiveProxyForWorkload(p, workloadName) +} + +func isTrackedToolHiveProxyForWorkload(p processMetadata, workloadName string) (bool, error) { env, err := p.Environ() if err != nil { return false, err @@ -101,7 +113,7 @@ func IsTrackedToolHiveProxyForWorkload(pid int, workloadName string) (bool, erro // isToolHiveProcess returns true if p is a ToolHive process (TOOLHIVE_DETACHED // or thv binary in exe/cmdline). -func isToolHiveProcess(p *gopsutilprocess.Process) bool { +func isToolHiveProcess(p processMetadata) bool { if hasToolHiveDetachedEnv(p) { return true } @@ -114,7 +126,7 @@ func isToolHiveProcess(p *gopsutilprocess.Process) bool { return false } -func hasToolHiveDetachedEnv(p *gopsutilprocess.Process) bool { +func hasToolHiveDetachedEnv(p processMetadata) bool { env, err := p.Environ() if err != nil { return false diff --git a/pkg/process/toolhive_proxy_test.go b/pkg/process/toolhive_proxy_test.go index 3de4df7b32..d48819ef56 100644 --- a/pkg/process/toolhive_proxy_test.go +++ b/pkg/process/toolhive_proxy_test.go @@ -5,6 +5,7 @@ package process import ( "bufio" + "errors" "fmt" "os" "os/exec" @@ -16,6 +17,9 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "go.uber.org/mock/gomock" + + "github.com/stacklok/toolhive/pkg/process/mocks" ) func TestIsToolHiveProxyForWorkload_InvalidPID(t *testing.T) { @@ -55,6 +59,81 @@ func TestIsTrackedToolHiveProxyForWorkload_DetachedRequiresExactWorkload(t *test assert.False(t, matched, "a hyphen continues the workload name, not a token boundary") } +func TestIsTrackedToolHiveProxyForWorkload_RejectsMissingIdentity(t *testing.T) { + t.Parallel() + for _, tt := range []struct { + name string + pid int + workload string + }{ + {name: "zero PID", pid: 0, workload: "github"}, + {name: "negative PID", pid: -1, workload: "github"}, + {name: "empty workload", pid: os.Getpid()}, + } { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + matched, err := IsTrackedToolHiveProxyForWorkload(tt.pid, tt.workload) + require.NoError(t, err) + assert.False(t, matched, "both a valid PID and a workload name are required") + }) + } +} + +//nolint:tparallel // owned-child cleanup must finish before the parent looks up its reaped PID +func TestIsTrackedToolHiveProxyForWorkload_ReapedProcess(t *testing.T) { + t.Parallel() + if runtime.GOOS == "windows" { + t.Skip("process identity fixture requires Unix symlinks and process inspection") + } + var pid int + t.Run("owned child", func(t *testing.T) { + pid = startIdentityProcess(t, true, "start", "github", "--foreground") + }) + require.Positive(t, pid) + // The subtest's cleanup kills and reaps the child before looking up its PID. + matched, err := IsTrackedToolHiveProxyForWorkload(pid, "github") + require.Error(t, err) + assert.False(t, matched, "a stale PID must not identify a workload supervisor") +} + +func TestIsTrackedToolHiveProxyForWorkload_MetadataErrors(t *testing.T) { + t.Parallel() + for _, tt := range []struct { + name string + env []string + environErr bool + }{ + { + name: "environment unavailable", + env: []string{ToolHiveDetachedEnv + "=" + ToolHiveDetachedValue}, + environErr: true, + }, + { + name: "detached command line unavailable", + env: []string{ToolHiveDetachedEnv + "=" + ToolHiveDetachedValue}, + }, + {name: "foreground command line unavailable"}, + } { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + metadata := mocks.NewMockProcessMetadata(gomock.NewController(t)) + metadataErr := errors.New("process metadata unavailable") + if tt.environErr { + metadata.EXPECT().Environ().Return(tt.env, metadataErr) + } else { + gomock.InOrder( + metadata.EXPECT().Environ().Return(tt.env, nil), + metadata.EXPECT().Cmdline().Return("/usr/bin/thv start github --foreground", metadataErr), + ) + } + + matched, err := isTrackedToolHiveProxyForWorkload(metadata, "github") + require.ErrorIs(t, err, metadataErr) + assert.False(t, matched, "unreadable identity must not authorize stopping a process") + }) + } +} + func TestIsTrackedToolHiveProxyForWorkload_ForegroundDoesNotRelaxPortIdentity(t *testing.T) { t.Parallel() diff --git a/pkg/workloads/main_test.go b/pkg/workloads/main_test.go new file mode 100644 index 0000000000..d470fec7cf --- /dev/null +++ b/pkg/workloads/main_test.go @@ -0,0 +1,34 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package workloads + +import ( + "fmt" + "os" + "testing" + + "github.com/stacklok/toolhive/pkg/process" +) + +const detachedReaperTestEnv = "TOOLHIVE_TEST_WORKLOADS_DETACHED_REAPER_79CBF5" + +func TestMain(m *testing.M) { + mode, fixture := os.LookupEnv(detachedReaperTestEnv) + if fixture { + if (mode == "clean" || mode == "error") && os.Getenv(process.ToolHiveDetachedEnv) == process.ToolHiveDetachedValue && + len(os.Args) == 4 && os.Args[1] == "start" && + os.Args[2] == "detached-reaper-79cbf5-"+mode && os.Args[3] == "--foreground" { + exitCode := 0 + if mode == "error" { + exitCode = 42 + } + fmt.Printf("detached reaper fixture exit %d\n", exitCode) + os.Exit(exitCode) + } + fmt.Fprintf(os.Stderr, "unexpected detached reaper invocation: mode=%q detached=%q args=%q\n", + mode, os.Getenv(process.ToolHiveDetachedEnv), os.Args) + os.Exit(2) + } + os.Exit(m.Run()) +} diff --git a/pkg/workloads/manager.go b/pkg/workloads/manager.go index 131dd4fd8e..97c2f9cfe2 100644 --- a/pkg/workloads/manager.go +++ b/pkg/workloads/manager.go @@ -100,11 +100,12 @@ type DefaultManager struct { statuses statuses.StatusManager configProvider config.Provider - retryConfig *retryConfig - newRunner mcpRunnerFactory - detachedSpawner detachedProcessSpawner - portFreer portFreer - proxyExitTimeout time.Duration + retryConfig *retryConfig + newRunner mcpRunnerFactory + detachedSpawner detachedProcessSpawner + portFreer portFreer + proxyExitTimeout time.Duration + clientManagerFactory func(context.Context) (client.Manager, error) } // mcpRunner is the subset of *runner.Runner that RunWorkload's retry loop @@ -180,6 +181,17 @@ func withProxyExitTimeout(timeout time.Duration) managerOption { return func(d *DefaultManager) { d.proxyExitTimeout = timeout } } +func withClientManagerFactory(f func(context.Context) (client.Manager, error)) managerOption { + return func(d *DefaultManager) { d.clientManagerFactory = f } +} + +func (d *DefaultManager) newClientManager(ctx context.Context) (client.Manager, error) { + if d.clientManagerFactory != nil { + return d.clientManagerFactory(ctx) + } + return client.NewManager(ctx) +} + func (d *DefaultManager) proxyExitTimeoutOrDefault() time.Duration { if d.proxyExitTimeout > 0 { return d.proxyExitTimeout @@ -519,7 +531,7 @@ func (d *DefaultManager) finishRemoteWorkloadStop(ctx context.Context, name stri if !exists { return nil } - if err := removeClientConfigurations(name, false); err != nil { + if err := d.removeClientConfigurations(name, false); err != nil { slog.Warn("failed to remove client configurations", "error", err) } else { slog.Debug("client configurations removed", "workload", name) @@ -719,7 +731,7 @@ func (d *DefaultManager) recordWorkloadRunFailure(ctx context.Context, name, rea // prepareWorkloadRestart removes stale client configuration and records that // the workload is restarting, unless shutdown interrupted client cleanup. func (d *DefaultManager) prepareWorkloadRestart(ctx context.Context, runConfig *runner.RunConfig, stable bool) { - clientManager, err := client.NewManager(ctx) + clientManager, err := d.newClientManager(ctx) if err == nil { slog.Debug("removing from client configurations before restart", "workload", runConfig.BaseName) if err := clientManager.RemoveServerFromClients(ctx, runConfig.BaseName, runConfig.Group); err != nil { @@ -891,15 +903,17 @@ func (d *DefaultManager) spawnDetached(ctx context.Context, runConfig *runner.Ru } // A long-lived parent (thv serve) must reap its detached children too. - go func() { - if err := detachedCmd.Wait(); err != nil { - slog.Debug("detached proxy exited with error", "pid", detachedCmd.Process.Pid, "error", err) - } - }() + go reapDetachedProcess(detachedCmd) return detachedCmd.Process.Pid, nil } +func reapDetachedProcess(cmd *exec.Cmd) { + if err := cmd.Wait(); err != nil { + slog.Debug("detached proxy exited with error", "pid", cmd.Process.Pid, "error", err) + } +} + // GetLogs retrieves the logs of a container. // The lines parameter specifies the maximum number of lines to return from the end of the logs. // If lines is 0, all logs are returned. @@ -1146,8 +1160,13 @@ func (d *DefaultManager) stopProcess(ctx context.Context, name string) bool { return false } + return d.stopVerifiedProxy(ctx, name, pid, process.KillProcess) +} + +// stopVerifiedProxy terminates a proxy whose identity the caller has verified. +func (d *DefaultManager) stopVerifiedProxy(ctx context.Context, name string, pid int, signal func(int) error) bool { slog.Debug("stopping proxy process", "workload", name, "pid", pid) - if err := process.KillProcess(pid); err != nil { + if err := signal(pid); err != nil { slog.Debug("failed to kill proxy process", "error", err) return false } @@ -1302,7 +1321,7 @@ func (d *DefaultManager) cleanupWorkloadResources(ctx context.Context, name, bas } // Remove client configurations - if err := removeClientConfigurations(name, isAuxiliary); err != nil { + if err := d.removeClientConfigurations(name, isAuxiliary); err != nil { slog.Warn("failed to remove client configurations", "error", err) } else { slog.Debug("client configurations removed", "workload", name) @@ -1498,7 +1517,7 @@ func (d *DefaultManager) maybeSetupRemoteWorkload( slog.Debug("failed to set workload status to stopping", "workload", name, "error", err) } d.stopProxyIfNeeded(ctx, name, runConfig.BaseName) - if err := removeClientConfigurations(name, false); err != nil { + if err := d.removeClientConfigurations(name, false); err != nil { slog.Warn("failed to remove client configurations", "error", err) } if err := d.statuses.SetWorkloadStatus(ctx, name, rt.WorkloadStatusStopped, ""); err != nil { @@ -1626,7 +1645,7 @@ func (d *DefaultManager) maybeSetupContainerWorkload(ctx context.Context, name s } // Clean up client configurations - if err := removeClientConfigurations(workloadName, labels.IsAuxiliaryWorkload(container.Labels)); err != nil { + if err := d.removeClientConfigurations(workloadName, labels.IsAuxiliaryWorkload(container.Labels)); err != nil { slog.Warn("failed to remove client configurations", "error", err) } @@ -1686,8 +1705,8 @@ func (d *DefaultManager) startWorkload(ctx context.Context, name string, mcpRunn } // TODO: Move to dedicated config management interface. -// updateClientConfigurations updates client configuration files with the MCP server URL -func removeClientConfigurations(containerName string, isAuxiliary bool) error { +// removeClientConfigurations removes the server from client configuration files. +func (d *DefaultManager) removeClientConfigurations(containerName string, isAuxiliary bool) error { // Get the workload's group by loading its run config runConfig, err := runner.LoadState(context.Background(), containerName) var group string @@ -1701,7 +1720,7 @@ func removeClientConfigurations(containerName string, isAuxiliary bool) error { group = runConfig.Group } - clientManager, err := client.NewManager(context.Background()) + clientManager, err := d.newClientManager(context.Background()) if err != nil { slog.Warn("failed to create client manager, skipping client config removal", "workload", containerName, "error", err) return nil @@ -1798,7 +1817,7 @@ func (d *DefaultManager) stopSingleContainerWorkload( return nil } - if err := removeClientConfigurations(name, isAuxiliary); err != nil { + if err := d.removeClientConfigurations(name, isAuxiliary); err != nil { slog.Warn("failed to remove client configurations", "error", err) } else { slog.Debug("client configurations removed", "workload", name) diff --git a/pkg/workloads/manager_coverage_test.go b/pkg/workloads/manager_coverage_test.go new file mode 100644 index 0000000000..fdf34e210d --- /dev/null +++ b/pkg/workloads/manager_coverage_test.go @@ -0,0 +1,244 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package workloads + +import ( + "context" + "errors" + "fmt" + "math" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/adrg/xdg" + "github.com/stretchr/testify/require" + "go.uber.org/mock/gomock" + + "github.com/stacklok/toolhive/pkg/client" + clientMocks "github.com/stacklok/toolhive/pkg/client/mocks" + "github.com/stacklok/toolhive/pkg/container/runtime" + runtimeMocks "github.com/stacklok/toolhive/pkg/container/runtime/mocks" + "github.com/stacklok/toolhive/pkg/labels" + "github.com/stacklok/toolhive/pkg/process" + "github.com/stacklok/toolhive/pkg/runner" + statusMocks "github.com/stacklok/toolhive/pkg/workloads/statuses/mocks" +) + +func TestDetachedReaperFixture_RejectsMismatchedInvocation(t *testing.T) { + t.Parallel() + executable, err := os.Executable() + require.NoError(t, err) + for _, tt := range []struct { + name string + mode string + }{ + {name: "marked malformed invocation", mode: "clean"}, + {name: "empty marker"}, + } { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + t.Cleanup(cancel) + // If TestMain falls through, select no tests so a regression cannot recursively spawn fixtures. + cmd := exec.CommandContext(ctx, executable, "-test.run=^$") + for _, entry := range os.Environ() { + if !strings.HasPrefix(entry, detachedReaperTestEnv+"=") && + !strings.HasPrefix(entry, process.ToolHiveDetachedEnv+"=") { + cmd.Env = append(cmd.Env, entry) + } + } + cmd.Env = append(cmd.Env, detachedReaperTestEnv+"="+tt.mode, + process.ToolHiveDetachedEnv+"="+process.ToolHiveDetachedValue) + output, err := cmd.CombinedOutput() + require.NoError(t, ctx.Err(), "fixture must reject the invocation before the deadline") + var exitErr *exec.ExitError + require.ErrorAs(t, err, &exitErr) + require.Equal(t, 2, exitErr.ExitCode(), string(output)) + require.Contains(t, string(output), "unexpected detached reaper invocation") + }) + } +} + +func TestDefaultManager_prepareWorkloadRestart_ClientCleanup(t *testing.T) { + t.Parallel() + for _, tt := range []struct { + name string + stable bool + cancelCleanup bool + preCancelled bool + factoryError bool + }{ + {name: "cleanup error still restarts"}, + {name: "cleanup error still restarts stable workload", stable: true}, + {name: "cancellation during cleanup preserves status", cancelCleanup: true}, + {name: "pre-cancelled restart preserves status", preCancelled: true}, + {name: "factory failure still restarts", factoryError: true}, + } { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + t.Cleanup(cancel) + if tt.preCancelled { + cancel() + } + ctrl := gomock.NewController(t) + sm := statusMocks.NewMockStatusManager(ctrl) + cm := clientMocks.NewMockManager(ctrl) + const name, group = "retry-client-cleanup", "test-group" + if !tt.factoryError { + cleanupCall := cm.EXPECT().RemoveServerFromClients(ctx, name, group).DoAndReturn(func(context.Context, string, string) error { + if !tt.preCancelled { + require.NoError(t, ctx.Err(), "cancellation must begin inside client cleanup") + } + if tt.cancelCleanup { + cancel() + } + return errors.New("client configuration is read-only") + }) + if tt.preCancelled { + cleanupCall.AnyTimes() + } + } + if !tt.cancelCleanup && !tt.preCancelled { + reason := "Container exited, restarting" + if tt.stable { + reason = "Container exited after stable run, restarting" + } + sm.EXPECT().SetWorkloadStatus(ctx, name, runtime.WorkloadStatusStarting, reason).Return(nil) + } + manager := &DefaultManager{statuses: sm} + withClientManagerFactory(func(context.Context) (client.Manager, error) { + if tt.factoryError { + return nil, errors.New("client manager unavailable") + } + return cm, nil + })(manager) + + manager.prepareWorkloadRestart(ctx, &runner.RunConfig{BaseName: name, Group: group}, tt.stable) + if tt.cancelCleanup || tt.preCancelled { + require.ErrorIs(t, ctx.Err(), context.Canceled) + } + }) + } +} + +//nolint:paralleltest // saved-workload fixtures use t.Setenv +func TestDefaultManager_StopCleanupErrorsDoNotPreventStopped(t *testing.T) { + isolateWorkloadStopState(t) + for _, remote := range []bool{false, true} { + for _, factoryError := range []bool{false, true} { + t.Run(fmt.Sprintf("remote=%t/factoryError=%t", remote, factoryError), func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + t.Cleanup(cancel) + const name, group = "stop-client-cleanup", "test-group" + rc := &runner.RunConfig{BaseName: name, Group: group} + persistStopRunConfig(t, name, rc) + ctrl := gomock.NewController(t) + sm := statusMocks.NewMockStatusManager(ctrl) + cm := clientMocks.NewMockManager(ctrl) + rm := runtimeMocks.NewMockRuntime(ctrl) + manager := &DefaultManager{statuses: sm, runtime: rm} + withClientManagerFactory(func(context.Context) (client.Manager, error) { + if factoryError { + return nil, errors.New("client manager unavailable") + } + return cm, nil + })(manager) + var cleanupCall *gomock.Call + if !factoryError { + cleanupCall = cm.EXPECT().RemoveServerFromClients(gomock.Any(), name, group). + Return(errors.New("client configuration is read-only")) + } + stopped := sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusStopped, "").Return(nil) + if cleanupCall != nil { + stopped.After(cleanupCall) + } + if remote { + require.NoError(t, manager.finishRemoteWorkloadStop(ctx, name, rc)) + return + } + sm.EXPECT().GetWorkloadPID(gomock.Any(), name).Return(0, nil) + withPortFreer(func(context.Context, *runner.RunConfig) {})(manager) + stop := rm.EXPECT().StopWorkload(gomock.Any(), name).Return(nil) + stopped.After(stop) + if cleanupCall != nil { + cleanupCall.After(stop) + } + require.NoError(t, manager.stopSingleContainerWorkload(ctx, &runtime.ContainerInfo{ + Name: name, Labels: map[string]string{labels.LabelBaseName: name}, + }, rc)) + }) + } + } +} + +func TestDefaultManager_stopVerifiedProxy_SignalErrorPreservesPID(t *testing.T) { + t.Parallel() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + t.Cleanup(cancel) + const name = "signal-error-proxy" + pid := math.MaxInt32 + manager := &DefaultManager{statuses: statusMocks.NewMockStatusManager(gomock.NewController(t))} + signalled := false + signal := func(handle int) error { + signalled = true + require.Equal(t, pid, handle, "the injected signal must receive the saved PID") + return errors.New("process signal failed") + } + + require.False(t, manager.stopVerifiedProxy(ctx, name, pid, signal), "a failed signal must not reset the saved PID") + require.True(t, signalled) +} + +func TestDefaultManager_spawnDetached_ReapsOwnedChildren(t *testing.T) { + isolateWorkloadStopState(t) + t.Setenv(process.ToolHiveDetachedEnv, "") + for _, mode := range []string{"clean", "error"} { + t.Run(mode, func(t *testing.T) { + t.Setenv(detachedReaperTestEnv, mode) + name := "detached-reaper-79cbf5-" + mode + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + t.Cleanup(cancel) + sm := statusMocks.NewMockStatusManager(gomock.NewController(t)) + sm.EXPECT().SetWorkloadStatus(ctx, name, runtime.WorkloadStatusStarting, "").Return(nil) + manager := &DefaultManager{statuses: sm} + + pid, err := manager.spawnDetached(ctx, &runner.RunConfig{BaseName: name}) + require.NoError(t, err) + require.Positive(t, pid) + reaped := false + t.Cleanup(func() { + if reaped { + return + } + alive, findErr := process.FindProcess(pid) + if findErr == nil && alive { + child, findErr := os.FindProcess(pid) + if findErr == nil { + _ = child.Kill() + } + } + cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cleanupCancel() + require.NoError(t, process.WaitForExit(cleanupCtx, pid), "detached fixture must not outlive the test") + }) + require.NoError(t, process.WaitForExit(ctx, pid), "spawnDetached must reap even a failed child") + reaped = true + alive, err := process.FindProcess(pid) + require.NoError(t, err) + require.False(t, alive) + log, err := os.ReadFile(filepath.Join(xdg.DataHome, "toolhive", "logs", name+".log")) + require.NoError(t, err) + exitCode := 0 + if mode == "error" { + exitCode = 42 + } + require.Contains(t, string(log), fmt.Sprintf("detached reaper fixture exit %d", exitCode), "only the explicitly gated child fixture may run") + }) + } +} diff --git a/pkg/workloads/manager_test.go b/pkg/workloads/manager_test.go index 6a160ea355..02d3da9855 100644 --- a/pkg/workloads/manager_test.go +++ b/pkg/workloads/manager_test.go @@ -9,11 +9,13 @@ import ( "errors" "fmt" "maps" + "net" "os" "os/exec" "os/signal" "path/filepath" goruntime "runtime" + "strconv" "strings" "syscall" "testing" @@ -24,12 +26,14 @@ import ( "github.com/stretchr/testify/require" "go.uber.org/mock/gomock" + "github.com/stacklok/toolhive/pkg/client" "github.com/stacklok/toolhive/pkg/config" configMocks "github.com/stacklok/toolhive/pkg/config/mocks" "github.com/stacklok/toolhive/pkg/container/runtime" runtimeMocks "github.com/stacklok/toolhive/pkg/container/runtime/mocks" "github.com/stacklok/toolhive/pkg/core" "github.com/stacklok/toolhive/pkg/labels" + "github.com/stacklok/toolhive/pkg/networking" "github.com/stacklok/toolhive/pkg/process" "github.com/stacklok/toolhive/pkg/runner" "github.com/stacklok/toolhive/pkg/state" @@ -1295,6 +1299,119 @@ func TestDefaultManager_RunWorkload_CancelledSupervisorClearsOnlyItsOwnPID(t *te require.NoError(t, manager.RunWorkload(ctx, &runner.RunConfig{BaseName: name})) } +func TestDefaultManager_RunWorkload_CancellationPreventsFurtherAttempts(t *testing.T) { + t.Parallel() + + for _, stage := range []string{"initial status", "runner", "restart status"} { + t.Run(stage, func(t *testing.T) { + t.Parallel() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + t.Cleanup(cancel) + ctrl := gomock.NewController(t) + sm := statusMocks.NewMockStatusManager(ctrl) + const name = "cancel-at-boundary" + sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusStarting, ""). + DoAndReturn(func(context.Context, string, runtime.WorkloadStatus, string) error { + if stage == "initial status" { + cancel() + } + return nil + }) + if stage == "restart status" { + sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusStarting, "Container exited, restarting"). + DoAndReturn(func(context.Context, string, runtime.WorkloadStatus, string) error { + cancel() + return nil + }) + } + expectSupervisorPIDCleanup(t, sm, name) + attempts := 0 + manager := &DefaultManager{statuses: sm} + withClientManagerFactory(func(context.Context) (client.Manager, error) { + return nil, errors.New("client manager unavailable") + })(manager) + withRunnerFactory(func(*runner.RunConfig, statuses.StatusManager) mcpRunner { + attempts++ + if stage == "runner" { + cancel() + } + return &fakeRunner{err: runner.ErrContainerExitedRestartNeeded} + })(manager) + + require.NoError(t, manager.RunWorkload(ctx, &runner.RunConfig{BaseName: name})) + require.ErrorIs(t, ctx.Err(), context.Canceled) + if stage == "initial status" { + assert.Zero(t, attempts, "shutdown must prevent runner creation") + } else { + assert.Equal(t, 1, attempts, "shutdown must not retry or record a terminal error") + } + }) + } +} + +func TestDefaultManager_RunWorkload_FailureSurvivesStatusAndPIDCleanupErrors(t *testing.T) { + t.Parallel() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + t.Cleanup(cancel) + ctrl := gomock.NewController(t) + sm := statusMocks.NewMockStatusManager(ctrl) + const name = "failed-supervisor" + runErr := errors.New("runner failed") + storageErr := errors.New("status storage unavailable") + gomock.InOrder( + sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusStarting, "").Return(nil), + sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusError, runErr.Error()).Return(storageErr), + sm.EXPECT().ResetWorkloadPIDIfMatch(gomock.Any(), name, os.Getpid()). + DoAndReturn(func(cleanupCtx context.Context, _ string, _ int) error { + assert.NoError(t, cleanupCtx.Err()) + _, bounded := cleanupCtx.Deadline() + assert.True(t, bounded) + return storageErr + }), + ) + manager := &DefaultManager{statuses: sm} + withRunnerFactory(func(*runner.RunConfig, statuses.StatusManager) mcpRunner { + return &fakeRunner{err: runErr} + })(manager) + + require.ErrorIs(t, manager.RunWorkload(ctx, &runner.RunConfig{BaseName: name}), runErr) +} + +func TestDefaultManager_recordWorkloadRunFailure_CancellationDoesNotOverwriteStatus(t *testing.T) { + t.Parallel() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + cancel() + manager := &DefaultManager{statuses: statusMocks.NewMockStatusManager(gomock.NewController(t))} + + manager.recordWorkloadRunFailure(ctx, "stopping-supervisor", "runner failed during shutdown") +} + +func TestDefaultManager_RunWorkload_RestartStatusFailureDoesNotConsumeExtraAttempts(t *testing.T) { + t.Parallel() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + t.Cleanup(cancel) + ctrl := gomock.NewController(t) + sm := statusMocks.NewMockStatusManager(ctrl) + const name = "restart-status-failure" + gomock.InOrder( + sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusStarting, "").Return(nil), + sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusStarting, "Container exited, restarting"). + Return(errors.New("status storage unavailable")), + ) + expectSupervisorPIDCleanup(t, sm, name) + factory := &fakeRunnerFactory{outcomes: []fakeRunOutcome{{err: runner.ErrContainerExitedRestartNeeded}, {}}} + manager := &DefaultManager{statuses: sm} + withClientManagerFactory(func(context.Context) (client.Manager, error) { + return nil, errors.New("client manager unavailable") + })(manager) + withRunnerFactory(factory.factory())(manager) + withRetryConfig(retryConfig{maxRetries: 2, initialDelay: time.Millisecond, + maxBackoff: time.Millisecond, stableRunThreshold: time.Minute})(manager) + + require.NoError(t, manager.RunWorkload(ctx, &runner.RunConfig{BaseName: name})) + assert.Equal(t, 2, factory.callCount) +} + //nolint:paralleltest // client configuration isolation uses t.Setenv func TestDefaultManager_RunWorkload_RetryCounterReset(t *testing.T) { isolateWorkloadStopState(t) @@ -2416,6 +2533,7 @@ func persistStopRunConfig(t *testing.T, name string, rc *runner.RunConfig) { type workloadProxyProcess struct { pid int + port int exited chan struct{} waitErr error // Read only after exited is closed by the Wait goroutine. } @@ -2433,13 +2551,25 @@ func TestWorkloadProxyProcess(t *testing.T) { } else { signal.Notify(terminated, syscall.SIGTERM) } - fmt.Println("ready") + var listener net.Listener + if mode == "listen" { + var err error + listener, err = net.Listen("tcp4", "127.0.0.1:0") + require.NoError(t, err) + fmt.Printf("ready %d\n", listener.Addr().(*net.TCPAddr).Port) + } else { + fmt.Println("ready") + } + exitCode := 0 select { case <-terminated: - os.Exit(0) case <-time.After(time.Minute): - os.Exit(1) + exitCode = 1 } + if listener != nil { + require.NoError(t, listener.Close()) + } + os.Exit(exitCode) } func startVerifiedProxyProcess(t *testing.T, name string, args ...string) *workloadProxyProcess { @@ -2448,6 +2578,11 @@ func startVerifiedProxyProcess(t *testing.T, name string, args ...string) *workl } func startProxyProcess(t *testing.T, name string, ignoreSIGTERM bool, args ...string) *workloadProxyProcess { + t.Helper() + return startProxyProcessFixture(t, name, ignoreSIGTERM, false, args...) +} + +func startProxyProcessFixture(t *testing.T, name string, ignoreSIGTERM, listen bool, args ...string) *workloadProxyProcess { t.Helper() if goruntime.GOOS == "windows" { t.Skip("proxy helper requires SIGTERM") @@ -2471,6 +2606,8 @@ func startProxyProcess(t *testing.T, name string, ignoreSIGTERM bool, args ...st mode := "1" if ignoreSIGTERM { mode = "ignore-term" + } else if listen { + mode = "listen" } cmd.Env = append(cmd.Env, "TOOLHIVE_TEST_PROXY_HELPER="+mode) if detached { @@ -2499,7 +2636,16 @@ func startProxyProcess(t *testing.T, name string, ignoreSIGTERM bool, args ...st }) select { case line := <-ready: - require.Equal(t, "ready\n", line) + if listen { + fields := strings.Fields(line) + require.Len(t, fields, 2) + require.Equal(t, "ready", fields[0]) + proxy.port, err = strconv.Atoi(fields[1]) + require.NoError(t, err) + require.Positive(t, proxy.port) + } else { + require.Equal(t, "ready\n", line) + } case <-time.After(5 * time.Second): t.Fatal("proxy helper did not start") } @@ -2683,7 +2829,8 @@ func TestDefaultManager_stopContainerWorkload_RuntimeStopFailureRecordsErrorAfte assert.True(t, cleanupComplete, "runtime stop must follow proxy cleanup even on failure") return stopErr }) - sm.EXPECT().SetWorkloadStatus(gomock.Any(), "container", runtime.WorkloadStatusError, stopErr.Error()).Return(nil) + sm.EXPECT().SetWorkloadStatus(gomock.Any(), "container", runtime.WorkloadStatusError, stopErr.Error()). + Return(errors.New("status storage unavailable")) manager := &DefaultManager{statuses: sm, runtime: rtMock} withPortFreer(func(context.Context, *runner.RunConfig) { cleanupComplete = true })(manager) @@ -2872,6 +3019,126 @@ func TestDefaultManager_stopRemoteWorkload_LiveProxyStatusesEndStopped(t *testin } } +//nolint:paralleltest // saved-workload fixtures use t.Setenv +func TestDefaultManager_stopRemoteWorkload_StatusWriteFailuresDoNotSkipProxyCleanup(t *testing.T) { + isolateWorkloadStopState(t) + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + t.Cleanup(cancel) + const name = "remote-status-failure" + rc := &runner.RunConfig{BaseName: name, RemoteURL: "https://example.com/mcp"} + persistStopRunConfig(t, name, rc) + ctrl := gomock.NewController(t) + sm := statusMocks.NewMockStatusManager(ctrl) + storageErr := errors.New("status storage unavailable") + fallbackCalls := 0 + gomock.InOrder( + sm.EXPECT().GetWorkload(gomock.Any(), name).Return(core.Workload{Status: runtime.WorkloadStatusRunning}, nil), + sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusStopping, "").Return(storageErr), + sm.EXPECT().GetWorkloadPID(gomock.Any(), name).Return(0, nil), + sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusStopped, ""). + DoAndReturn(func(context.Context, string, runtime.WorkloadStatus, string) error { + assert.Equal(t, 1, fallbackCalls, "proxy cleanup must precede the final status write") + return storageErr + }), + ) + manager := &DefaultManager{statuses: sm} + withPortFreer(func(context.Context, *runner.RunConfig) { fallbackCalls++ })(manager) + + require.NoError(t, manager.stopRemoteWorkload(ctx, name, rc)) + assert.Equal(t, 1, fallbackCalls) +} + +//nolint:paralleltest // saved-workload fixtures use t.Setenv +func TestDefaultManager_stopRemoteWorkload_StoppedStatusStillCleansUpProxy(t *testing.T) { + isolateWorkloadStopState(t) + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + t.Cleanup(cancel) + const name = "already-stopped-remote" + ctrl := gomock.NewController(t) + sm := statusMocks.NewMockStatusManager(ctrl) + sm.EXPECT().GetWorkload(gomock.Any(), name).Return(core.Workload{Status: runtime.WorkloadStatusStopped}, nil) + sm.EXPECT().GetWorkloadPID(gomock.Any(), name).Return(0, nil) + manager := &DefaultManager{statuses: sm} + rc := &runner.RunConfig{BaseName: name} + fallbackCalls := 0 + withPortFreer(func(_ context.Context, got *runner.RunConfig) { + assert.Same(t, rc, got) + fallbackCalls++ + })(manager) + + require.NoError(t, manager.stopRemoteWorkload(ctx, name, rc)) + assert.Equal(t, 1, fallbackCalls, "stale status must not suppress orphan cleanup or create new status") +} + +//nolint:paralleltest // saved-workload fixtures use t.Setenv +func TestDefaultManager_finishRemoteWorkloadStop_StoreFailureDoesNotWriteStopped(t *testing.T) { + isolateWorkloadStopState(t) + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + t.Cleanup(cancel) + stateDir := filepath.Join(xdg.StateHome, state.DefaultAppName) + require.NoError(t, os.MkdirAll(stateDir, 0750)) + require.NoError(t, os.WriteFile(filepath.Join(stateDir, state.RunConfigsDir), []byte("not a directory"), 0600)) + manager := &DefaultManager{statuses: statusMocks.NewMockStatusManager(gomock.NewController(t))} + + err := manager.finishRemoteWorkloadStop(ctx, "remote", &runner.RunConfig{BaseName: "remote"}) + require.Error(t, err) + assert.Contains(t, err.Error(), "failed to open run configuration store after stop") +} + +//nolint:paralleltest // saved-workload fixtures use t.Setenv +func TestDefaultManager_stopContainerWorkload_StateCheckFailurePreservesRuntimeError(t *testing.T) { + isolateWorkloadStopState(t) + if goruntime.GOOS == "windows" { + t.Skip("state failure fixture requires symlinks") + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + t.Cleanup(cancel) + const name = "failed-state-check" + rc := &runner.RunConfig{BaseName: name} + persistStopRunConfig(t, name, rc) + path := filepath.Join(xdg.StateHome, state.DefaultAppName, state.RunConfigsDir, name+".json") + require.NoError(t, os.Remove(path)) + require.NoError(t, os.Symlink(path, path)) + ctrl := gomock.NewController(t) + rtMock := runtimeMocks.NewMockRuntime(ctrl) + sm := statusMocks.NewMockStatusManager(ctrl) + stopErr := errors.New("runtime stop failed") + rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), name).Return(runtime.ContainerInfo{}, runtime.ErrWorkloadNotFound) + sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusStopping, ""). + Return(errors.New("status storage unavailable")) + sm.EXPECT().GetWorkloadPID(gomock.Any(), name).Return(0, nil) + rtMock.EXPECT().StopWorkload(gomock.Any(), name).Return(stopErr) + manager := &DefaultManager{statuses: sm, runtime: rtMock} + withPortFreer(func(context.Context, *runner.RunConfig) {})(manager) + + err := manager.stopContainerWorkload(ctx, name, rc) + require.ErrorIs(t, err, stopErr) + require.ErrorIs(t, err, syscall.ELOOP) + assert.Contains(t, err.Error(), "failed to check saved workload after stop") +} + +//nolint:paralleltest // saved-workload fixtures use t.Setenv +func TestDefaultManager_stopSingleContainerWorkload_AuxiliaryNeedsNoSavedStateOrProxy(t *testing.T) { + isolateWorkloadStopState(t) + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + t.Cleanup(cancel) + const name = "inspector" + ctrl := gomock.NewController(t) + rtMock := runtimeMocks.NewMockRuntime(ctrl) + sm := statusMocks.NewMockStatusManager(ctrl) + gomock.InOrder( + rtMock.EXPECT().StopWorkload(gomock.Any(), name).Return(nil), + sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusStopped, "").Return(nil), + ) + manager := &DefaultManager{runtime: rtMock, statuses: sm} + withPortFreer(func(context.Context, *runner.RunConfig) { t.Error("auxiliary workload must not clean up a proxy") })(manager) + workload := &runtime.ContainerInfo{Name: name, Labels: map[string]string{ + labels.LabelBaseName: name, labels.LabelAuxiliary: "true", + }} + + require.NoError(t, manager.stopSingleContainerWorkload(ctx, workload, &runner.RunConfig{BaseName: name})) +} + // TestDefaultManager_stopProcess verifies the boolean contract that the // stop/delete port-cleanup fallback relies on: stopProcess reports true only // when a tracked, identity-verified proxy exits. A false return (no PID recorded — @@ -2913,13 +3180,14 @@ func TestDefaultManager_stopProcess(t *testing.T) { want: false, }, { - name: "verified proxy exits and returns true", + name: "verified proxy exit succeeds even when PID reset fails", workload: "test-workload", setupMocks: func(t *testing.T, sm *statusMocks.MockStatusManager) { t.Helper() pid := startVerifiedProxyProcess(t, "test-workload").pid sm.EXPECT().GetWorkloadPID(gomock.Any(), "test-workload").Return(pid, nil) - sm.EXPECT().ResetWorkloadPIDIfMatch(gomock.Any(), "test-workload", pid).Return(nil) + sm.EXPECT().ResetWorkloadPIDIfMatch(gomock.Any(), "test-workload", pid). + Return(errors.New("status storage unavailable")) }, want: true, }, @@ -2943,6 +3211,33 @@ func TestDefaultManager_stopProcess(t *testing.T) { } } +func TestDefaultManager_ensureProxyStopped_ExitedPIDCleanupFailureStillFallsBack(t *testing.T) { + t.Parallel() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + t.Cleanup(cancel) + pid, exited := startKillableProcess(t) + child, err := os.FindProcess(pid) + require.NoError(t, err) + require.NoError(t, child.Kill()) + select { + case <-exited: + case <-ctx.Done(): + t.Fatal("child was not reaped before stale PID cleanup") + } + ctrl := gomock.NewController(t) + sm := statusMocks.NewMockStatusManager(ctrl) + const name = "already-exited-proxy" + sm.EXPECT().GetWorkloadPID(gomock.Any(), name).Return(pid, nil) + sm.EXPECT().ResetWorkloadPIDIfMatch(gomock.Any(), name, pid). + Return(errors.New("status storage unavailable")) + manager := &DefaultManager{statuses: sm} + fallbackCalls := 0 + withPortFreer(func(context.Context, *runner.RunConfig) { fallbackCalls++ })(manager) + + manager.ensureProxyStopped(ctx, name, name, &runner.RunConfig{BaseName: name}) + assert.Equal(t, 1, fallbackCalls, "clearing a stale PID is not proof that the port is free") +} + func TestDefaultManager_ensureProxyStopped_UnverifiedLivePIDIsPreservedWithoutSignaling(t *testing.T) { t.Parallel() @@ -3011,6 +3306,50 @@ func TestDefaultManager_ensureProxyStopped_ExitTimeoutPreservesVerifiedPIDAndFal } } +//nolint:paralleltest // saved-workload fixtures use t.Setenv +func TestDefaultManager_freePortHolderIfNeeded_WaitsForOwnedProxyExitAndReleasesListener(t *testing.T) { + isolateWorkloadStopState(t) + if goruntime.GOOS == "darwin" || goruntime.GOOS == "freebsd" { + if _, err := exec.LookPath("lsof"); err != nil { + t.Skipf("TCP owner discovery requires lsof: %v", err) + } + } + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + t.Cleanup(cancel) + name := fmt.Sprintf("port-cleanup-%d", time.Now().UnixNano()) + proxy := startProxyProcessFixture(t, name, false, true) + portPID, err := networking.GetProcessOnPort(proxy.port) + require.NoError(t, err) + require.Equal(t, proxy.pid, portPID, "port discovery must identify only the owned fixture") + rc := &runner.RunConfig{BaseName: name, Port: proxy.port} + persistStopRunConfig(t, name, rc) + saved, err := runner.LoadState(ctx, name) + require.NoError(t, err) + manager := &DefaultManager{} + withProxyExitTimeout(5 * time.Second)(manager) + + wrongWorkload := *saved + wrongWorkload.BaseName += "-other" + manager.freePortHolderIfNeeded(ctx, &wrongWorkload) + alive, err := process.FindProcess(proxy.pid) + require.NoError(t, err) + require.True(t, alive, "cleanup must not signal another workload's proxy") + portPID, err = networking.GetProcessOnPort(proxy.port) + require.NoError(t, err) + require.Equal(t, proxy.pid, portPID, "identity mismatch must leave the owned listener intact") + + manager.freePortHolderIfNeeded(ctx, saved) + listener, err := net.Listen("tcp4", fmt.Sprintf("127.0.0.1:%d", proxy.port)) + require.NoError(t, err, "cleanup must release the listener before returning") + t.Cleanup(func() { assert.NoError(t, listener.Close()) }) + select { + case <-proxy.exited: + require.NoError(t, proxy.waitErr, "owned proxy must complete its graceful shutdown") + case <-ctx.Done(): + t.Fatal("port cleanup did not terminate and reap the owned proxy") + } +} + // TestDefaultManager_orphanProxyPortCleanup verifies that stop and rm fall back // to port-based proxy cleanup when the tracked PID is unavailable (the missing // status-file scenario), and that the fallback does not run on the normal path From c68dcbf151a680a4e041ee94608160b369a58fb4 Mon Sep 17 00:00:00 2001 From: Jairus Christensen Date: Wed, 4 Nov 2026 01:40:11 -0700 Subject: [PATCH 3/7] Stop supervisors before deleting workloads 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 --- docs/arch/08-workloads-lifecycle.md | 2 + pkg/container/docker/client.go | 64 +++++--- pkg/container/docker/client_remove_test.go | 175 +++++++++++++++++++++ pkg/workloads/manager.go | 74 +++++---- pkg/workloads/manager_delete_test.go | 154 ++++++++++++++++++ pkg/workloads/manager_test.go | 12 +- 6 files changed, 427 insertions(+), 54 deletions(-) create mode 100644 pkg/container/docker/client_remove_test.go create mode 100644 pkg/workloads/manager_delete_test.go diff --git a/docs/arch/08-workloads-lifecycle.md b/docs/arch/08-workloads-lifecycle.md index e13914cebf..4a2b00608f 100644 --- a/docs/arch/08-workloads-lifecycle.md +++ b/docs/arch/08-workloads-lifecycle.md @@ -118,6 +118,8 @@ thv rm my-server **Container workload**: Stops proxy → removes container → deletes state +Deletion attempts supervisor shutdown before removing the container. It makes a fresh removal attempt even if the initial container lookup finds no container, because startup may still be in flight. If removal fails, deletion preserves the saved run configuration for retry. Supervisor shutdown remains best-effort and is not a strict barrier: a foreground supervisor may handle SIGTERM by running its own deletion cleanup, which can overlap manager removal if the proxy wait expires; see [Proxy termination](#proxy-termination). + **Remote workload**: Stops proxy → deletes state **Implementation**: `pkg/workloads/manager.go` diff --git a/pkg/container/docker/client.go b/pkg/container/docker/client.go index b16d4ebd04..9e6772d312 100644 --- a/pkg/container/docker/client.go +++ b/pkg/container/docker/client.go @@ -489,33 +489,36 @@ func (c *Client) StopWorkload(ctx context.Context, workloadName string) error { return nil } -// RemoveWorkload removes a workload -// If the workload doesn't exist, it returns success +// RemoveWorkload removes a workload and its associated helpers and networks. +// A missing primary does not prevent cleanup of resources derived from the +// supplied name. Other inspection errors are returned without attempting cleanup. func (c *Client) RemoveWorkload(ctx context.Context, workloadName string) error { - // get container name from ID + // Inspect again at removal time; the supervisor may have created or removed + // the primary container since the manager's initial inspection. containerResponse, err := c.inspectContainerByName(ctx, workloadName) if err != nil { - slog.Warn("failed to inspect container", "name", workloadName, "error", err) + if !errors.Is(err, runtime.ErrWorkloadNotFound) && !errors.Is(err, runtime.ErrContainerNotFound) && !errdefs.IsNotFound(err) { + return fmt.Errorf("failed to inspect workload %s for removal: %w", workloadName, err) + } } - // remove the / if it starts with it - containerName := containerResponse.Name - containerName = strings.TrimPrefix(containerName, "/") - - // remove the workload containers - var labels map[string]string - if containerResponse.Config != nil { - labels = containerResponse.Config.Labels - } else { - labels = make(map[string]string) - } - err = c.removeContainer(ctx, containerResponse.ID) - if err != nil { - return err // removeContainer already wraps the error with context. + containerName := workloadName + var workloadLabels map[string]string + if err == nil { + containerName = strings.TrimPrefix(containerResponse.Name, "/") + if containerResponse.Config != nil { + workloadLabels = containerResponse.Config.Labels + } + if err := c.removeContainer(ctx, containerResponse.ID); err != nil { + return err // removeContainer already wraps the error with context. + } } - // Clean up any proxy containers associated with this workload. - err = c.removeProxyContainers(ctx, containerName, labels) + // When the primary is absent, only its exact workload-name-derived helper + // names are available. Nil labels retain legacy network-isolation cleanup. + // Callers must supply the physical container name to clean up timestamped + // resources in that case; an unknown physical name cannot be reconstructed. + err = c.removeProxyContainers(ctx, containerName, workloadLabels) if err != nil { return err // removeProxyContainers already wraps the error with context. } @@ -1391,7 +1394,7 @@ func (c *Client) removeContainer(ctx context.Context, containerID string) error return nil } -// removeProxyContainers removes the MCP server container and any proxy containers. +// removeProxyContainers removes only exact-name ToolHive auxiliary containers. func (c *Client) removeProxyContainers( ctx context.Context, containerName string, @@ -1414,11 +1417,28 @@ func (c *Client) removeProxyContainers( for _, suffix := range suffixes { containerName := fmt.Sprintf("%s-%s", containerName, suffix) - containerId, err := c.findExistingContainer(ctx, containerName) + result, err := c.api.ContainerList(ctx, mobyclient.ContainerListOptions{ + All: true, + Filters: mobyclient.Filters{}. + Add("name", containerName). + Add("label", fmt.Sprintf("%s=%s", lb.LabelToolHive, lb.LabelToolHiveValue)). + Add("label", fmt.Sprintf("%s=%s", ToolhiveAuxiliaryWorkloadLabel, LabelValueTrue)), + }) if err != nil { slog.Debug("failed to find container", "type", suffix, "name", containerName, "error", err) continue } + var containerId string + for _, candidate := range result.Items { + if candidate.Labels[lb.LabelToolHive] != lb.LabelToolHiveValue || + candidate.Labels[ToolhiveAuxiliaryWorkloadLabel] != LabelValueTrue { + continue + } + if slices.Contains(candidate.Names, containerName) || slices.Contains(candidate.Names, "/"+containerName) { + containerId = candidate.ID + break + } + } if containerId == "" { continue } diff --git a/pkg/container/docker/client_remove_test.go b/pkg/container/docker/client_remove_test.go new file mode 100644 index 0000000000..796046804c --- /dev/null +++ b/pkg/container/docker/client_remove_test.go @@ -0,0 +1,175 @@ +// SPDX-FileCopyrightText: Copyright 2025 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package docker + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "strings" + "sync" + "testing" + + "github.com/containerd/errdefs" + "github.com/moby/moby/api/types/container" + mobyclient "github.com/moby/moby/client" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestRemoveWorkload_AbsentPrimaryCleansOnlyItsOrphanResources(t *testing.T) { + t.Parallel() + for _, tt := range []struct { + name string + disappearsOnInspect bool + collisionLabels map[string]string + }{ + {name: "empty lookup preserves unlabeled helper-name collision"}, + { + name: "Docker inspect not found preserves nonauxiliary ToolHive collision", + disappearsOnInspect: true, + collisionLabels: map[string]string{"toolhive": "true", "toolhive-basename": "svc-ingress"}, + }, + } { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + var mu sync.Mutex + remaining := map[string]bool{ + "/containers/helper-egress": true, + "/containers/helper-dns": true, + "/containers/other-dns": true, + "/containers/collision-ingress": true, + "/networks/internal-svc": true, + "/networks/internal-other": true, + "/networks/external": true, + } + client := discoveryHTTPClient(t, func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + defer mu.Unlock() + path := strings.TrimPrefix(r.URL.Path, "/v1.44") + w.Header().Set("Content-Type", "application/json") + switch { + case r.Method == http.MethodDelete: + if !remaining[path] { + t.Errorf("unexpected or unsafe deletion: %s", path) + http.Error(w, `{"message":"not found"}`, http.StatusNotFound) + return + } + delete(remaining, path) + w.WriteHeader(http.StatusNoContent) + case path == "/containers/json": + // An unrelated workload must keep the shared external network alive. + _, _ = w.Write([]byte(`[{"Id":"other","Names":["/other"],"Labels":{"toolhive":"true"}}]`)) + case path == "/networks": + _, _ = w.Write([]byte(`[{"Id":"internal-svc","Name":"toolhive-svc-internal"},{"Id":"internal-other","Name":"toolhive-other-internal"},{"Id":"external","Name":"toolhive-external"}]`)) + default: + t.Errorf("unexpected Docker request: %s %s", r.Method, path) + http.Error(w, `{"message":"unexpected request"}`, http.StatusInternalServerError) + } + }) + candidates := []container.Summary{ + { + ID: "helper-egress", Names: []string{"/svc-egress"}, + Labels: map[string]string{"toolhive": "true", "toolhive-basename": "svc-egress", ToolhiveAuxiliaryWorkloadLabel: "true"}, + }, + { + ID: "other-dns", Names: []string{"/mysvc-dns"}, + Labels: map[string]string{"toolhive": "true", "toolhive-basename": "mysvc-dns", ToolhiveAuxiliaryWorkloadLabel: "true"}, + }, + { + ID: "helper-dns", Names: []string{"/svc-dns"}, + Labels: map[string]string{"toolhive": "true", "toolhive-basename": "svc-dns", ToolhiveAuxiliaryWorkloadLabel: "true"}, + }, + {ID: "collision-ingress", Names: []string{"/svc-ingress"}, Labels: tt.collisionLabels}, + } + if tt.disappearsOnInspect { + candidates = append(candidates, container.Summary{ + ID: "missing-primary", Names: []string{"/svc"}, + Labels: map[string]string{"toolhive": "true", "toolhive-basename": "svc"}, + }) + } + api := &fakeDockerAPI{ + listFunc: func(_ context.Context, opts mobyclient.ContainerListOptions) ([]container.Summary, error) { + var found []container.Summary + candidateLoop: + for _, candidate := range candidates { + // Honor every requested label so a production ownership filter is exercised. + for _, filter := range filterValues(opts.Filters, "label") { + key, value, hasValue := strings.Cut(filter, "=") + actual, exists := candidate.Labels[key] + if !exists || (hasValue && actual != value) { + continue candidateLoop + } + } + names := filterValues(opts.Filters, "name") + matchesName := len(names) == 0 + for _, name := range names { + for _, actual := range candidate.Names { + matchesName = matchesName || strings.Contains(actual, name) + } + } + if matchesName { + found = append(found, candidate) + } + } + return found, nil + }, + inspectFunc: func(_ context.Context, id string) (container.InspectResponse, error) { + assert.True(t, tt.disappearsOnInspect, "empty lookup must not inspect an empty ID") + assert.Equal(t, "missing-primary", id) + return container.InspectResponse{}, errdefs.ErrNotFound + }, + removeFunc: func(_ context.Context, id string, _ mobyclient.ContainerRemoveOptions) error { + t.Errorf("absent primary must not be removed by empty or stale ID: %q", id) + return nil + }, + } + c := &Client{api: api, client: client} + + require.NoError(t, c.RemoveWorkload(t.Context(), "svc")) + mu.Lock() + defer mu.Unlock() + assert.Equal(t, map[string]bool{ + "/containers/collision-ingress": true, + "/containers/other-dns": true, + "/networks/internal-other": true, + "/networks/external": true, + }, remaining, "cleanup must remove owned helpers and private network without deleting helper-name collisions or unrelated networks") + }) + } +} + +func TestRemoveWorkload_InspectionFailureDoesNotDeleteResources(t *testing.T) { + t.Parallel() + for _, failureAt := range []string{"lookup", "inspect"} { + t.Run(failureAt, func(t *testing.T) { + t.Parallel() + inspectErr := errors.New("Docker daemon unavailable") + api := &fakeDockerAPI{ + listFunc: func(_ context.Context, _ mobyclient.ContainerListOptions) ([]container.Summary, error) { + if failureAt == "lookup" { + return nil, inspectErr + } + return []container.Summary{{ID: "primary", Names: []string{"/svc"}}}, nil + }, + inspectFunc: func(context.Context, string) (container.InspectResponse, error) { + return container.InspectResponse{}, inspectErr + }, + removeFunc: func(context.Context, string, mobyclient.ContainerRemoveOptions) error { + t.Error("failed inspection must not remove a primary container") + return nil + }, + } + client := discoveryHTTPClient(t, func(w http.ResponseWriter, r *http.Request) { + t.Errorf("failed inspection must not attempt helper or network cleanup: %s %s", r.Method, r.URL.Path) + w.WriteHeader(http.StatusInternalServerError) + _ = json.NewEncoder(w).Encode(map[string]string{"message": "unexpected cleanup"}) + }) + c := &Client{api: api, client: client} + + require.ErrorIs(t, c.RemoveWorkload(t.Context(), "svc"), inspectErr) + }) + } +} diff --git a/pkg/workloads/manager.go b/pkg/workloads/manager.go index 97c2f9cfe2..dad395a146 100644 --- a/pkg/workloads/manager.go +++ b/pkg/workloads/manager.go @@ -1048,35 +1048,50 @@ func (d *DefaultManager) deleteContainerWorkload(ctx context.Context, name strin slog.Warn("failed to set workload status to removing", "workload", name, "error", err) } - // Determine baseName and isAuxiliary for cleanup (needed even if container doesn't exist) - var baseName string - var isAuxiliary bool - + // Use live labels when available, falling back to saved identity if startup + // has not created the container yet. + var containerLabels map[string]string if container != nil { - containerLabels := container.Labels - baseName = labels.GetContainerBaseName(containerLabels) - isAuxiliary = labels.IsAuxiliaryWorkload(containerLabels) - - // Remove the container first - if err := d.removeContainer(ctx, name); err != nil { - return err + containerLabels = container.Labels + } else if runConfig != nil { + containerLabels = runConfig.ContainerLabels + } + baseName := labels.GetContainerBaseName(containerLabels) + if baseName == "" { + if runConfig != nil && runConfig.BaseName != "" { + baseName = runConfig.BaseName + } else { + baseName = name } - } else { - // Container doesn't exist, but we still need to clean up state - // Use the workload name as baseName (they're typically the same) - baseName = name - isAuxiliary = false - slog.Debug("container not found for workload, proceeding with state cleanup", "workload", name) } + isAuxiliary := labels.IsAuxiliaryWorkload(containerLabels) - // Stop proxy-runner process AFTER container removal to prevent recreation - // Skip for auxiliary workloads like inspector that don't use proxy processes + // Attempt supervisor shutdown before removal, rather than letting removal + // itself trigger a restart. Shutdown is best-effort and may time out; + // foreground SIGTERM cleanup can then overlap this deletion. + // Auxiliary workloads like inspector do not use proxy processes. if !isAuxiliary { - d.ensureProxyStopped(ctx, name, baseName, runConfig) + proxyConfig := runConfig + if runConfig != nil { + configCopy := *runConfig + configCopy.BaseName = baseName + proxyConfig = &configCopy + } + d.ensureProxyStopped(ctx, name, baseName, proxyConfig) } else { slog.Debug("skipping proxy-runner stop for auxiliary workload", "workload", name) } + // Always perform a fresh removal: a container absent during inspection may + // have been created in flight before the supervisor stopped. + runtimeName := name + if container == nil && runConfig != nil && runConfig.ContainerName != "" { + runtimeName = runConfig.ContainerName + } + if err := d.removeContainer(ctx, name, runtimeName); err != nil { + return err + } + // Clean up associated resources (must happen even if container doesn't exist) d.cleanupWorkloadResources(ctx, name, baseName, isAuxiliary) @@ -1092,7 +1107,7 @@ func (d *DefaultManager) deleteContainerWorkload(ctx context.Context, name strin func (d *DefaultManager) getWorkloadContainer(ctx context.Context, name string) (*rt.ContainerInfo, error) { container, err := d.runtime.GetWorkloadInfo(ctx, name) if err != nil { - if errors.Is(err, rt.ErrWorkloadNotFound) { + if errors.Is(err, rt.ErrWorkloadNotFound) || errors.Is(err, rt.ErrContainerNotFound) { // Log but don't fail the entire operation for not found containers slog.Warn("failed to get workload", "workload", name, "error", err) return nil, nil @@ -1271,14 +1286,15 @@ func (d *DefaultManager) freePortHolderIfNeeded(ctx context.Context, runConfig * } } -// removeContainer removes the container from the runtime -func (d *DefaultManager) removeContainer(ctx context.Context, name string) error { +// removeContainer removes and verifies runtimeName while keeping status and +// diagnostics associated with the original workload name. +func (d *DefaultManager) removeContainer(ctx context.Context, name, runtimeName string) error { slog.Debug("removing container", "workload", name) - if err := d.runtime.RemoveWorkload(ctx, name); err != nil { + if err := d.runtime.RemoveWorkload(ctx, runtimeName); err != nil { if statusErr := d.statuses.SetWorkloadStatus(ctx, name, rt.WorkloadStatusError, err.Error()); statusErr != nil { slog.Warn("Failed to set workload status to error", "workload", name, "error", statusErr) } - return fmt.Errorf("failed to remove container: %w", err) + return fmt.Errorf("failed to remove container for workload %s: %w", name, err) } // Wait for the container to actually be removed from the runtime @@ -1286,21 +1302,21 @@ func (d *DefaultManager) removeContainer(ctx context.Context, name string) error const maxRetries = 30 const retryDelay = 100 * time.Millisecond for range maxRetries { - _, err := d.runtime.GetWorkloadInfo(ctx, name) + _, err := d.runtime.GetWorkloadInfo(ctx, runtimeName) if err != nil { - if errors.Is(err, rt.ErrWorkloadNotFound) { + if errors.Is(err, rt.ErrWorkloadNotFound) || errors.Is(err, rt.ErrContainerNotFound) { // Container is gone, deletion complete slog.Debug("container removed from runtime", "workload", name) return nil } // Some other error occurred slog.Warn("error checking container status during removal", "error", err) - return fmt.Errorf("failed to verify container removal: %w", err) + return fmt.Errorf("failed to verify container removal for workload %s: %w", name, err) } // Container still exists, wait and retry select { case <-ctx.Done(): - return fmt.Errorf("context cancelled while waiting for container removal: %w", ctx.Err()) + return fmt.Errorf("context cancelled while waiting for container removal for workload %s: %w", name, ctx.Err()) case <-time.After(retryDelay): continue } diff --git a/pkg/workloads/manager_delete_test.go b/pkg/workloads/manager_delete_test.go new file mode 100644 index 0000000000..a3b5c46d62 --- /dev/null +++ b/pkg/workloads/manager_delete_test.go @@ -0,0 +1,154 @@ +// SPDX-FileCopyrightText: Copyright 2025 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package workloads + +import ( + "context" + "errors" + "fmt" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.uber.org/mock/gomock" + + "github.com/stacklok/toolhive/pkg/container/runtime" + runtimeMocks "github.com/stacklok/toolhive/pkg/container/runtime/mocks" + "github.com/stacklok/toolhive/pkg/labels" + "github.com/stacklok/toolhive/pkg/process" + "github.com/stacklok/toolhive/pkg/runner" + statusMocks "github.com/stacklok/toolhive/pkg/workloads/statuses/mocks" +) + +//nolint:paralleltest // saved-workload fixtures use t.Setenv +func TestDefaultManager_deleteContainerWorkload_StopsSupervisorBeforeFreshRemoval(t *testing.T) { + isolateWorkloadStopState(t) + removeErr := errors.New("network teardown failed") + for _, tt := range []struct { + name string + missingErr error + removeErr error + verifiedErr error + }{ + {name: "existing primary", verifiedErr: runtime.ErrWorkloadNotFound}, + {name: "primary starts after empty lookup", missingErr: runtime.ErrWorkloadNotFound, verifiedErr: runtime.ErrWorkloadNotFound}, + {name: "primary starts after inspect not found", missingErr: runtime.ErrContainerNotFound, verifiedErr: runtime.ErrContainerNotFound}, + {name: "deletion failure preserves saved config", missingErr: runtime.ErrWorkloadNotFound, removeErr: removeErr}, + } { + t.Run(tt.name, func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + t.Cleanup(cancel) + const name = "deleting-workload" + const containerName = "deleting-workload-1730000000" + rc := &runner.RunConfig{BaseName: name, ContainerName: containerName} + persistStopRunConfig(t, name, rc) + saved, err := runner.LoadState(ctx, name) + require.NoError(t, err) + proxy := startVerifiedProxyProcess(t, name) + ctrl := gomock.NewController(t) + rtMock := runtimeMocks.NewMockRuntime(ctrl) + sm := statusMocks.NewMockStatusManager(ctrl) + primaryExists := tt.missingErr == nil + if tt.missingErr != nil { + rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), name). + Return(runtime.ContainerInfo{}, fmt.Errorf("initial inspection: %w", tt.missingErr)) + } else { + rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), name).Return(runtime.ContainerInfo{ + Name: containerName, Labels: map[string]string{labels.LabelBaseName: name}, + }, nil) + } + sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusRemoving, "").Return(nil) + sm.EXPECT().GetWorkloadPID(gomock.Any(), name).DoAndReturn(func(context.Context, string) (int, error) { + // Model an in-flight supervisor startup finishing after the initial lookup. + primaryExists = true + return proxy.pid, nil + }) + sm.EXPECT().ResetWorkloadPIDIfMatch(gomock.Any(), name, proxy.pid).Return(nil) + removalName := name + if tt.missingErr != nil { + removalName = containerName + } + rtMock.EXPECT().RemoveWorkload(gomock.Any(), removalName).DoAndReturn(func(context.Context, string) error { + alive, err := process.FindProcess(proxy.pid) + require.NoError(t, err) + require.False(t, alive, "runtime deletion began while the supervisor could still recreate the workload") + // Check liveness before waiting: waiting first could hide the original ordering regression. + select { + case <-proxy.exited: + assert.NoError(t, proxy.waitErr, "supervisor must finish graceful shutdown before runtime deletion") + case <-time.After(time.Second): + t.Fatal("supervisor helper was not reaped") + } + assert.True(t, primaryExists, "fresh removal must catch the workload created after the initial lookup") + if tt.removeErr == nil { + primaryExists = false + } + return tt.removeErr + }) + if tt.removeErr != nil { + sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusError, tt.removeErr.Error()).Return(nil) + } else { + rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), removalName). + Return(runtime.ContainerInfo{}, fmt.Errorf("removal verification: %w", tt.verifiedErr)) + sm.EXPECT().DeleteWorkloadStatus(gomock.Any(), name).Return(nil) + } + manager := &DefaultManager{runtime: rtMock, statuses: sm} + withPortFreer(func(context.Context, *runner.RunConfig) { + t.Error("verified supervisor exit must not need port fallback") + })(manager) + + err = manager.deleteContainerWorkload(ctx, name, rc) + if tt.removeErr != nil { + require.ErrorIs(t, err, tt.removeErr) + after, loadErr := runner.LoadState(ctx, name) + require.NoError(t, loadErr, "failed deletion must retain recovery state") + assert.Equal(t, saved, after) + } else { + require.NoError(t, err) + assert.False(t, primaryExists, "delete must not leave a newly created primary behind") + _, loadErr := runner.LoadState(ctx, name) + require.Error(t, loadErr, "successful deletion must remove saved config") + } + }) + } +} + +//nolint:paralleltest // saved-workload fixtures use t.Setenv +func TestDefaultManager_deleteContainerWorkload_AuxiliaryDoesNotStopSupervisorOrDeleteParentConfig(t *testing.T) { + isolateWorkloadStopState(t) + ctx := context.Background() + const parent = "parent-workload" + const auxiliary = "parent-workload-inspector" + parentConfig := &runner.RunConfig{BaseName: parent} + persistStopRunConfig(t, parent, parentConfig) + saved, err := runner.LoadState(ctx, parent) + require.NoError(t, err) + proxy := startVerifiedProxyProcess(t, parent) + auxLabels := map[string]string{labels.LabelBaseName: auxiliary, labels.LabelAuxiliary: "true"} + ctrl := gomock.NewController(t) + rtMock := runtimeMocks.NewMockRuntime(ctrl) + sm := statusMocks.NewMockStatusManager(ctrl) + rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), auxiliary). + Return(runtime.ContainerInfo{Name: auxiliary, Labels: auxLabels}, nil) + sm.EXPECT().SetWorkloadStatus(gomock.Any(), auxiliary, runtime.WorkloadStatusRemoving, "").Return(nil) + rtMock.EXPECT().RemoveWorkload(gomock.Any(), auxiliary).Return(nil) + rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), auxiliary).Return(runtime.ContainerInfo{}, runtime.ErrWorkloadNotFound) + sm.EXPECT().DeleteWorkloadStatus(gomock.Any(), auxiliary).Return(nil) + manager := &DefaultManager{runtime: rtMock, statuses: sm} + withPortFreer(func(context.Context, *runner.RunConfig) { t.Error("auxiliary deletion must not clean up parent proxy") })(manager) + + require.NoError(t, manager.deleteContainerWorkload(ctx, auxiliary, nil)) + alive, err := process.FindProcess(proxy.pid) + require.NoError(t, err) + assert.True(t, alive, "auxiliary deletion must not stop the parent supervisor") + select { + case <-proxy.exited: + t.Error("auxiliary deletion stopped the parent supervisor") + default: + } + after, err := runner.LoadState(ctx, parent) + require.NoError(t, err) + assert.Equal(t, saved, after) +} diff --git a/pkg/workloads/manager_test.go b/pkg/workloads/manager_test.go index 02d3da9855..19d5ea9f4d 100644 --- a/pkg/workloads/manager_test.go +++ b/pkg/workloads/manager_test.go @@ -1710,7 +1710,7 @@ func TestDefaultManager_removeContainer(t *testing.T) { } ctx := context.Background() - err := manager.removeContainer(ctx, tt.workloadName) + err := manager.removeContainer(ctx, tt.workloadName, tt.workloadName) if tt.expectError { require.Error(t, err) @@ -2187,7 +2187,10 @@ func TestDefaultManager_updateSingleWorkload(t *testing.T) { pid := startVerifiedProxyProcess(t, "test-workload").pid sm.EXPECT().GetWorkloadPID(gomock.Any(), "test-workload").Return(pid, nil) rt.EXPECT().StopWorkload(gomock.Any(), "test-workload").Return(nil) - sm.EXPECT().ResetWorkloadPIDIfMatch(gomock.Any(), "test-workload", pid).Return(nil) + resetPID := sm.EXPECT().ResetWorkloadPIDIfMatch(gomock.Any(), "test-workload", pid).Return(nil) + // Delete observes the PID already cleared by stop. + sm.EXPECT().GetWorkloadPID(gomock.Any(), "test-workload"). + Return(0, nil).After(resetPID) // Mock delete operation - workload exists and can be deleted rt.EXPECT().GetWorkloadInfo(gomock.Any(), "test-workload"). @@ -2231,7 +2234,10 @@ func TestDefaultManager_updateSingleWorkload(t *testing.T) { pid := startVerifiedProxyProcess(t, "test-workload").pid sm.EXPECT().GetWorkloadPID(gomock.Any(), "test-workload").Return(pid, nil) rt.EXPECT().StopWorkload(gomock.Any(), "test-workload").Return(nil) - sm.EXPECT().ResetWorkloadPIDIfMatch(gomock.Any(), "test-workload", pid).Return(nil) + resetPID := sm.EXPECT().ResetWorkloadPIDIfMatch(gomock.Any(), "test-workload", pid).Return(nil) + // Delete observes the PID already cleared by stop. + sm.EXPECT().GetWorkloadPID(gomock.Any(), "test-workload"). + Return(0, nil).After(resetPID) // Mock failed delete rt.EXPECT().GetWorkloadInfo(gomock.Any(), "test-workload"). From d8b2713bf7af09cda49f74a08f034315d7981750 Mon Sep 17 00:00:00 2001 From: Jairus Christensen Date: Wed, 4 Nov 2026 20:39:41 -0700 Subject: [PATCH 4/7] Address shutdown review feedback 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. --- docs/arch/08-workloads-lifecycle.md | 99 +++- pkg/container/docker/client.go | 5 + pkg/container/docker/client_remove_test.go | 71 ++- pkg/process/mocks/mock_process_metadata.go | 15 + pkg/process/toolhive_proxy.go | 44 +- pkg/process/toolhive_proxy_test.go | 51 +- pkg/workloads/manager.go | 261 +++++++---- pkg/workloads/manager_coverage_test.go | 38 +- pkg/workloads/manager_delete_test.go | 95 +++- pkg/workloads/manager_test.go | 437 +++++++++++++----- pkg/workloads/statuses/file_status.go | 34 ++ pkg/workloads/statuses/file_status_test.go | 50 ++ .../statuses/mocks/mock_status_manager.go | 14 + pkg/workloads/statuses/noop.go | 5 + pkg/workloads/statuses/status.go | 11 + 15 files changed, 984 insertions(+), 246 deletions(-) diff --git a/docs/arch/08-workloads-lifecycle.md b/docs/arch/08-workloads-lifecycle.md index 4a2b00608f..8b9c6dee79 100644 --- a/docs/arch/08-workloads-lifecycle.md +++ b/docs/arch/08-workloads-lifecycle.md @@ -19,7 +19,11 @@ stateDiagram-v2 Starting --> Running: Success Starting --> Error: Failed + Starting --> Stopping: Stop Running --> Stopping: Stop + Unhealthy --> Stopping: Stop + Unauthenticated --> Stopping: Stop + AuthRetrying --> Stopping: Stop Running --> Unhealthy: Health Failed Running --> Unauthenticated: Auth Failed Running --> AuthRetrying: Transient Token Refresh Failures @@ -81,21 +85,32 @@ thv stop my-server **Container workload**: Stops proxy process → stops container → preserves state -Explicit named stop attempts proxy cleanup even when the primary container has -exited or disappeared. After cleanup, it makes a fresh attempt to stop the -container by name. For an existing saved workload, successful stop writes -`Stopped`, replacing prior `Error` or `PolicyStopped` status and context. -Auxiliary workloads skip proxy cleanup. +Stopping a workload by name always cleans up its proxy and asks the runtime to +stop the container, even when the container has exited or is gone. This stops a +supervisor that is waiting in restart backoff. Auxiliary workloads have no proxy +to clean up. -The unchanged `--all` and `--group` selection still excludes `Starting` workloads, -including supervisors waiting in restart backoff. This recovery applies to -explicit named stop, not all stop forms. +Stop writes `Stopping` and then `Stopped`, and removes client configuration, +only when something was live: the container was running or a supervisor PID was +recorded. Otherwise stop leaves the current status alone, so an `Error` or +`PolicyStopped` workload keeps its status and reason. -Stop preserves saved run configuration, but a foreground `run` still deletes its workload during normal exit cleanup. The bounded five-second exit wait means explicit stop can return before the foreground owner's cleanup completes. Stop rechecks saved configuration before writing final status and skips that write if configuration is already gone. This recheck and the status write are not atomic against concurrent deletion, so deletion races remain. Stop does not create status for an unknown missing name. +`thv stop --all` and `--group` skip `Starting` workloads, including supervisors +waiting in restart backoff. Stop them by name. + +Stop keeps the saved run configuration, but a foreground `run` deletes its +workload when it exits. Stop waits at most five seconds for the supervisor to +exit, so it can return before that cleanup finishes. Before it writes the final +status, stop checks that the saved configuration still exists, and skips the +write if it is gone. The check and the write are not atomic, so a concurrent +delete can still race with stop. Stop does not create status for a name it +doesn't know. **Remote workload**: Stops proxy → preserves state -Successful explicit stop transitions a remote workload from `Running`, `Starting`, `AuthRetrying`, `Unauthenticated`, or `Unhealthy` to `Stopped`, subject to the saved-state recheck above. Terminal status handling is unchanged. +Stop moves a remote workload from `Running`, `Starting`, `AuthRetrying`, +`Unauthenticated`, or `Unhealthy` to `Stopped`, with the same saved +configuration check. Other statuses are left alone. **Implementation**: `pkg/workloads/manager.go` @@ -118,7 +133,25 @@ thv rm my-server **Container workload**: Stops proxy → removes container → deletes state -Deletion attempts supervisor shutdown before removing the container. It makes a fresh removal attempt even if the initial container lookup finds no container, because startup may still be in flight. If removal fails, deletion preserves the saved run configuration for retry. Supervisor shutdown remains best-effort and is not a strict barrier: a foreground supervisor may handle SIGTERM by running its own deletion cleanup, which can overlap manager removal if the proxy wait expires; see [Proxy termination](#proxy-termination). +Delete stops the supervisor before it removes the container. If the container +lookup finds nothing but a saved run configuration exists, delete still asks the +runtime to remove the workload, because a supervisor in backoff can create the +container again. If that removal fails and the container still can't be found, +delete logs the error and cleans up the saved state. If the container now +exists, delete returns the error and keeps the saved state so you can retry. A +name with no container and no saved run configuration skips runtime removal. + +Delete uses the container's runtime name when it finds one, then the saved +`ContainerName`, then the workload name. + +The Docker runtime only deletes networks that carry the `toolhive=true` and +workload name labels. It leaves unlabelled networks alone, even when their +names match ToolHive's naming scheme. + +Stopping the supervisor is best-effort. A foreground supervisor runs its own +cleanup when it gets SIGTERM, and that cleanup can overlap with delete if the +supervisor takes longer than the exit wait. See +[Proxy termination](#proxy-termination). **Remote workload**: Stops proxy → deletes state @@ -152,13 +185,43 @@ The same `Applier` backs both the CLI (`thv upgrade apply`) and the API (`POST / ### Proxy termination -Stop and delete verify that the PID recorded in workload status belongs to a ToolHive process. Non-detached supervisors must also have a `run`, `start`, or `restart` token in their arguments. An unnamed `run` may omit its derived workload name from arguments. Foreground `start` and `restart` include the name, but all three use only the recorded PID for workload binding, without a process-birth-time check. Detached supervisors must match the exact workload name. A live PID whose identity cannot be verified remains recorded and is not signaled. - -On Unix, termination uses SIGTERM without escalation. On Windows, it uses TerminateProcess, a hard stop. Both paths wait up to five seconds for exit. If PID-based termination is unavailable or incomplete, they attempt port-based cleanup when saved configuration permits it. This fallback requires an exact workload identity match for the port holder and also waits up to five seconds for exit. Cleanup is best-effort and can leave a proxy running or its port occupied. - -The supervisor keeps its PID registered across container restart attempts, including backoff. Shutdown cancels the backoff. On final exit, PID cleanup clears the recorded PID only if it still matches the exiting process. - -**Implementation**: `pkg/workloads/manager.go`, `pkg/runner/runner.go` +Before signalling the PID in the status file, stop and delete check that it +belongs to this workload's ToolHive supervisor. A detached supervisor must have +the exact workload name on its command line. A foreground supervisor must be a +`thv` process whose first `run`, `start`, or `restart` argument names the +workload: + +- `start` and `restart` must have the workload name as a whole argument, unless + they use `--all` or `--group`. +- `run` must have `--name `, `--name=`, or the workload name + as a positional argument. Only an unnamed `thv run ` is accepted + without a name, because its name is derived from the image. + +There is no process start-time check, so if the OS reuses the PID for another +matching `thv` command, ToolHive can't tell. A PID that is alive but can't be +verified is left alone. + +On Unix, stop sends SIGTERM and does not escalate. On Windows, it uses +TerminateProcess, which is a hard stop. Both wait up to five seconds for the +process to exit. If the process was signalled but is still exiting after the +wait, stop doesn't signal it again. If there is no PID to signal, or it can't be +verified, stop falls back to freeing the proxy port when the saved configuration +allows it. The port holder must match the workload exactly, and the fallback +also waits up to five seconds. Cleanup is best-effort and can leave a proxy +running or its port in use. + +The supervisor owns its PID entry. It keeps the PID registered across container +restart attempts, including backoff, and shutdown cancels the backoff. When it +exits, it clears the PID only if the entry still holds its own PID. If it was +cancelled by a signal while `Starting` or `Running`, it writes `Stopped` under +the status file lock, as long as the recorded PID is unset or its own, and exits +with status 0. + +Start and restart stop any other supervisor whose PID is recorded for the +workload before they spawn a new one, whatever the current status is. They never +signal their own PID. + +**Implementation**: `pkg/workloads/manager.go`, `pkg/process/toolhive_proxy.go` ### List diff --git a/pkg/container/docker/client.go b/pkg/container/docker/client.go index 9e6772d312..5e85886e4d 100644 --- a/pkg/container/docker/client.go +++ b/pkg/container/docker/client.go @@ -1372,6 +1372,11 @@ func (c *Client) deleteNetwork(ctx context.Context, name string) error { return nil } + if !lb.IsToolHiveContainer(networkToRemove.Labels) || lb.GetContainerName(networkToRemove.Labels) == "" { + slog.Debug("network lacks ToolHive ownership labels, skipping deletion", "name", name) + return nil + } + if _, err := c.client.NetworkRemove(ctx, networkToRemove.ID, mobyclient.NetworkRemoveOptions{}); err != nil { return fmt.Errorf("failed to remove network %s: %w", name, err) } diff --git a/pkg/container/docker/client_remove_test.go b/pkg/container/docker/client_remove_test.go index 796046804c..95fc74b0ed 100644 --- a/pkg/container/docker/client_remove_test.go +++ b/pkg/container/docker/client_remove_test.go @@ -14,9 +14,12 @@ import ( "github.com/containerd/errdefs" "github.com/moby/moby/api/types/container" + "github.com/moby/moby/api/types/network" mobyclient "github.com/moby/moby/client" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + + "github.com/stacklok/toolhive/pkg/labels" ) func TestRemoveWorkload_AbsentPrimaryCleansOnlyItsOrphanResources(t *testing.T) { @@ -63,7 +66,7 @@ func TestRemoveWorkload_AbsentPrimaryCleansOnlyItsOrphanResources(t *testing.T) // An unrelated workload must keep the shared external network alive. _, _ = w.Write([]byte(`[{"Id":"other","Names":["/other"],"Labels":{"toolhive":"true"}}]`)) case path == "/networks": - _, _ = w.Write([]byte(`[{"Id":"internal-svc","Name":"toolhive-svc-internal"},{"Id":"internal-other","Name":"toolhive-other-internal"},{"Id":"external","Name":"toolhive-external"}]`)) + _, _ = w.Write([]byte(`[{"Id":"internal-svc","Name":"toolhive-svc-internal","Labels":{"toolhive":"true","toolhive-name":"toolhive-svc-internal"}},{"Id":"internal-other","Name":"toolhive-other-internal","Labels":{"toolhive":"true","toolhive-name":"toolhive-other-internal"}},{"Id":"external","Name":"toolhive-external","Labels":{"toolhive":"true","toolhive-name":"toolhive-external"}}]`)) default: t.Errorf("unexpected Docker request: %s %s", r.Method, path) http.Error(w, `{"message":"unexpected request"}`, http.StatusInternalServerError) @@ -141,6 +144,72 @@ func TestRemoveWorkload_AbsentPrimaryCleansOnlyItsOrphanResources(t *testing.T) } } +func TestRemoveWorkload_AbsentPrimaryRequiresNetworkOwnership(t *testing.T) { + t.Parallel() + for _, tt := range []struct { + name string + networkLabels map[string]string + wantDeleted bool + }{ + {name: "unlabelled network"}, + {name: "missing name label", networkLabels: map[string]string{labels.LabelToolHive: labels.LabelToolHiveValue}}, + {name: "missing ownership label", networkLabels: map[string]string{labels.LabelName: "network"}}, + {name: "false ownership label", networkLabels: map[string]string{labels.LabelToolHive: "false", labels.LabelName: "network"}}, + {name: "empty name label", networkLabels: map[string]string{labels.LabelToolHive: labels.LabelToolHiveValue, labels.LabelName: ""}}, + {name: "owned network", wantDeleted: true}, + } { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + var mu sync.Mutex + var deleted []string + client := discoveryHTTPClient(t, func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + defer mu.Unlock() + path := strings.TrimPrefix(r.URL.Path, "/v1.44") + w.Header().Set("Content-Type", "application/json") + switch { + case r.Method == http.MethodDelete: + deleted = append(deleted, path) + w.WriteHeader(http.StatusNoContent) + case path == "/containers/json": + _, _ = w.Write([]byte(`[]`)) + case path == "/networks": + var networks []network.Summary + for _, name := range []string{"toolhive-foo-internal", "toolhive-external"} { + networkLabels := tt.networkLabels + if tt.wantDeleted { + networkLabels = make(map[string]string) + labels.AddNetworkLabels(networkLabels, name) + } + networks = append(networks, network.Summary{Network: network.Network{ + ID: name, Name: name, Labels: networkLabels, + }}) + } + assert.NoError(t, json.NewEncoder(w).Encode(networks)) + default: + t.Errorf("unexpected Docker request: %s %s", r.Method, path) + w.WriteHeader(http.StatusInternalServerError) + } + }) + api := &fakeDockerAPI{ + listFunc: func(context.Context, mobyclient.ContainerListOptions) ([]container.Summary, error) { + return nil, nil + }, + } + c := &Client{api: api, client: client} + + require.NoError(t, c.RemoveWorkload(t.Context(), "foo")) + mu.Lock() + defer mu.Unlock() + if tt.wantDeleted { + assert.Equal(t, []string{"/networks/toolhive-foo-internal", "/networks/toolhive-external"}, deleted) + } else { + assert.Empty(t, deleted, "networks without ToolHive ownership labels must survive removal") + } + }) + } +} + func TestRemoveWorkload_InspectionFailureDoesNotDeleteResources(t *testing.T) { t.Parallel() for _, failureAt := range []string{"lookup", "inspect"} { diff --git a/pkg/process/mocks/mock_process_metadata.go b/pkg/process/mocks/mock_process_metadata.go index 68855bb50d..e4f8a4e55b 100644 --- a/pkg/process/mocks/mock_process_metadata.go +++ b/pkg/process/mocks/mock_process_metadata.go @@ -54,6 +54,21 @@ func (mr *MockProcessMetadataMockRecorder) Cmdline() *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Cmdline", reflect.TypeOf((*MockProcessMetadata)(nil).Cmdline)) } +// CmdlineSlice mocks base method. +func (m *MockProcessMetadata) CmdlineSlice() ([]string, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "CmdlineSlice") + ret0, _ := ret[0].([]string) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// CmdlineSlice indicates an expected call of CmdlineSlice. +func (mr *MockProcessMetadataMockRecorder) CmdlineSlice() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CmdlineSlice", reflect.TypeOf((*MockProcessMetadata)(nil).CmdlineSlice)) +} + // Environ mocks base method. func (m *MockProcessMetadata) Environ() ([]string, error) { m.ctrl.T.Helper() diff --git a/pkg/process/toolhive_proxy.go b/pkg/process/toolhive_proxy.go index f42e54e95b..a445280fa6 100644 --- a/pkg/process/toolhive_proxy.go +++ b/pkg/process/toolhive_proxy.go @@ -21,6 +21,7 @@ const ( type processMetadata interface { Environ() ([]string, error) Cmdline() (string, error) + CmdlineSlice() ([]string, error) Exe() (string, error) } @@ -78,7 +79,8 @@ func IsToolHiveProxyForWorkload(pid int, workloadName string) (bool, error) { // IsTrackedToolHiveProxyForWorkload verifies a PID read from a workload's status. // Detached supervisors must match the workload name. Non-detached ToolHive // run/start/restart supervisors use recorded-PID binding without a process-birth-time check. -// An unnamed run may omit its derived workload name; start/restart include the name. +// An unnamed run may omit its derived workload name. Named runs must match; +// start/restart must include the name or select --all or --group. // Port-discovered PIDs must use IsToolHiveProxyForWorkload instead. func IsTrackedToolHiveProxyForWorkload(pid int, workloadName string) (bool, error) { if pid <= 0 || workloadName == "" { @@ -103,12 +105,46 @@ func isTrackedToolHiveProxyForWorkload(p processMetadata, workloadName string) ( } return cmdlineContainsWorkload(cmdline, workloadName), nil } - cmdline, err := p.Cmdline() + args, err := p.CmdlineSlice() if err != nil { return false, err } - return isToolHiveProcess(p) && (strings.Contains(cmdline, " run ") || strings.Contains(cmdline, " start ") || - strings.Contains(cmdline, " restart ")), nil + if !isToolHiveProcess(p) { + return false, nil + } + for i := 1; i < len(args); i++ { + switch args[i] { + case "run": + return trackedRunMatchesWorkload(args[i+1:], workloadName), nil + case "start", "restart": + return slices.ContainsFunc(args[i+1:], func(arg string) bool { + return arg == workloadName || arg == "--all" || arg == "--group" || strings.HasPrefix(arg, "--group=") + }), nil + } + } + return false, nil +} + +func trackedRunMatchesWorkload(args []string, workloadName string) bool { + named := false + for i := 0; i < len(args); i++ { + switch { + case args[i] == "--name": + named = true + i++ + if i >= len(args) || args[i] != workloadName { + return false + } + case strings.HasPrefix(args[i], "--name="): + named = true + if strings.TrimPrefix(args[i], "--name=") != workloadName { + return false + } + } + } + return named || slices.ContainsFunc(args, func(arg string) bool { + return !strings.HasPrefix(arg, "-") + }) } // isToolHiveProcess returns true if p is a ToolHive process (TOOLHIVE_DETACHED diff --git a/pkg/process/toolhive_proxy_test.go b/pkg/process/toolhive_proxy_test.go index d48819ef56..ee9c231836 100644 --- a/pkg/process/toolhive_proxy_test.go +++ b/pkg/process/toolhive_proxy_test.go @@ -121,10 +121,12 @@ func TestIsTrackedToolHiveProxyForWorkload_MetadataErrors(t *testing.T) { if tt.environErr { metadata.EXPECT().Environ().Return(tt.env, metadataErr) } else { - gomock.InOrder( - metadata.EXPECT().Environ().Return(tt.env, nil), - metadata.EXPECT().Cmdline().Return("/usr/bin/thv start github --foreground", metadataErr), - ) + metadata.EXPECT().Environ().Return(tt.env, nil) + if len(tt.env) > 0 { + metadata.EXPECT().Cmdline().Return("/usr/bin/thv start github --foreground", metadataErr) + } else { + metadata.EXPECT().CmdlineSlice().Return(nil, metadataErr) + } } matched, err := isTrackedToolHiveProxyForWorkload(metadata, "github") @@ -134,6 +136,47 @@ func TestIsTrackedToolHiveProxyForWorkload_MetadataErrors(t *testing.T) { } } +func TestIsTrackedToolHiveProxyForWorkload_ForegroundArguments(t *testing.T) { + t.Parallel() + for _, tt := range []struct { + name string + args []string + expected bool + }{ + {name: "start another workload", args: []string{"thv", "start", "other", "--foreground"}}, + {name: "root flag before run", args: []string{"thv", "--debug", "run", "img", "--name", "demo"}, expected: true}, + {name: "equals name", args: []string{"thv", "run", "img", "--name=demo"}, expected: true}, + {name: "different name", args: []string{"thv", "run", "img", "--name", "other"}}, + {name: "different equals name", args: []string{"thv", "run", "demo", "--name=other"}}, + {name: "missing name value", args: []string{"thv", "run", "img", "--name"}}, + {name: "empty name value", args: []string{"thv", "run", "img", "--name="}}, + {name: "unnamed run", args: []string{"thv", "run", "img"}, expected: true}, + {name: "positional workload", args: []string{"thv", "run", "demo"}, expected: true}, + {name: "run without image", args: []string{"thv", "run"}}, + {name: "start all", args: []string{"thv", "start", "--all", "--foreground"}, expected: true}, + {name: "start group", args: []string{"thv", "start", "--group", "servers"}, expected: true}, + {name: "restart equals group", args: []string{"thv", "restart", "--group=servers"}, expected: true}, + {name: "restart workload", args: []string{"thv", "restart", "demo", "--foreground"}, expected: true}, + {name: "reject partial workload", args: []string{"thv", "start", "demo-extra", "--foreground"}}, + {name: "reject subcommand substring", args: []string{"thv", "serve", "--description= run img"}}, + {name: "skip executable", args: []string{"run", "demo"}}, + {name: "first subcommand wins", args: []string{"thv", "start", "other", "run", "img"}}, + {name: "empty argv"}, + } { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + metadata := mocks.NewMockProcessMetadata(gomock.NewController(t)) + metadata.EXPECT().Environ().Return(nil, nil).Times(2) + metadata.EXPECT().CmdlineSlice().Return(tt.args, nil) + metadata.EXPECT().Exe().Return("/usr/bin/thv", nil) + + matched, err := isTrackedToolHiveProxyForWorkload(metadata, "demo") + require.NoError(t, err) + assert.Equal(t, tt.expected, matched) + }) + } +} + func TestIsTrackedToolHiveProxyForWorkload_ForegroundDoesNotRelaxPortIdentity(t *testing.T) { t.Parallel() diff --git a/pkg/workloads/manager.go b/pkg/workloads/manager.go index dad395a146..71c26ccb43 100644 --- a/pkg/workloads/manager.go +++ b/pkg/workloads/manager.go @@ -100,12 +100,41 @@ type DefaultManager struct { statuses statuses.StatusManager configProvider config.Provider - retryConfig *retryConfig - newRunner mcpRunnerFactory - detachedSpawner detachedProcessSpawner - portFreer portFreer - proxyExitTimeout time.Duration - clientManagerFactory func(context.Context) (client.Manager, error) + retryConfig *retryConfig + newRunner mcpRunnerFactory + detachedSpawner detachedProcessSpawner + portFreer portFreer + proxyExitTimeout time.Duration + clientManagers clientManagerProvider + savedRunConfigs savedRunConfigChecker +} + +// clientManagerProvider creates the client manager used to update MCP client +// configurations when a workload stops, restarts, or is deleted. +type clientManagerProvider interface { + NewClientManager(ctx context.Context) (client.Manager, error) +} + +type defaultClientManagerProvider struct{} + +func (defaultClientManagerProvider) NewClientManager(ctx context.Context) (client.Manager, error) { + return client.NewManager(ctx) +} + +// savedRunConfigChecker reports whether a workload still has a saved run +// configuration. +type savedRunConfigChecker interface { + Exists(ctx context.Context, name string) (bool, error) +} + +type defaultSavedRunConfigChecker struct{} + +func (defaultSavedRunConfigChecker) Exists(ctx context.Context, name string) (bool, error) { + store, err := state.NewRunConfigStore(state.DefaultAppName) + if err != nil { + return false, fmt.Errorf("failed to open run configuration store: %w", err) + } + return store.Exists(ctx, name) } // mcpRunner is the subset of *runner.Runner that RunWorkload's retry loop @@ -181,17 +210,6 @@ func withProxyExitTimeout(timeout time.Duration) managerOption { return func(d *DefaultManager) { d.proxyExitTimeout = timeout } } -func withClientManagerFactory(f func(context.Context) (client.Manager, error)) managerOption { - return func(d *DefaultManager) { d.clientManagerFactory = f } -} - -func (d *DefaultManager) newClientManager(ctx context.Context) (client.Manager, error) { - if d.clientManagerFactory != nil { - return d.clientManagerFactory(ctx) - } - return client.NewManager(ctx) -} - func (d *DefaultManager) proxyExitTimeoutOrDefault() time.Duration { if d.proxyExitTimeout > 0 { return d.proxyExitTimeout @@ -259,9 +277,11 @@ func NewManager(ctx context.Context) (*DefaultManager, error) { } return &DefaultManager{ - runtime: runtime, - statuses: statusManager, - configProvider: config.NewDefaultProvider(), + runtime: runtime, + statuses: statusManager, + configProvider: config.NewDefaultProvider(), + clientManagers: defaultClientManagerProvider{}, + savedRunConfigs: defaultSavedRunConfigChecker{}, }, nil } @@ -278,9 +298,11 @@ func NewManagerWithProvider(ctx context.Context, configProvider config.Provider) } return &DefaultManager{ - runtime: runtime, - statuses: statusManager, - configProvider: configProvider, + runtime: runtime, + statuses: statusManager, + configProvider: configProvider, + clientManagers: defaultClientManagerProvider{}, + savedRunConfigs: defaultSavedRunConfigChecker{}, }, nil } @@ -292,9 +314,11 @@ func NewManagerFromRuntime(runtime rt.Runtime) (Manager, error) { } return &DefaultManager{ - runtime: runtime, - statuses: statusManager, - configProvider: config.NewDefaultProvider(), + runtime: runtime, + statuses: statusManager, + configProvider: config.NewDefaultProvider(), + clientManagers: defaultClientManagerProvider{}, + savedRunConfigs: defaultSavedRunConfigChecker{}, }, nil } @@ -307,9 +331,11 @@ func NewManagerFromRuntimeWithProvider(runtime rt.Runtime, configProvider config } return &DefaultManager{ - runtime: runtime, - statuses: statusManager, - configProvider: configProvider, + runtime: runtime, + statuses: statusManager, + configProvider: configProvider, + clientManagers: defaultClientManagerProvider{}, + savedRunConfigs: defaultSavedRunConfigChecker{}, }, nil } @@ -524,7 +550,7 @@ func (d *DefaultManager) stopRemoteWorkload(ctx context.Context, name string, ru } func (d *DefaultManager) finishRemoteWorkloadStop(ctx context.Context, name string, runConfig *runner.RunConfig) error { - exists, err := savedWorkloadStillExists(ctx, name, runConfig, false) + exists, err := d.savedWorkloadStillExists(ctx, name, runConfig, false) if err != nil { return err } @@ -547,15 +573,13 @@ func (d *DefaultManager) finishRemoteWorkloadStop(ctx context.Context, name stri // Recheck after cleanup so stop does not recreate its status or repeat client // cleanup for a deleted workload. Auxiliary/no-config paths retain // their existing behavior because they need not have their own saved state. -func savedWorkloadStillExists(ctx context.Context, name string, runConfig *runner.RunConfig, isAuxiliary bool) (bool, error) { +func (d *DefaultManager) savedWorkloadStillExists( + ctx context.Context, name string, runConfig *runner.RunConfig, isAuxiliary bool, +) (bool, error) { if runConfig == nil || isAuxiliary { return true, nil } - store, err := state.NewRunConfigStore(state.DefaultAppName) - if err != nil { - return false, fmt.Errorf("failed to open run configuration store after stop: %w", err) - } - exists, err := store.Exists(ctx, cmp.Or(runConfig.BaseName, name)) + exists, err := d.savedRunConfigs.Exists(ctx, cmp.Or(runConfig.BaseName, name)) if err != nil { return false, fmt.Errorf("failed to check saved workload after stop: %w", err) } @@ -567,6 +591,7 @@ func savedWorkloadStillExists(ctx context.Context, name string, runConfig *runne // if the container is missing and enables port-based proxy cleanup. func (d *DefaultManager) stopContainerWorkload(ctx context.Context, name string, runConfig *runner.RunConfig) error { container, err := d.runtime.GetWorkloadInfo(ctx, name) + found := err == nil if err != nil { if !errors.Is(err, rt.ErrWorkloadNotFound) { return fmt.Errorf("failed to find workload %s: %w", name, err) @@ -591,14 +616,22 @@ func (d *DefaultManager) stopContainerWorkload(ctx context.Context, name string, } } - // Transition workload to `stopping` state. - if err := d.statuses.SetWorkloadStatus(ctx, name, rt.WorkloadStatusStopping, ""); err != nil { - slog.Debug("failed to set workload status to stopping", "workload", name, "error", err) + // Only a running container or a recorded supervisor gives stop 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.isSupervisorProcessAlive(ctx, labels.GetContainerBaseName(container.Labels)) + if live { + if err := d.statuses.SetWorkloadStatus(ctx, name, rt.WorkloadStatusStopping, ""); err != nil { + slog.Debug("failed to set workload status to stopping", "workload", name, "error", err) + } + } else { + slog.Warn("Failed to stop workload", "workload", name, "error", ErrWorkloadNotRunning) } // Clean up the proxy before stopping by name, even if the initial container // was exited or missing: its supervisor may have recreated it since inspection. - return d.stopSingleContainerWorkload(ctx, &container, runConfig) + return d.stopSingleContainerWorkload(ctx, &container, runConfig, live) } // RunWorkload runs a workload in the foreground with automatic restart on container exit. @@ -713,10 +746,17 @@ func (d *DefaultManager) finishWorkloadRun(ctx context.Context, name string, run if err := d.statuses.ResetWorkloadPIDIfMatch(cleanupCtx, name, os.Getpid()); err != nil { slog.Warn("failed to reset workload PID", "workload", name, "error", err) } - if ctx.Err() != nil { - return nil + if ctx.Err() == nil { + return runErr } - return runErr + // A cancellation that does not come from stop or delete (for example + // SIGTERM or Ctrl-C) would otherwise leave the status at starting or + // running. The guarded write leaves newer statuses and replacement + // supervisors alone. + if err := d.statuses.SetWorkloadStoppedIfOwned(cleanupCtx, name, os.Getpid()); err != nil { + slog.Warn("failed to set workload status to stopped", "workload", name, "error", err) + } + return nil } func (d *DefaultManager) recordWorkloadRunFailure(ctx context.Context, name, reason string) { @@ -731,7 +771,7 @@ func (d *DefaultManager) recordWorkloadRunFailure(ctx context.Context, name, rea // prepareWorkloadRestart removes stale client configuration and records that // the workload is restarting, unless shutdown interrupted client cleanup. func (d *DefaultManager) prepareWorkloadRestart(ctx context.Context, runConfig *runner.RunConfig, stable bool) { - clientManager, err := d.newClientManager(ctx) + clientManager, err := d.clientManagers.NewClientManager(ctx) if err == nil { slog.Debug("removing from client configurations before restart", "workload", runConfig.BaseName) if err := clientManager.RemoveServerFromClients(ctx, runConfig.BaseName, runConfig.Group); err != nil { @@ -1082,13 +1122,7 @@ func (d *DefaultManager) deleteContainerWorkload(ctx context.Context, name strin slog.Debug("skipping proxy-runner stop for auxiliary workload", "workload", name) } - // Always perform a fresh removal: a container absent during inspection may - // have been created in flight before the supervisor stopped. - runtimeName := name - if container == nil && runConfig != nil && runConfig.ContainerName != "" { - runtimeName = runConfig.ContainerName - } - if err := d.removeContainer(ctx, name, runtimeName); err != nil { + if err := d.removeWorkloadContainer(ctx, name, container, runConfig); err != nil { return err } @@ -1103,6 +1137,39 @@ func (d *DefaultManager) deleteContainerWorkload(ctx context.Context, name strin return nil } +// removeWorkloadContainer removes the workload's container during delete. +// container is the result of the initial lookup and may be nil. +func (d *DefaultManager) removeWorkloadContainer( + ctx context.Context, name string, container *rt.ContainerInfo, runConfig *runner.RunConfig, +) error { + if container == nil && runConfig == nil { + // Nothing identifies a container to remove; only the state cleanup applies. + slog.Debug("container not found for workload, proceeding with state cleanup", "workload", name) + return nil + } + + runtimeName := name + if container != nil { + runtimeName = cmp.Or(container.Name, name) + } else if runConfig.ContainerName != "" { + runtimeName = runConfig.ContainerName + } + + // Remove even when the saved container was absent during inspection: the + // supervisor may have created it in flight before it stopped. + err := d.removeContainer(ctx, name, runtimeName) + if err == nil || container != nil { + return err + } + if _, lookupErr := d.runtime.GetWorkloadInfo(ctx, runtimeName); errors.Is(lookupErr, rt.ErrWorkloadNotFound) || + errors.Is(lookupErr, rt.ErrContainerNotFound) { + slog.Warn("container removal failed but no container exists, continuing with state cleanup", + "workload", name, "container", runtimeName, "error", err) + return nil + } + return err +} + // getWorkloadContainer retrieves workload container info with error handling func (d *DefaultManager) getWorkloadContainer(ctx context.Context, name string) (*rt.ContainerInfo, error) { container, err := d.runtime.GetWorkloadInfo(ctx, name) @@ -1142,20 +1209,33 @@ func (d *DefaultManager) isSupervisorProcessAlive(ctx context.Context, name stri return true } -// stopProcess stops the proxy process associated with the container. It reports -// whether a verified proxy exited after termination. A false return signals -// callers to try port-based cleanup. Unverified PIDs are cleared only if the -// process is confirmed gone; otherwise they remain available for a later retry. -func (d *DefaultManager) stopProcess(ctx context.Context, name string) bool { +// proxyStopResult describes the outcome of stopping a tracked proxy PID. +type proxyStopResult int + +const ( + // proxyNotStopped means no verified proxy was signalled, so callers may + // fall back to port-based cleanup. + proxyNotStopped proxyStopResult = iota + // proxyStopped means the verified proxy was signalled and has exited. + proxyStopped + // proxyExiting means the verified proxy was signalled but had not exited + // when the wait timed out. Signalling it again would not help. + proxyExiting +) + +// stopProcess stops the proxy process associated with the container. +// Unverified PIDs are cleared only if the process is confirmed gone; otherwise +// they remain available for a later retry. +func (d *DefaultManager) stopProcess(ctx context.Context, name string) proxyStopResult { if name == "" { slog.Warn("could not find base container name in labels") - return false + return proxyNotStopped } pid, err := d.statuses.GetWorkloadPID(ctx, name) if err != nil || pid <= 0 { slog.Debug("no PID found, proxy may not be running in detached mode", "workload", name) - return false + return proxyNotStopped } // Foreground runs rely on the status entry for workload binding; detached @@ -1166,31 +1246,31 @@ func (d *DefaultManager) stopProcess(ctx context.Context, name string) bool { if findErr != nil || alive { slog.Warn("could not verify tracked proxy identity, preserving PID without signaling", "workload", name, "pid", pid, "identityError", err, "error", findErr) - return false + return proxyNotStopped } slog.Debug("tracked proxy is gone, clearing PID", "workload", name, "pid", pid) if err := d.statuses.ResetWorkloadPIDIfMatch(ctx, name, pid); err != nil { slog.Warn("failed to reset workload PID", "workload", name, "error", err) } - return false + return proxyNotStopped } return d.stopVerifiedProxy(ctx, name, pid, process.KillProcess) } // stopVerifiedProxy terminates a proxy whose identity the caller has verified. -func (d *DefaultManager) stopVerifiedProxy(ctx context.Context, name string, pid int, signal func(int) error) bool { +func (d *DefaultManager) stopVerifiedProxy(ctx context.Context, name string, pid int, signal func(int) error) proxyStopResult { slog.Debug("stopping proxy process", "workload", name, "pid", pid) if err := signal(pid); err != nil { slog.Debug("failed to kill proxy process", "error", err) - return false + return proxyNotStopped } waitCtx, cancel := context.WithTimeout(ctx, d.proxyExitTimeoutOrDefault()) defer cancel() if err := process.WaitForExit(waitCtx, pid); err != nil { - slog.Warn("failed waiting for proxy process to exit", "workload", name, "pid", pid, "error", err) - return false + slog.Warn("proxy process is still exiting after signal", "workload", name, "pid", pid, "error", err) + return proxyExiting } slog.Debug("proxy process stopped", "workload", name, "pid", pid) @@ -1198,33 +1278,31 @@ func (d *DefaultManager) stopVerifiedProxy(ctx context.Context, name string, pid slog.Warn("failed to reset workload PID", "workload", name, "error", err) } - return true + return proxyStopped } -// stopProxyIfNeeded stops the proxy process if the workload has a base name. It -// reports whether a tracked proxy process was stopped (see stopProcess); false -// when there is no base name or no proxy was killed. -func (d *DefaultManager) stopProxyIfNeeded(ctx context.Context, name, baseName string) bool { +// stopProxyIfNeeded stops the proxy process if the workload has a base name +// (see stopProcess). +func (d *DefaultManager) stopProxyIfNeeded(ctx context.Context, name, baseName string) proxyStopResult { slog.Debug("removing proxy process", "workload", name) if baseName == "" { - return false + return proxyNotStopped } return d.stopProcess(ctx, baseName) } // ensureProxyStopped makes a best-effort attempt to stop the workload's proxy // and free its port. -// It first stops the tracked PID (stopProxyIfNeeded); if that does not stop a -// proxy — no PID is recorded, identity verification fails, or termination does -// not complete — it falls back to port-based cleanup, which only kills a process -// verified to be this workload's own proxy. -// On Unix, a timed-out wait can result in another SIGTERM via the fallback, but -// neither path escalates to SIGKILL. Windows uses hard TerminateProcess instead. +// It first stops the tracked PID (stopProxyIfNeeded). If no verified proxy was +// signalled — no PID is recorded, identity verification fails, or the signal +// fails — it falls back to port-based cleanup, which only kills a process +// verified to be this workload's own proxy. A proxy that was signalled but is +// still exiting is not signalled again. // runConfig may be nil (no port fallback then). Used by the stop and delete // paths; the restart path instead frees the port itself, just before the child // re-binds. func (d *DefaultManager) ensureProxyStopped(ctx context.Context, name, baseName string, runConfig *runner.RunConfig) { - if !d.stopProxyIfNeeded(ctx, name, baseName) { + if d.stopProxyIfNeeded(ctx, name, baseName) == proxyNotStopped { d.portFreerOrDefault()(ctx, runConfig) } } @@ -1646,7 +1724,7 @@ func (d *DefaultManager) maybeSetupContainerWorkload(ctx context.Context, name s // Stop the supervisor process (proxy) if it exists (may already be dead) // This ensures we clean up any orphaned supervisor processes if !labels.IsAuxiliaryWorkload(container.Labels) { - d.stopProcess(ctx, workloadName) + d.stopOtherSupervisor(ctx, workloadName) } // Now stop the container if it's running @@ -1669,6 +1747,11 @@ func (d *DefaultManager) maybeSetupContainerWorkload(ctx context.Context, name s if err := d.statuses.SetWorkloadStatus(ctx, workloadName, rt.WorkloadStatusStopped, ""); err != nil { slog.Debug("Failed to set workload status to stopped", "workload", workloadName, "error", err) } + } else if !labels.IsAuxiliaryWorkload(container.Labels) { + // A supervisor can still be alive in restart backoff while the status + // is starting and the container has exited. Stop it so two supervisors + // do not manage the same workload. + d.stopOtherSupervisor(ctx, workloadName) } // Load runner configuration from state @@ -1696,6 +1779,17 @@ func (d *DefaultManager) maybeSetupContainerWorkload(ctx context.Context, name s return workloadName, mcpRunner, nil } +// stopOtherSupervisor stops the supervisor recorded for the workload unless it +// is this process, which happens when a detached `start --foreground` child +// sets up its own workload. +func (d *DefaultManager) stopOtherSupervisor(ctx context.Context, name string) { + pid, err := d.statuses.GetWorkloadPID(ctx, name) + if err != nil || pid <= 0 || pid == os.Getpid() { + return + } + d.stopProcess(ctx, name) +} + // startWorkload starts the workload in either foreground or background mode func (d *DefaultManager) startWorkload(ctx context.Context, name string, mcpRunner *runner.Runner, foreground bool) error { slog.Debug("starting tooling server", "workload", name) @@ -1736,7 +1830,7 @@ func (d *DefaultManager) removeClientConfigurations(containerName string, isAuxi group = runConfig.Group } - clientManager, err := d.newClientManager(context.Background()) + clientManager, err := d.clientManagers.NewClientManager(context.Background()) if err != nil { slog.Warn("failed to create client manager, skipping client config removal", "workload", containerName, "error", err) return nil @@ -1798,9 +1892,10 @@ func (*DefaultManager) cleanupTempPermissionProfile(ctx context.Context, baseNam // stopSingleContainerWorkload stops a single container workload. runConfig may // be nil; when present it lets stop fall back to port-based proxy cleanup if the -// tracked PID is unavailable (e.g. a missing status file). +// tracked PID is unavailable (e.g. a missing status file). The stopped status +// and client-configuration cleanup only apply when live is true. func (d *DefaultManager) stopSingleContainerWorkload( - ctx context.Context, workload *rt.ContainerInfo, runConfig *runner.RunConfig, + ctx context.Context, workload *rt.ContainerInfo, runConfig *runner.RunConfig, live bool, ) error { childCtx, cancel := context.WithTimeout(context.Background(), AsyncOperationTimeout) defer cancel() @@ -1817,7 +1912,7 @@ func (d *DefaultManager) stopSingleContainerWorkload( slog.Debug("stopping containers", "workload", name) // Stop the container stopErr := d.runtime.StopWorkload(childCtx, workload.Name) - exists, err := savedWorkloadStillExists(childCtx, name, runConfig, isAuxiliary) + exists, err := d.savedWorkloadStillExists(childCtx, name, runConfig, isAuxiliary) if err != nil { return errors.Join(err, stopErr) } @@ -1829,7 +1924,7 @@ func (d *DefaultManager) stopSingleContainerWorkload( } return fmt.Errorf("failed to stop container: %w", stopErr) } - if !exists { + if !exists || !live { return nil } diff --git a/pkg/workloads/manager_coverage_test.go b/pkg/workloads/manager_coverage_test.go index fdf34e210d..b52cea622c 100644 --- a/pkg/workloads/manager_coverage_test.go +++ b/pkg/workloads/manager_coverage_test.go @@ -11,6 +11,7 @@ import ( "os" "os/exec" "path/filepath" + goruntime "runtime" "strings" "testing" "time" @@ -112,12 +113,12 @@ func TestDefaultManager_prepareWorkloadRestart_ClientCleanup(t *testing.T) { sm.EXPECT().SetWorkloadStatus(ctx, name, runtime.WorkloadStatusStarting, reason).Return(nil) } manager := &DefaultManager{statuses: sm} - withClientManagerFactory(func(context.Context) (client.Manager, error) { + manager.clientManagers = testClientManagerProvider(func(context.Context) (client.Manager, error) { if tt.factoryError { return nil, errors.New("client manager unavailable") } return cm, nil - })(manager) + }) manager.prepareWorkloadRestart(ctx, &runner.RunConfig{BaseName: name, Group: group}, tt.stable) if tt.cancelCleanup || tt.preCancelled { @@ -142,13 +143,16 @@ func TestDefaultManager_StopCleanupErrorsDoNotPreventStopped(t *testing.T) { sm := statusMocks.NewMockStatusManager(ctrl) cm := clientMocks.NewMockManager(ctrl) rm := runtimeMocks.NewMockRuntime(ctrl) - manager := &DefaultManager{statuses: sm, runtime: rm} - withClientManagerFactory(func(context.Context) (client.Manager, error) { + manager := &DefaultManager{ + savedRunConfigs: testSavedRunConfigChecker{exists: true}, + statuses: sm, runtime: rm, + } + manager.clientManagers = testClientManagerProvider(func(context.Context) (client.Manager, error) { if factoryError { return nil, errors.New("client manager unavailable") } return cm, nil - })(manager) + }) var cleanupCall *gomock.Call if !factoryError { cleanupCall = cm.EXPECT().RemoveServerFromClients(gomock.Any(), name, group). @@ -171,7 +175,7 @@ func TestDefaultManager_StopCleanupErrorsDoNotPreventStopped(t *testing.T) { } require.NoError(t, manager.stopSingleContainerWorkload(ctx, &runtime.ContainerInfo{ Name: name, Labels: map[string]string{labels.LabelBaseName: name}, - }, rc)) + }, rc, true)) }) } } @@ -191,11 +195,31 @@ func TestDefaultManager_stopVerifiedProxy_SignalErrorPreservesPID(t *testing.T) return errors.New("process signal failed") } - require.False(t, manager.stopVerifiedProxy(ctx, name, pid, signal), "a failed signal must not reset the saved PID") + require.Equal(t, proxyNotStopped, manager.stopVerifiedProxy(ctx, name, pid, signal), "a failed signal must not reset the saved PID") require.True(t, signalled) } +func TestDefaultManager_stopVerifiedProxy_ExitTimeout(t *testing.T) { + t.Parallel() + const name = "signalled-but-exiting" + proxy := startProxyProcess(t, name, true) + sm := statusMocks.NewMockStatusManager(gomock.NewController(t)) + manager := &DefaultManager{statuses: sm} + withProxyExitTimeout(50 * time.Millisecond)(manager) + + result := manager.stopVerifiedProxy(context.Background(), name, proxy.pid, process.KillProcess) + require.Equal(t, proxyExiting, result) + select { + case <-proxy.exited: + t.Error("SIGTERM-ignoring proxy unexpectedly exited") + default: + } +} + func TestDefaultManager_spawnDetached_ReapsOwnedChildren(t *testing.T) { + if goruntime.GOOS == "windows" { + t.Skip("detached fixture requires Unix process reaping") + } isolateWorkloadStopState(t) t.Setenv(process.ToolHiveDetachedEnv, "") for _, mode := range []string{"clean", "error"} { diff --git a/pkg/workloads/manager_delete_test.go b/pkg/workloads/manager_delete_test.go index a3b5c46d62..faab53d207 100644 --- a/pkg/workloads/manager_delete_test.go +++ b/pkg/workloads/manager_delete_test.go @@ -66,10 +66,7 @@ func TestDefaultManager_deleteContainerWorkload_StopsSupervisorBeforeFreshRemova return proxy.pid, nil }) sm.EXPECT().ResetWorkloadPIDIfMatch(gomock.Any(), name, proxy.pid).Return(nil) - removalName := name - if tt.missingErr != nil { - removalName = containerName - } + removalName := containerName rtMock.EXPECT().RemoveWorkload(gomock.Any(), removalName).DoAndReturn(func(context.Context, string) error { alive, err := process.FindProcess(proxy.pid) require.NoError(t, err) @@ -88,13 +85,18 @@ func TestDefaultManager_deleteContainerWorkload_StopsSupervisorBeforeFreshRemova return tt.removeErr }) if tt.removeErr != nil { + rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), removalName).Return(runtime.ContainerInfo{Name: containerName}, nil) sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusError, tt.removeErr.Error()).Return(nil) } else { rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), removalName). Return(runtime.ContainerInfo{}, fmt.Errorf("removal verification: %w", tt.verifiedErr)) sm.EXPECT().DeleteWorkloadStatus(gomock.Any(), name).Return(nil) } - manager := &DefaultManager{runtime: rtMock, statuses: sm} + manager := &DefaultManager{ + clientManagers: testClientManagerProvider(unavailableClientManager), + runtime: rtMock, + statuses: sm, + } withPortFreer(func(context.Context, *runner.RunConfig) { t.Error("verified supervisor exit must not need port fallback") })(manager) @@ -136,7 +138,11 @@ func TestDefaultManager_deleteContainerWorkload_AuxiliaryDoesNotStopSupervisorOr rtMock.EXPECT().RemoveWorkload(gomock.Any(), auxiliary).Return(nil) rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), auxiliary).Return(runtime.ContainerInfo{}, runtime.ErrWorkloadNotFound) sm.EXPECT().DeleteWorkloadStatus(gomock.Any(), auxiliary).Return(nil) - manager := &DefaultManager{runtime: rtMock, statuses: sm} + manager := &DefaultManager{ + clientManagers: testClientManagerProvider(unavailableClientManager), + runtime: rtMock, + statuses: sm, + } withPortFreer(func(context.Context, *runner.RunConfig) { t.Error("auxiliary deletion must not clean up parent proxy") })(manager) require.NoError(t, manager.deleteContainerWorkload(ctx, auxiliary, nil)) @@ -152,3 +158,80 @@ func TestDefaultManager_deleteContainerWorkload_AuxiliaryDoesNotStopSupervisorOr require.NoError(t, err) assert.Equal(t, saved, after) } + +//nolint:paralleltest // deletion reads and removes saved state +func TestDefaultManager_deleteContainerWorkload_MissingContainer(t *testing.T) { + isolateWorkloadStopState(t) + removeErr := errors.New("runtime removal failed") + verifyErr := errors.New("runtime inspection failed") + for _, tt := range []struct { + name string + saved bool + removeErr error + verifyErr error + appeared bool + }{ + {name: "no saved configuration skips runtime removal"}, + {name: "failed removal with no remaining container deletes saved state", saved: true, removeErr: removeErr}, + {name: "container appearing after failed removal preserves saved state", saved: true, removeErr: removeErr, appeared: true}, + {name: "failed verification with no remaining container deletes saved state", saved: true, verifyErr: verifyErr}, + {name: "container appearing after failed verification preserves saved state", saved: true, verifyErr: verifyErr, appeared: true}, + } { + t.Run(tt.name, func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + t.Cleanup(cancel) + const name = "missing-delete-workload" + const containerName = "missing-delete-workload-20260101" + var rc *runner.RunConfig + if tt.saved { + rc = &runner.RunConfig{BaseName: name, ContainerName: containerName} + persistStopRunConfig(t, name, rc) + } + ctrl := gomock.NewController(t) + rtMock := runtimeMocks.NewMockRuntime(ctrl) + sm := statusMocks.NewMockStatusManager(ctrl) + rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), name).Return(runtime.ContainerInfo{}, runtime.ErrWorkloadNotFound) + sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusRemoving, "").Return(nil) + sm.EXPECT().GetWorkloadPID(gomock.Any(), name).Return(0, nil) + if tt.saved { + rtMock.EXPECT().RemoveWorkload(gomock.Any(), containerName).Return(tt.removeErr) + if tt.removeErr != nil { + sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusError, tt.removeErr.Error()).Return(nil) + } else { + rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), containerName).Return(runtime.ContainerInfo{}, tt.verifyErr) + } + if tt.appeared { + rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), containerName).Return(runtime.ContainerInfo{Name: containerName}, nil) + } else { + rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), containerName).Return(runtime.ContainerInfo{}, runtime.ErrContainerNotFound) + } + } + if !tt.appeared { + sm.EXPECT().DeleteWorkloadStatus(gomock.Any(), name).Return(nil) + } + fallbackCalls := 0 + manager := &DefaultManager{ + runtime: rtMock, + statuses: sm, + clientManagers: testClientManagerProvider(unavailableClientManager), + } + withPortFreer(func(context.Context, *runner.RunConfig) { fallbackCalls++ })(manager) + + err := manager.deleteContainerWorkload(ctx, name, rc) + assert.Equal(t, 1, fallbackCalls, "missing containers must not suppress orphan proxy cleanup") + if tt.appeared { + if tt.removeErr != nil { + require.ErrorIs(t, err, tt.removeErr) + } else { + require.ErrorIs(t, err, tt.verifyErr) + } + _, loadErr := runner.LoadState(ctx, name) + require.NoError(t, loadErr, "failed deletion must retain recovery state") + } else { + require.NoError(t, err) + _, loadErr := runner.LoadState(ctx, name) + require.Error(t, loadErr, "successful deletion must remove saved state") + } + }) + } +} diff --git a/pkg/workloads/manager_test.go b/pkg/workloads/manager_test.go index 19d5ea9f4d..a448579971 100644 --- a/pkg/workloads/manager_test.go +++ b/pkg/workloads/manager_test.go @@ -27,6 +27,7 @@ import ( "go.uber.org/mock/gomock" "github.com/stacklok/toolhive/pkg/client" + clientMocks "github.com/stacklok/toolhive/pkg/client/mocks" "github.com/stacklok/toolhive/pkg/config" configMocks "github.com/stacklok/toolhive/pkg/config/mocks" "github.com/stacklok/toolhive/pkg/container/runtime" @@ -43,6 +44,25 @@ import ( statusMocks "github.com/stacklok/toolhive/pkg/workloads/statuses/mocks" ) +type testClientManagerProvider func(context.Context) (client.Manager, error) + +func (f testClientManagerProvider) NewClientManager(ctx context.Context) (client.Manager, error) { + return f(ctx) +} + +func unavailableClientManager(context.Context) (client.Manager, error) { + return nil, errors.New("client manager unavailable") +} + +type testSavedRunConfigChecker struct { + exists bool + err error +} + +func (f testSavedRunConfigChecker) Exists(context.Context, string) (bool, error) { + return f.exists, f.err +} + func TestDefaultManager_ListWorkloadsInGroup(t *testing.T) { t.Parallel() @@ -754,7 +774,9 @@ func TestDefaultManager_restartRemoteWorkload(t *testing.T) { tt.setupMocks(statusMgr) manager := &DefaultManager{ - statuses: statusMgr, + savedRunConfigs: testSavedRunConfigChecker{exists: true}, + clientManagers: testClientManagerProvider(unavailableClientManager), + statuses: statusMgr, } err := manager.restartRemoteWorkload(context.Background(), tt.workloadName, tt.runConfig, tt.foreground) @@ -869,8 +891,9 @@ func TestDefaultManager_restartContainerWorkload(t *testing.T) { tt.setupMocks(statusMgr, runtimeMgr) manager := &DefaultManager{ - statuses: statusMgr, - runtime: runtimeMgr, + clientManagers: testClientManagerProvider(unavailableClientManager), + statuses: statusMgr, + runtime: runtimeMgr, } err := manager.restartContainerWorkload(context.Background(), tt.workloadName, tt.foreground) @@ -907,7 +930,9 @@ func TestDefaultManager_restartLogicConsistency(t *testing.T) { statusMgr.EXPECT().GetWorkloadPID(gomock.Any(), "test-base").Return(12345, nil) manager := &DefaultManager{ - statuses: statusMgr, + savedRunConfigs: testSavedRunConfigChecker{exists: true}, + clientManagers: testClientManagerProvider(unavailableClientManager), + statuses: statusMgr, } runConfig := &runner.RunConfig{ @@ -939,7 +964,9 @@ func TestDefaultManager_restartLogicConsistency(t *testing.T) { statusMgr.EXPECT().SetWorkloadPID(gomock.Any(), gomock.Any(), gomock.Any()).AnyTimes().Return(nil) manager := &DefaultManager{ - statuses: statusMgr, + savedRunConfigs: testSavedRunConfigChecker{exists: true}, + clientManagers: testClientManagerProvider(unavailableClientManager), + statuses: statusMgr, } runConfig := &runner.RunConfig{ @@ -974,7 +1001,9 @@ func TestDefaultManager_restartLogicConsistency(t *testing.T) { statusMgr.EXPECT().SetWorkloadPID(gomock.Any(), gomock.Any(), gomock.Any()).AnyTimes().Return(nil) manager := &DefaultManager{ - statuses: statusMgr, + savedRunConfigs: testSavedRunConfigChecker{exists: true}, + clientManagers: testClientManagerProvider(unavailableClientManager), + statuses: statusMgr, } runConfig := &runner.RunConfig{ @@ -1013,8 +1042,10 @@ func TestDefaultManager_restartLogicConsistency(t *testing.T) { statusMgr.EXPECT().GetWorkloadPID(gomock.Any(), "test-workload").Return(12345, nil) manager := &DefaultManager{ - statuses: statusMgr, - runtime: runtimeMgr, + savedRunConfigs: testSavedRunConfigChecker{exists: true}, + clientManagers: testClientManagerProvider(unavailableClientManager), + statuses: statusMgr, + runtime: runtimeMgr, } err := manager.restartContainerWorkload(context.Background(), "test-workload", false) @@ -1058,8 +1089,10 @@ func TestDefaultManager_restartLogicConsistency(t *testing.T) { statusMgr.EXPECT().SetWorkloadPID(gomock.Any(), gomock.Any(), gomock.Any()).AnyTimes().Return(nil) manager := &DefaultManager{ - statuses: statusMgr, - runtime: runtimeMgr, + savedRunConfigs: testSavedRunConfigChecker{exists: true}, + clientManagers: testClientManagerProvider(unavailableClientManager), + statuses: statusMgr, + runtime: runtimeMgr, } _ = manager.restartContainerWorkload(context.Background(), "test-workload", false) @@ -1102,8 +1135,10 @@ func TestDefaultManager_restartLogicConsistency(t *testing.T) { statusMgr.EXPECT().SetWorkloadPID(gomock.Any(), gomock.Any(), gomock.Any()).AnyTimes().Return(nil) manager := &DefaultManager{ - statuses: statusMgr, - runtime: runtimeMgr, + savedRunConfigs: testSavedRunConfigChecker{exists: true}, + clientManagers: testClientManagerProvider(unavailableClientManager), + statuses: statusMgr, + runtime: runtimeMgr, } _ = manager.restartContainerWorkload(context.Background(), "test-workload", false) @@ -1220,9 +1255,9 @@ func (f *fakeRunnerFactory) factory() mcpRunnerFactory { } } -func expectSupervisorPIDCleanup(t *testing.T, sm *statusMocks.MockStatusManager, name string) { +func expectSupervisorPIDCleanup(t *testing.T, sm *statusMocks.MockStatusManager, name string) *gomock.Call { t.Helper() - sm.EXPECT().ResetWorkloadPIDIfMatch(gomock.Any(), name, os.Getpid()). + return sm.EXPECT().ResetWorkloadPIDIfMatch(gomock.Any(), name, os.Getpid()). DoAndReturn(func(ctx context.Context, _ string, _ int) error { assert.NoError(t, ctx.Err(), "PID cleanup must survive supervisor cancellation") _, bounded := ctx.Deadline() @@ -1231,9 +1266,20 @@ func expectSupervisorPIDCleanup(t *testing.T, sm *statusMocks.MockStatusManager, }) } -//nolint:paralleltest // client configuration isolation uses t.Setenv +func expectSupervisorCancellationCleanup(t *testing.T, sm *statusMocks.MockStatusManager, name string) { + t.Helper() + resetPID := expectSupervisorPIDCleanup(t, sm, name) + sm.EXPECT().SetWorkloadStoppedIfOwned(gomock.Any(), name, os.Getpid()).After(resetPID). + DoAndReturn(func(ctx context.Context, _ string, _ int) error { + assert.NoError(t, ctx.Err(), "status cleanup must survive supervisor cancellation") + _, bounded := ctx.Deadline() + assert.True(t, bounded, "status cleanup must not wait indefinitely") + return nil + }) +} + func TestDefaultManager_RunWorkload_CancellationInterruptsBackoff(t *testing.T) { - isolateWorkloadStopState(t) + t.Parallel() ctrl := gomock.NewController(t) sm := statusMocks.NewMockStatusManager(ctrl) @@ -1246,9 +1292,12 @@ func TestDefaultManager_RunWorkload_CancellationInterruptsBackoff(t *testing.T) return nil }) // No Error status write is allowed after a user requests shutdown. - expectSupervisorPIDCleanup(t, sm, name) + expectSupervisorCancellationCleanup(t, sm, name) factory := &fakeRunnerFactory{outcomes: []fakeRunOutcome{{err: runner.ErrContainerExitedRestartNeeded}}} - manager := &DefaultManager{statuses: sm} + manager := &DefaultManager{ + clientManagers: testClientManagerProvider(unavailableClientManager), + statuses: sm, + } withRunnerFactory(factory.factory())(manager) withRetryConfig(retryConfig{ maxRetries: 3, initialDelay: 30 * time.Second, @@ -1288,7 +1337,7 @@ func TestDefaultManager_RunWorkload_CancelledSupervisorClearsOnlyItsOwnPID(t *te sm := statusMocks.NewMockStatusManager(ctrl) // The guarded API must receive this supervisor's PID, never a replacement's // PID read from storage or an unconditional reset. - expectSupervisorPIDCleanup(t, sm, name) + expectSupervisorCancellationCleanup(t, sm, name) manager := &DefaultManager{statuses: sm} withRunnerFactory(func(*runner.RunConfig, statuses.StatusManager) mcpRunner { t.Error("cancelled supervisor must not create a runner") @@ -1324,12 +1373,12 @@ func TestDefaultManager_RunWorkload_CancellationPreventsFurtherAttempts(t *testi return nil }) } - expectSupervisorPIDCleanup(t, sm, name) + expectSupervisorCancellationCleanup(t, sm, name) attempts := 0 manager := &DefaultManager{statuses: sm} - withClientManagerFactory(func(context.Context) (client.Manager, error) { + manager.clientManagers = testClientManagerProvider(func(context.Context) (client.Manager, error) { return nil, errors.New("client manager unavailable") - })(manager) + }) withRunnerFactory(func(*runner.RunConfig, statuses.StatusManager) mcpRunner { attempts++ if stage == "runner" { @@ -1401,9 +1450,9 @@ func TestDefaultManager_RunWorkload_RestartStatusFailureDoesNotConsumeExtraAttem expectSupervisorPIDCleanup(t, sm, name) factory := &fakeRunnerFactory{outcomes: []fakeRunOutcome{{err: runner.ErrContainerExitedRestartNeeded}, {}}} manager := &DefaultManager{statuses: sm} - withClientManagerFactory(func(context.Context) (client.Manager, error) { + manager.clientManagers = testClientManagerProvider(func(context.Context) (client.Manager, error) { return nil, errors.New("client manager unavailable") - })(manager) + }) withRunnerFactory(factory.factory())(manager) withRetryConfig(retryConfig{maxRetries: 2, initialDelay: time.Millisecond, maxBackoff: time.Millisecond, stableRunThreshold: time.Minute})(manager) @@ -1412,9 +1461,8 @@ func TestDefaultManager_RunWorkload_RestartStatusFailureDoesNotConsumeExtraAttem assert.Equal(t, 2, factory.callCount) } -//nolint:paralleltest // client configuration isolation uses t.Setenv func TestDefaultManager_RunWorkload_RetryCounterReset(t *testing.T) { - isolateWorkloadStopState(t) + t.Parallel() // Test thresholds: short enough to keep the test fast, but with a wide // margin between "short" and "stable" run durations so scheduler jitter @@ -1489,6 +1537,7 @@ func TestDefaultManager_RunWorkload_RetryCounterReset(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + t.Parallel() ctrl := gomock.NewController(t) defer ctrl.Finish() @@ -1500,7 +1549,10 @@ func TestDefaultManager_RunWorkload_RetryCounterReset(t *testing.T) { expectSupervisorPIDCleanup(t, mockStatusMgr, "retry-test") factory := &fakeRunnerFactory{outcomes: tt.outcomes} - manager := &DefaultManager{statuses: mockStatusMgr} + manager := &DefaultManager{ + clientManagers: testClientManagerProvider(unavailableClientManager), + statuses: mockStatusMgr, + } withRetryConfig(testCfg)(manager) withRunnerFactory(factory.factory())(manager) @@ -2271,9 +2323,11 @@ func TestDefaultManager_updateSingleWorkload(t *testing.T) { } manager := &DefaultManager{ - runtime: mockRuntime, - statuses: mockStatusManager, - configProvider: mockConfigProvider, + savedRunConfigs: testSavedRunConfigChecker{exists: true}, + clientManagers: testClientManagerProvider(unavailableClientManager), + runtime: mockRuntime, + statuses: mockStatusManager, + configProvider: mockConfigProvider, } // Inject a no-op spawner so RunWorkloadDetached does not re-exec the // test binary. Without this, the real spawn would orphan a child @@ -2518,13 +2572,7 @@ func isolateWorkloadStopState(t *testing.T) { t.Setenv("XDG_STATE_HOME", t.TempDir()) t.Setenv("XDG_DATA_HOME", t.TempDir()) t.Setenv("XDG_CONFIG_HOME", t.TempDir()) - // NewManager fails before runtime auto-detection or client discovery. XDG - // isolation alone is insufficient: DefaultProvider caches registered clients - // in a singleton, so also seed an empty config rather than reuse a prior load. - t.Setenv("TOOLHIVE_RUNTIME", "disabled-for-test") xdg.Reload() - config.SetSingletonConfig(&config.Config{}) - t.Cleanup(config.ResetSingleton) } func persistStopRunConfig(t *testing.T, name string, rc *runner.RunConfig) { @@ -2694,7 +2742,7 @@ func TestDefaultManager_stopContainerWorkload_ExitedContainerWaitsForTrackedProx Labels: map[string]string{labels.LabelBaseName: "requested-container"}, }, nil) sm.EXPECT().SetWorkloadStatus(gomock.Any(), "requested-container", runtime.WorkloadStatusStopping, "").Return(nil) - sm.EXPECT().GetWorkloadPID(gomock.Any(), "requested-container").Return(proxy.pid, nil) + sm.EXPECT().GetWorkloadPID(gomock.Any(), "requested-container").Return(proxy.pid, nil).Times(2) sm.EXPECT().ResetWorkloadPIDIfMatch(gomock.Any(), "requested-container", proxy.pid).Return(nil) rtMock.EXPECT().StopWorkload(gomock.Any(), "requested-container-1730000000").DoAndReturn(func(context.Context, string) error { select { @@ -2706,7 +2754,11 @@ func TestDefaultManager_stopContainerWorkload_ExitedContainerWaitsForTrackedProx return nil }) sm.EXPECT().SetWorkloadStatus(gomock.Any(), "requested-container", runtime.WorkloadStatusStopped, "").Return(nil) - manager := &DefaultManager{statuses: sm, runtime: rtMock} + manager := &DefaultManager{ + savedRunConfigs: testSavedRunConfigChecker{exists: true}, + clientManagers: testClientManagerProvider(unavailableClientManager), + statuses: sm, runtime: rtMock, + } withPortFreer(func(context.Context, *runner.RunConfig) { t.Error("verified proxy exit must not require port fallback") })(manager) @@ -2718,9 +2770,8 @@ func TestDefaultManager_stopContainerWorkload_ExitedContainerWaitsForTrackedProx } } -//nolint:paralleltest // t.Setenv is incompatible with t.Parallel func TestDefaultManager_stopContainerWorkload_MissingContainerUsesSavedLabels(t *testing.T) { - isolateWorkloadStopState(t) + t.Parallel() for _, tt := range []struct { name string @@ -2752,7 +2803,8 @@ func TestDefaultManager_stopContainerWorkload_MissingContainerUsesSavedLabels(t }, } { t.Run(tt.name, func(t *testing.T) { - persistStopRunConfig(t, "requested-container", tt.runConfig) + t.Parallel() + original := *tt.runConfig original.ContainerLabels = maps.Clone(tt.runConfig.ContainerLabels) ctrl := gomock.NewController(t) @@ -2760,15 +2812,18 @@ func TestDefaultManager_stopContainerWorkload_MissingContainerUsesSavedLabels(t rtMock := runtimeMocks.NewMockRuntime(ctrl) rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), "requested-container").Return(runtime.ContainerInfo{}, fmt.Errorf("inspect: %w", runtime.ErrWorkloadNotFound)) - sm.EXPECT().SetWorkloadStatus(gomock.Any(), "requested-container", runtime.WorkloadStatusStopping, "").Return(nil) - sm.EXPECT().GetWorkloadPID(gomock.Any(), "requested-container").Return(0, runtime.ErrWorkloadNotFound) + + sm.EXPECT().GetWorkloadPID(gomock.Any(), "requested-container").Return(0, runtime.ErrWorkloadNotFound).Times(2) fallbackCalls := 0 rtMock.EXPECT().StopWorkload(gomock.Any(), tt.wantContainerName).DoAndReturn(func(context.Context, string) error { assert.Equal(t, 1, fallbackCalls, "proxy cleanup must precede the fresh runtime stop") return nil }) - sm.EXPECT().SetWorkloadStatus(gomock.Any(), "requested-container", runtime.WorkloadStatusStopped, "").Return(nil) - manager := &DefaultManager{statuses: sm, runtime: rtMock} + + manager := &DefaultManager{ + savedRunConfigs: testSavedRunConfigChecker{exists: true}, + statuses: sm, runtime: rtMock, + } withPortFreer(func(_ context.Context, rc *runner.RunConfig) { assert.Same(t, tt.runConfig, rc) fallbackCalls++ @@ -2819,17 +2874,16 @@ func TestDefaultManager_stopContainerWorkload_InspectionFailureDoesNotStopProxy( &runner.RunConfig{BaseName: "saved-base"}), inspectErr) } -//nolint:paralleltest // saved-workload fixtures use t.Setenv func TestDefaultManager_stopContainerWorkload_RuntimeStopFailureRecordsErrorAfterProxyCleanup(t *testing.T) { - isolateWorkloadStopState(t) + t.Parallel() ctrl := gomock.NewController(t) sm := statusMocks.NewMockStatusManager(ctrl) rtMock := runtimeMocks.NewMockRuntime(ctrl) stopErr := errors.New("runtime stop failed") rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), "container").Return(runtime.ContainerInfo{}, runtime.ErrWorkloadNotFound) - sm.EXPECT().SetWorkloadStatus(gomock.Any(), "container", runtime.WorkloadStatusStopping, "").Return(nil) - sm.EXPECT().GetWorkloadPID(gomock.Any(), "container").Return(0, runtime.ErrWorkloadNotFound) + + sm.EXPECT().GetWorkloadPID(gomock.Any(), "container").Return(0, runtime.ErrWorkloadNotFound).Times(2) cleanupComplete := false rtMock.EXPECT().StopWorkload(gomock.Any(), "container").DoAndReturn(func(context.Context, string) error { assert.True(t, cleanupComplete, "runtime stop must follow proxy cleanup even on failure") @@ -2837,11 +2891,14 @@ func TestDefaultManager_stopContainerWorkload_RuntimeStopFailureRecordsErrorAfte }) sm.EXPECT().SetWorkloadStatus(gomock.Any(), "container", runtime.WorkloadStatusError, stopErr.Error()). Return(errors.New("status storage unavailable")) - manager := &DefaultManager{statuses: sm, runtime: rtMock} + manager := &DefaultManager{ + savedRunConfigs: testSavedRunConfigChecker{exists: true}, + statuses: sm, runtime: rtMock, + } withPortFreer(func(context.Context, *runner.RunConfig) { cleanupComplete = true })(manager) rc := &runner.RunConfig{BaseName: "container"} - persistStopRunConfig(t, "container", rc) + require.ErrorIs(t, manager.stopContainerWorkload(context.Background(), "container", rc), stopErr) } @@ -2860,6 +2917,105 @@ func TestDefaultManager_stopContainerWorkload_MissingConfigPropagatesRuntimeStop require.ErrorIs(t, manager.stopContainerWorkload(context.Background(), "container", nil), stopErr) } +func TestDefaultManager_stopContainerWorkload_InactivePreservesStatusAndClients(t *testing.T) { + t.Parallel() + + for _, status := range []runtime.WorkloadStatus{runtime.WorkloadStatusError, runtime.WorkloadStatusPolicyStopped} { + for _, missing := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/missing=%t", status, missing), func(t *testing.T) { + t.Parallel() + const name = "inactive-workload" + const containerName = "inactive-workload-20260101" + ctrl := gomock.NewController(t) + sm := statusMocks.NewMockStatusManager(ctrl) + rtMock := runtimeMocks.NewMockRuntime(ctrl) + cm := clientMocks.NewMockManager(ctrl) + previous := core.Workload{Name: name, Status: status, StatusContext: "original failure or policy decision"} + sm.EXPECT().GetWorkload(gomock.Any(), name).Return(previous, nil).AnyTimes() + sm.EXPECT().GetWorkloadPID(gomock.Any(), name).Return(0, nil).Times(2) + if missing { + rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), name).Return(runtime.ContainerInfo{}, runtime.ErrWorkloadNotFound) + } else { + rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), name).Return(runtime.ContainerInfo{ + Name: containerName, State: "exited", Labels: map[string]string{labels.LabelBaseName: name}, + }, nil) + } + rc := &runner.RunConfig{BaseName: name, ContainerName: containerName} + manager := &DefaultManager{ + runtime: rtMock, + statuses: sm, + savedRunConfigs: testSavedRunConfigChecker{exists: true}, + clientManagers: testClientManagerProvider(func(context.Context) (client.Manager, error) { + return cm, nil + }), + } + fallbackCalls := 0 + withPortFreer(func(_ context.Context, got *runner.RunConfig) { + assert.Same(t, rc, got) + fallbackCalls++ + })(manager) + rtMock.EXPECT().StopWorkload(gomock.Any(), containerName).DoAndReturn(func(context.Context, string) error { + assert.Equal(t, 1, fallbackCalls, "orphan cleanup must precede the runtime stop") + return nil + }) + + require.NoError(t, manager.stopContainerWorkload(context.Background(), name, rc)) + assert.Equal(t, 1, fallbackCalls) + }) + } + } +} + +//nolint:paralleltest // runner setup loads saved state +func TestDefaultManager_maybeSetupContainerWorkload_StartingSupervisor(t *testing.T) { + isolateWorkloadStopState(t) + for _, ownPID := range []bool{false, true} { + t.Run(fmt.Sprintf("ownPID=%t", ownPID), func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + t.Cleanup(cancel) + const name = "restart-backoff-workload" + rc := &runner.RunConfig{BaseName: name, ContainerName: name + "-20260101"} + persistStopRunConfig(t, name, rc) + pid := os.Getpid() + var proxy *workloadProxyProcess + if !ownPID { + proxy = startVerifiedProxyProcess(t, name) + pid = proxy.pid + } + ctrl := gomock.NewController(t) + rtMock := runtimeMocks.NewMockRuntime(ctrl) + sm := statusMocks.NewMockStatusManager(ctrl) + rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), name).Return(runtime.ContainerInfo{ + Name: rc.ContainerName, State: "exited", Labels: map[string]string{labels.LabelBaseName: name}, + }, nil) + sm.EXPECT().GetWorkload(gomock.Any(), name).Return(core.Workload{Name: name, Status: runtime.WorkloadStatusStarting}, nil) + pidCall := sm.EXPECT().GetWorkloadPID(gomock.Any(), name).Return(pid, nil) + if !ownPID { + pidCall.Times(2) + sm.EXPECT().ResetWorkloadPIDIfMatch(gomock.Any(), name, pid).Return(nil) + } + sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusStarting, ""). + DoAndReturn(func(context.Context, string, runtime.WorkloadStatus, string) error { + if proxy != nil { + select { + case <-proxy.exited: + assert.NoError(t, proxy.waitErr, "the previous supervisor must exit gracefully before restart") + default: + t.Error("restart became ready to spawn while its previous supervisor was alive") + } + } + return nil + }) + manager := &DefaultManager{runtime: rtMock, statuses: sm} + + gotName, gotRunner, err := manager.maybeSetupContainerWorkload(ctx, name) + require.NoError(t, err) + assert.Equal(t, name, gotName) + require.NotNil(t, gotRunner) + }) + } +} + //nolint:paralleltest // t.Setenv is incompatible with t.Parallel func TestDefaultManager_StopWorkloads_MissingContainerStopsSavedContainerNameAndPreservesConfig(t *testing.T) { isolateWorkloadStopState(t) @@ -2883,15 +3039,18 @@ func TestDefaultManager_StopWorkloads_MissingContainerStopsSavedContainerNameAnd sm := statusMocks.NewMockStatusManager(ctrl) rtMock := runtimeMocks.NewMockRuntime(ctrl) rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), name).Return(runtime.ContainerInfo{}, runtime.ErrWorkloadNotFound) - sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusStopping, "").Return(nil) - sm.EXPECT().GetWorkloadPID(gomock.Any(), name).Return(0, runtime.ErrWorkloadNotFound) - sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusStopped, "").Return(nil) + + sm.EXPECT().GetWorkloadPID(gomock.Any(), name).Return(0, runtime.ErrWorkloadNotFound).Times(2) + cleanupComplete := false rtMock.EXPECT().StopWorkload(gomock.Any(), runConfig.ContainerName).DoAndReturn(func(context.Context, string) error { assert.True(t, cleanupComplete) return nil }) - manager := &DefaultManager{statuses: sm, runtime: rtMock} + manager := &DefaultManager{ + savedRunConfigs: testSavedRunConfigChecker{exists: true}, + statuses: sm, runtime: rtMock, + } withPortFreer(func(_ context.Context, rc *runner.RunConfig) { assert.Equal(t, before, rc) cleanupComplete = true @@ -2935,6 +3094,7 @@ func TestDefaultManager_StopWorkload_ForegroundDeletionIsNotResurrected(t *testi Name: name, Status: runtime.WorkloadStatusRunning, }, nil) } else { + sm.EXPECT().GetWorkloadPID(gomock.Any(), name).Return(proxy.pid, nil) rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), name).Return(runtime.ContainerInfo{ Name: name, State: "exited", Labels: map[string]string{labels.LabelBaseName: name}, }, nil) @@ -2967,7 +3127,12 @@ func TestDefaultManager_StopWorkload_ForegroundDeletionIsNotResurrected(t *testi require.ErrorIs(t, err, os.ErrNotExist, "owner deletion must precede guarded PID reset") return fileStatuses.ResetWorkloadPIDIfMatch(ctx, name, pid) }) - manager := &DefaultManager{runtime: rtMock, statuses: sm} + manager := &DefaultManager{ + clientManagers: testClientManagerProvider(unavailableClientManager), + savedRunConfigs: defaultSavedRunConfigChecker{}, + runtime: rtMock, + statuses: sm, + } withPortFreer(func(context.Context, *runner.RunConfig) { t.Error("foreground exit must not require port fallback") })(manager) @@ -2986,7 +3151,7 @@ func TestDefaultManager_StopWorkload_ForegroundDeletionIsNotResurrected(t *testi } } -//nolint:paralleltest // saved-workload fixtures use t.Setenv +//nolint:paralleltest // client configuration cleanup loads saved state func TestDefaultManager_stopRemoteWorkload_LiveProxyStatusesEndStopped(t *testing.T) { isolateWorkloadStopState(t) for _, status := range []runtime.WorkloadStatus{ @@ -2998,7 +3163,7 @@ func TestDefaultManager_stopRemoteWorkload_LiveProxyStatusesEndStopped(t *testin t.Run(string(status), func(t *testing.T) { const name = "remote-retry-backoff" rc := &runner.RunConfig{BaseName: name, RemoteURL: "https://example.com/mcp"} - persistStopRunConfig(t, name, rc) + proxy := startVerifiedProxyProcess(t, name) ctrl := gomock.NewController(t) sm := statusMocks.NewMockStatusManager(ctrl) @@ -3011,7 +3176,11 @@ func TestDefaultManager_stopRemoteWorkload_LiveProxyStatusesEndStopped(t *testin sm.EXPECT().ResetWorkloadPIDIfMatch(gomock.Any(), name, proxy.pid).Return(nil), sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusStopped, "").Return(nil), ) - manager := &DefaultManager{statuses: sm} + manager := &DefaultManager{ + savedRunConfigs: testSavedRunConfigChecker{exists: true}, + clientManagers: testClientManagerProvider(unavailableClientManager), + statuses: sm, + } withPortFreer(func(context.Context, *runner.RunConfig) { t.Error("tracked supervisor exit must not need fallback") })(manager) require.NoError(t, manager.stopRemoteWorkload(context.Background(), name, rc)) @@ -3025,14 +3194,14 @@ func TestDefaultManager_stopRemoteWorkload_LiveProxyStatusesEndStopped(t *testin } } -//nolint:paralleltest // saved-workload fixtures use t.Setenv +//nolint:paralleltest // client configuration cleanup loads saved state func TestDefaultManager_stopRemoteWorkload_StatusWriteFailuresDoNotSkipProxyCleanup(t *testing.T) { isolateWorkloadStopState(t) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) t.Cleanup(cancel) const name = "remote-status-failure" rc := &runner.RunConfig{BaseName: name, RemoteURL: "https://example.com/mcp"} - persistStopRunConfig(t, name, rc) + ctrl := gomock.NewController(t) sm := statusMocks.NewMockStatusManager(ctrl) storageErr := errors.New("status storage unavailable") @@ -3047,16 +3216,19 @@ func TestDefaultManager_stopRemoteWorkload_StatusWriteFailuresDoNotSkipProxyClea return storageErr }), ) - manager := &DefaultManager{statuses: sm} + manager := &DefaultManager{ + savedRunConfigs: testSavedRunConfigChecker{exists: true}, + clientManagers: testClientManagerProvider(unavailableClientManager), + statuses: sm, + } withPortFreer(func(context.Context, *runner.RunConfig) { fallbackCalls++ })(manager) require.NoError(t, manager.stopRemoteWorkload(ctx, name, rc)) assert.Equal(t, 1, fallbackCalls) } -//nolint:paralleltest // saved-workload fixtures use t.Setenv func TestDefaultManager_stopRemoteWorkload_StoppedStatusStillCleansUpProxy(t *testing.T) { - isolateWorkloadStopState(t) + t.Parallel() ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) t.Cleanup(cancel) const name = "already-stopped-remote" @@ -3076,54 +3248,42 @@ func TestDefaultManager_stopRemoteWorkload_StoppedStatusStillCleansUpProxy(t *te assert.Equal(t, 1, fallbackCalls, "stale status must not suppress orphan cleanup or create new status") } -//nolint:paralleltest // saved-workload fixtures use t.Setenv -func TestDefaultManager_finishRemoteWorkloadStop_StoreFailureDoesNotWriteStopped(t *testing.T) { - isolateWorkloadStopState(t) - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - t.Cleanup(cancel) - stateDir := filepath.Join(xdg.StateHome, state.DefaultAppName) - require.NoError(t, os.MkdirAll(stateDir, 0750)) - require.NoError(t, os.WriteFile(filepath.Join(stateDir, state.RunConfigsDir), []byte("not a directory"), 0600)) - manager := &DefaultManager{statuses: statusMocks.NewMockStatusManager(gomock.NewController(t))} - - err := manager.finishRemoteWorkloadStop(ctx, "remote", &runner.RunConfig{BaseName: "remote"}) - require.Error(t, err) - assert.Contains(t, err.Error(), "failed to open run configuration store after stop") +func TestDefaultManager_finishRemoteWorkloadStop_StateCheckFailureDoesNotWriteStopped(t *testing.T) { + t.Parallel() + checkErr := errors.New("state store unavailable") + manager := &DefaultManager{ + statuses: statusMocks.NewMockStatusManager(gomock.NewController(t)), + savedRunConfigs: testSavedRunConfigChecker{err: checkErr}, + } + err := manager.finishRemoteWorkloadStop(context.Background(), "remote", &runner.RunConfig{BaseName: "remote"}) + require.ErrorIs(t, err, checkErr) } -//nolint:paralleltest // saved-workload fixtures use t.Setenv func TestDefaultManager_stopContainerWorkload_StateCheckFailurePreservesRuntimeError(t *testing.T) { - isolateWorkloadStopState(t) - if goruntime.GOOS == "windows" { - t.Skip("state failure fixture requires symlinks") - } - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - t.Cleanup(cancel) + t.Parallel() const name = "failed-state-check" rc := &runner.RunConfig{BaseName: name} - persistStopRunConfig(t, name, rc) - path := filepath.Join(xdg.StateHome, state.DefaultAppName, state.RunConfigsDir, name+".json") - require.NoError(t, os.Remove(path)) - require.NoError(t, os.Symlink(path, path)) ctrl := gomock.NewController(t) rtMock := runtimeMocks.NewMockRuntime(ctrl) sm := statusMocks.NewMockStatusManager(ctrl) stopErr := errors.New("runtime stop failed") + checkErr := errors.New("state store unavailable") rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), name).Return(runtime.ContainerInfo{}, runtime.ErrWorkloadNotFound) - sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusStopping, ""). - Return(errors.New("status storage unavailable")) - sm.EXPECT().GetWorkloadPID(gomock.Any(), name).Return(0, nil) + sm.EXPECT().GetWorkloadPID(gomock.Any(), name).Return(0, nil).Times(2) rtMock.EXPECT().StopWorkload(gomock.Any(), name).Return(stopErr) - manager := &DefaultManager{statuses: sm, runtime: rtMock} + manager := &DefaultManager{ + statuses: sm, + runtime: rtMock, + savedRunConfigs: testSavedRunConfigChecker{err: checkErr}, + } withPortFreer(func(context.Context, *runner.RunConfig) {})(manager) - - err := manager.stopContainerWorkload(ctx, name, rc) + err := manager.stopContainerWorkload(context.Background(), name, rc) require.ErrorIs(t, err, stopErr) - require.ErrorIs(t, err, syscall.ELOOP) + require.ErrorIs(t, err, checkErr) assert.Contains(t, err.Error(), "failed to check saved workload after stop") } -//nolint:paralleltest // saved-workload fixtures use t.Setenv +//nolint:paralleltest // client configuration cleanup loads saved state func TestDefaultManager_stopSingleContainerWorkload_AuxiliaryNeedsNoSavedStateOrProxy(t *testing.T) { isolateWorkloadStopState(t) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) @@ -3136,20 +3296,19 @@ func TestDefaultManager_stopSingleContainerWorkload_AuxiliaryNeedsNoSavedStateOr rtMock.EXPECT().StopWorkload(gomock.Any(), name).Return(nil), sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusStopped, "").Return(nil), ) - manager := &DefaultManager{runtime: rtMock, statuses: sm} + manager := &DefaultManager{ + clientManagers: testClientManagerProvider(unavailableClientManager), + runtime: rtMock, + statuses: sm, + } withPortFreer(func(context.Context, *runner.RunConfig) { t.Error("auxiliary workload must not clean up a proxy") })(manager) workload := &runtime.ContainerInfo{Name: name, Labels: map[string]string{ labels.LabelBaseName: name, labels.LabelAuxiliary: "true", }} - require.NoError(t, manager.stopSingleContainerWorkload(ctx, workload, &runner.RunConfig{BaseName: name})) + require.NoError(t, manager.stopSingleContainerWorkload(ctx, workload, &runner.RunConfig{BaseName: name}, true)) } -// TestDefaultManager_stopProcess verifies the boolean contract that the -// stop/delete port-cleanup fallback relies on: stopProcess reports true only -// when a tracked, identity-verified proxy exits. A false return (no PID recorded — -// e.g. a missing status file — or an unverified PID) is what triggers the -// port-based cleanup fallback in stopSingleContainerWorkload/deleteContainerWorkload. func TestDefaultManager_stopProcess(t *testing.T) { t.Parallel() @@ -3157,33 +3316,33 @@ func TestDefaultManager_stopProcess(t *testing.T) { name string workload string setupMocks func(t *testing.T, sm *statusMocks.MockStatusManager) - want bool + want proxyStopResult }{ { - name: "empty name returns false", + name: "empty name returns not stopped", workload: "", setupMocks: func(_ *testing.T, _ *statusMocks.MockStatusManager) { // No status manager calls expected for an empty name. }, - want: false, + want: proxyNotStopped, }, { - name: "GetWorkloadPID error returns false", + name: "GetWorkloadPID error returns not stopped", workload: "test-workload", setupMocks: func(_ *testing.T, sm *statusMocks.MockStatusManager) { sm.EXPECT().GetWorkloadPID(gomock.Any(), "test-workload").Return(0, errors.New("boom")) }, - want: false, + want: proxyNotStopped, }, { - name: "missing status file (pid 0) returns false", + name: "missing status file (pid 0) returns not stopped", workload: "test-workload", setupMocks: func(_ *testing.T, sm *statusMocks.MockStatusManager) { // A missing status file yields PID 0 with no error; identity validation // rejects it without a PID update. sm.EXPECT().GetWorkloadPID(gomock.Any(), "test-workload").Return(0, nil) }, - want: false, + want: proxyNotStopped, }, { name: "verified proxy exit succeeds even when PID reset fails", @@ -3195,7 +3354,7 @@ func TestDefaultManager_stopProcess(t *testing.T) { sm.EXPECT().ResetWorkloadPIDIfMatch(gomock.Any(), "test-workload", pid). Return(errors.New("status storage unavailable")) }, - want: true, + want: proxyStopped, }, } @@ -3285,7 +3444,7 @@ func TestDefaultManager_ensureProxyStopped_UnverifiedLivePIDIsPreservedWithoutSi } } -func TestDefaultManager_ensureProxyStopped_ExitTimeoutPreservesVerifiedPIDAndFallsBackOnce(t *testing.T) { +func TestDefaultManager_ensureProxyStopped_ExitTimeoutPreservesVerifiedPIDWithoutFallback(t *testing.T) { t.Parallel() const name = "slow-shutdown-supervisor" @@ -3304,7 +3463,7 @@ func TestDefaultManager_ensureProxyStopped_ExitTimeoutPreservesVerifiedPIDAndFal })(manager) manager.ensureProxyStopped(context.Background(), name, name, runConfig) - assert.Equal(t, 1, fallbackCalls, "verified timeout must run port fallback once") + assert.Zero(t, fallbackCalls, "a signalled proxy must not be signalled again through port cleanup") select { case <-proxy.exited: t.Error("SIGTERM-ignoring proxy unexpectedly exited") @@ -3396,13 +3555,17 @@ func TestDefaultManager_orphanProxyPortCleanup(t *testing.T) { var freed []*runner.RunConfig runConfig := &runner.RunConfig{BaseName: workloadName, Port: 54321} persistStopRunConfig(t, workloadName, runConfig) - manager := &DefaultManager{statuses: sm, runtime: rtMock} + manager := &DefaultManager{ + savedRunConfigs: testSavedRunConfigChecker{exists: true}, + clientManagers: testClientManagerProvider(unavailableClientManager), + statuses: sm, runtime: rtMock, + } withPortFreer(func(_ context.Context, rc *runner.RunConfig) { freed = append(freed, rc) })(manager) ci := containerInfo() - err := manager.stopSingleContainerWorkload(context.Background(), &ci, runConfig) + err := manager.stopSingleContainerWorkload(context.Background(), &ci, runConfig, true) require.NoError(t, err) require.Len(t, freed, 1, "port-cleanup fallback should run exactly once") @@ -3426,14 +3589,18 @@ func TestDefaultManager_orphanProxyPortCleanup(t *testing.T) { sm.EXPECT().SetWorkloadStatus(gomock.Any(), workloadName, runtime.WorkloadStatusStopped, "").Return(nil) freedCalls := 0 - manager := &DefaultManager{statuses: sm, runtime: rtMock} + manager := &DefaultManager{ + savedRunConfigs: testSavedRunConfigChecker{exists: true}, + clientManagers: testClientManagerProvider(unavailableClientManager), + statuses: sm, runtime: rtMock, + } withPortFreer(func(_ context.Context, _ *runner.RunConfig) { freedCalls++ })(manager) ci := containerInfo() err := manager.stopSingleContainerWorkload( - context.Background(), &ci, savedRunConfig(t), + context.Background(), &ci, savedRunConfig(t), true, ) require.NoError(t, err) @@ -3461,7 +3628,11 @@ func TestDefaultManager_orphanProxyPortCleanup(t *testing.T) { var freed []*runner.RunConfig runConfig := &runner.RunConfig{BaseName: workloadName, Port: 54321} persistStopRunConfig(t, workloadName, runConfig) - manager := &DefaultManager{statuses: sm, runtime: rtMock} + manager := &DefaultManager{ + savedRunConfigs: testSavedRunConfigChecker{exists: true}, + clientManagers: testClientManagerProvider(unavailableClientManager), + statuses: sm, runtime: rtMock, + } withPortFreer(func(_ context.Context, rc *runner.RunConfig) { freed = append(freed, rc) })(manager) @@ -3493,7 +3664,11 @@ func TestDefaultManager_orphanProxyPortCleanup(t *testing.T) { sm.EXPECT().DeleteWorkloadStatus(gomock.Any(), workloadName).Return(nil) freedCalls := 0 - manager := &DefaultManager{statuses: sm, runtime: rtMock} + manager := &DefaultManager{ + savedRunConfigs: testSavedRunConfigChecker{exists: true}, + clientManagers: testClientManagerProvider(unavailableClientManager), + statuses: sm, runtime: rtMock, + } withPortFreer(func(_ context.Context, _ *runner.RunConfig) { freedCalls++ })(manager) @@ -3524,7 +3699,11 @@ func TestDefaultManager_orphanProxyPortCleanup(t *testing.T) { var freed []*runner.RunConfig runConfig := &runner.RunConfig{BaseName: workloadName, Port: 54321} persistStopRunConfig(t, workloadName, runConfig) - manager := &DefaultManager{statuses: sm} + manager := &DefaultManager{ + savedRunConfigs: testSavedRunConfigChecker{exists: true}, + clientManagers: testClientManagerProvider(unavailableClientManager), + statuses: sm, + } withPortFreer(func(_ context.Context, rc *runner.RunConfig) { freed = append(freed, rc) })(manager) @@ -3552,7 +3731,11 @@ func TestDefaultManager_orphanProxyPortCleanup(t *testing.T) { var freed []*runner.RunConfig runConfig := &runner.RunConfig{BaseName: workloadName, Port: 54321} persistStopRunConfig(t, workloadName, runConfig) - manager := &DefaultManager{statuses: sm} + manager := &DefaultManager{ + savedRunConfigs: testSavedRunConfigChecker{exists: true}, + clientManagers: testClientManagerProvider(unavailableClientManager), + statuses: sm, + } withPortFreer(func(_ context.Context, rc *runner.RunConfig) { freed = append(freed, rc) })(manager) @@ -3584,7 +3767,11 @@ func TestDefaultManager_orphanProxyPortCleanup(t *testing.T) { sm.EXPECT().SetWorkloadStatus(gomock.Any(), workloadName, runtime.WorkloadStatusStopped, "").Return(nil) freedCalls := 0 - manager := &DefaultManager{statuses: sm} + manager := &DefaultManager{ + savedRunConfigs: testSavedRunConfigChecker{exists: true}, + clientManagers: testClientManagerProvider(unavailableClientManager), + statuses: sm, + } withPortFreer(func(_ context.Context, _ *runner.RunConfig) { freedCalls++ })(manager) @@ -3612,7 +3799,11 @@ func TestDefaultManager_orphanProxyPortCleanup(t *testing.T) { sm.EXPECT().DeleteWorkloadStatus(gomock.Any(), workloadName).Return(nil) freedCalls := 0 - manager := &DefaultManager{statuses: sm} + manager := &DefaultManager{ + savedRunConfigs: testSavedRunConfigChecker{exists: true}, + clientManagers: testClientManagerProvider(unavailableClientManager), + statuses: sm, + } withPortFreer(func(_ context.Context, _ *runner.RunConfig) { freedCalls++ })(manager) diff --git a/pkg/workloads/statuses/file_status.go b/pkg/workloads/statuses/file_status.go index d118476759..917808db67 100644 --- a/pkg/workloads/statuses/file_status.go +++ b/pkg/workloads/statuses/file_status.go @@ -519,6 +519,40 @@ func (f *fileStatusManager) ResetWorkloadPIDIfMatch(ctx context.Context, workloa return err } +// SetWorkloadStoppedIfOwned marks a workload stopped only if, re-checked under +// the file lock, its status file still exists, still claims starting or +// running, and records no PID or ownerPID. A supervisor cancelled by a signal +// uses it so it neither recreates a deleted workload's status nor overrides a +// replacement supervisor or a newer stopping/removing status. +func (f *fileStatusManager) SetWorkloadStoppedIfOwned(ctx context.Context, workloadName string, ownerPID int) error { + return f.withFileLock(ctx, workloadName, func(statusFilePath string) error { + if _, err := os.Stat(statusFilePath); os.IsNotExist(err) { + return nil + } else if err != nil { + return fmt.Errorf("failed to check status file for workload %s: %w", workloadName, err) + } + + statusFile, err := f.readStatusFile(statusFilePath) + if err != nil { + return fmt.Errorf("failed to read existing status for workload %s: %w", workloadName, err) + } + if statusFile.Status != rt.WorkloadStatusStarting && statusFile.Status != rt.WorkloadStatusRunning { + slog.Debug("skipping stopped mark: status changed", "workload", workloadName, "status", statusFile.Status) + return nil + } + if statusFile.ProcessID != 0 && statusFile.ProcessID != ownerPID { + slog.Debug("skipping stopped mark: workload owned by another process", + "workload", workloadName, "current_pid", statusFile.ProcessID, "owner_pid", ownerPID) + return nil + } + + statusFile.Status = rt.WorkloadStatusStopped + statusFile.StatusContext = "" + statusFile.UpdatedAt = time.Now() + return f.writeStatusFile(statusFilePath, *statusFile) + }) +} + // GetWorkloadPID retrieves the PID of a workload from its status file. func (f *fileStatusManager) GetWorkloadPID(ctx context.Context, workloadName string) (int, error) { var pid int diff --git a/pkg/workloads/statuses/file_status_test.go b/pkg/workloads/statuses/file_status_test.go index d9546af162..ae0aced44e 100644 --- a/pkg/workloads/statuses/file_status_test.go +++ b/pkg/workloads/statuses/file_status_test.go @@ -1910,6 +1910,56 @@ func TestFileStatusManager_ResetWorkloadPIDIfMatch_NonExistentWorkload(t *testin require.NoFileExists(t, statusFile) } +func TestFileStatusManager_SetWorkloadStoppedIfOwned(t *testing.T) { + t.Parallel() + const ownerPID = 12345 + + tests := []struct { + name string + status rt.WorkloadStatus + pid int + wantStatus rt.WorkloadStatus + wantContext string + }{ + {name: "starting without PID", status: rt.WorkloadStatusStarting, wantStatus: rt.WorkloadStatusStopped}, + {name: "running with owner PID", status: rt.WorkloadStatusRunning, pid: ownerPID, wantStatus: rt.WorkloadStatusStopped}, + {name: "replacement PID", status: rt.WorkloadStatusStarting, pid: 99999, + wantStatus: rt.WorkloadStatusStarting, wantContext: "original"}, + {name: "removing", status: rt.WorkloadStatusRemoving, wantStatus: rt.WorkloadStatusRemoving, wantContext: "original"}, + {name: "error", status: rt.WorkloadStatusError, wantStatus: rt.WorkloadStatusError, wantContext: "original"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + tempDir := t.TempDir() + manager := &fileStatusManager{baseDir: tempDir} + ctx := context.Background() + + require.NoError(t, manager.SetWorkloadStatus(ctx, "test-workload", tt.status, "original")) + require.NoError(t, manager.SetWorkloadPID(ctx, "test-workload", tt.pid)) + + require.NoError(t, manager.SetWorkloadStoppedIfOwned(ctx, "test-workload", ownerPID)) + + data, err := os.ReadFile(filepath.Join(tempDir, "test-workload.json")) + require.NoError(t, err) + var statusFileData workloadStatusFile + require.NoError(t, json.Unmarshal(data, &statusFileData)) + assert.Equal(t, tt.wantStatus, statusFileData.Status) + assert.Equal(t, tt.wantContext, statusFileData.StatusContext) + assert.Equal(t, tt.pid, statusFileData.ProcessID) + }) + } + + t.Run("missing status is not recreated", func(t *testing.T) { + t.Parallel() + tempDir := t.TempDir() + manager := &fileStatusManager{baseDir: tempDir} + + require.NoError(t, manager.SetWorkloadStoppedIfOwned(context.Background(), "test-workload", ownerPID)) + require.NoFileExists(t, filepath.Join(tempDir, "test-workload.json")) + }) +} + // TestFileStatusManager_GetWorkload_PIDMigration tests PID migration from legacy PID files to status files func TestFileStatusManager_GetWorkload_PIDMigration(t *testing.T) { t.Parallel() diff --git a/pkg/workloads/statuses/mocks/mock_status_manager.go b/pkg/workloads/statuses/mocks/mock_status_manager.go index 9ff073471f..9b300d2f88 100644 --- a/pkg/workloads/statuses/mocks/mock_status_manager.go +++ b/pkg/workloads/statuses/mocks/mock_status_manager.go @@ -156,3 +156,17 @@ func (mr *MockStatusManagerMockRecorder) SetWorkloadStatus(ctx, workloadName, st mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetWorkloadStatus", reflect.TypeOf((*MockStatusManager)(nil).SetWorkloadStatus), ctx, workloadName, status, contextMsg) } + +// SetWorkloadStoppedIfOwned mocks base method. +func (m *MockStatusManager) SetWorkloadStoppedIfOwned(ctx context.Context, workloadName string, ownerPID int) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "SetWorkloadStoppedIfOwned", ctx, workloadName, ownerPID) + ret0, _ := ret[0].(error) + return ret0 +} + +// SetWorkloadStoppedIfOwned indicates an expected call of SetWorkloadStoppedIfOwned. +func (mr *MockStatusManagerMockRecorder) SetWorkloadStoppedIfOwned(ctx, workloadName, ownerPID any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetWorkloadStoppedIfOwned", reflect.TypeOf((*MockStatusManager)(nil).SetWorkloadStoppedIfOwned), ctx, workloadName, ownerPID) +} diff --git a/pkg/workloads/statuses/noop.go b/pkg/workloads/statuses/noop.go index f24e710e29..c7c2145964 100644 --- a/pkg/workloads/statuses/noop.go +++ b/pkg/workloads/statuses/noop.go @@ -54,6 +54,11 @@ func (*NoopStatusManager) ResetWorkloadPIDIfMatch(_ context.Context, _ string, _ return nil } +// SetWorkloadStoppedIfOwned does nothing and returns nil. +func (*NoopStatusManager) SetWorkloadStoppedIfOwned(_ context.Context, _ string, _ int) error { + return nil +} + // GetWorkloadPID returns 0 and nil error. func (*NoopStatusManager) GetWorkloadPID(_ context.Context, _ string) (int, error) { return 0, nil diff --git a/pkg/workloads/statuses/status.go b/pkg/workloads/statuses/status.go index 776dc9c5cd..c78ccddbfb 100644 --- a/pkg/workloads/statuses/status.go +++ b/pkg/workloads/statuses/status.go @@ -42,6 +42,10 @@ type StatusManager interface { // dying process from clobbering the PID written by a replacement process // that started in the meantime. ResetWorkloadPIDIfMatch(ctx context.Context, workloadName string, expectedPID int) error + // SetWorkloadStoppedIfOwned marks a workload stopped only if its status + // still exists, is starting or running, and records either no PID or + // ownerPID. It never creates a status entry or overrides a newer status. + SetWorkloadStoppedIfOwned(ctx context.Context, workloadName string, ownerPID int) error // GetWorkloadPID retrieves the PID of a workload by its name. // Returns 0 if the workload does not exist or if PID is not available. GetWorkloadPID(ctx context.Context, workloadName string) (int, error) @@ -165,6 +169,13 @@ func (*runtimeStatusManager) ResetWorkloadPIDIfMatch(_ context.Context, workload return nil } +func (*runtimeStatusManager) SetWorkloadStoppedIfOwned(_ context.Context, workloadName string, ownerPID int) error { + // Noop for runtime status manager + slog.Debug("workload conditional stop (noop for runtime status manager)", + "workload", workloadName, "owner_pid", ownerPID) + return nil +} + func (*runtimeStatusManager) GetWorkloadPID(_ context.Context, workloadName string) (int, error) { // Noop for runtime status manager - always return 0 slog.Debug("workload PID requested (noop for runtime status manager, returning 0)", "workload", workloadName) From d3ee6673e4f37d257b899c0de37eac1d95f007b2 Mon Sep 17 00:00:00 2001 From: Jairus Christensen Date: Wed, 4 Nov 2026 21:20:04 -0700 Subject: [PATCH 5/7] Tighten supervisor identity and handoff 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. --- docs/arch/08-workloads-lifecycle.md | 31 +++++---- pkg/process/toolhive_proxy.go | 99 +++++++++++++++++++++++++---- pkg/process/toolhive_proxy_test.go | 47 +++++++++++++- pkg/workloads/manager.go | 45 +++++++++++-- pkg/workloads/manager_test.go | 84 ++++++++++++++++++++---- 5 files changed, 265 insertions(+), 41 deletions(-) diff --git a/docs/arch/08-workloads-lifecycle.md b/docs/arch/08-workloads-lifecycle.md index 8b9c6dee79..23e4e89e47 100644 --- a/docs/arch/08-workloads-lifecycle.md +++ b/docs/arch/08-workloads-lifecycle.md @@ -91,9 +91,10 @@ supervisor that is waiting in restart backoff. Auxiliary workloads have no proxy to clean up. Stop writes `Stopping` and then `Stopped`, and removes client configuration, -only when something was live: the container was running or a supervisor PID was -recorded. Otherwise stop leaves the current status alone, so an `Error` or -`PolicyStopped` workload keeps its status and reason. +only when something was live: the container was running or the recorded +supervisor PID belongs to a running process. Otherwise stop leaves the current +status alone, so an `Error` or `PolicyStopped` workload keeps its status and +reason, even if a stale PID is still recorded. `thv stop --all` and `--group` skip `Starting` workloads, including supervisors waiting in restart backoff. Stop them by name. @@ -188,14 +189,15 @@ The same `Applier` backs both the CLI (`thv upgrade apply`) and the API (`POST / Before signalling the PID in the status file, stop and delete check that it belongs to this workload's ToolHive supervisor. A detached supervisor must have the exact workload name on its command line. A foreground supervisor must be a -`thv` process whose first `run`, `start`, or `restart` argument names the -workload: +`thv` process whose subcommand, the first argument that is not a flag, is +`run`, `start`, or `restart`. Only the ToolHive arguments before `--` are +checked, because everything after `--` goes to the MCP server. - `start` and `restart` must have the workload name as a whole argument, unless - they use `--all` or `--group`. -- `run` must have `--name `, `--name=`, or the workload name - as a positional argument. Only an unnamed `thv run ` is accepted - without a name, because its name is derived from the image. + they select workloads with `--all`/`-a` or `--group`/`-g`. +- `run` must have `--name ` or `--name=`. A `run` without + `--name`, such as `thv run ` or `thv run --from-config `, is + accepted without a name, because its name comes from the image or the file. There is no process start-time check, so if the OS reuses the PID for another matching `thv` command, ToolHive can't tell. A PID that is alive but can't be @@ -217,9 +219,14 @@ cancelled by a signal while `Starting` or `Running`, it writes `Stopped` under the status file lock, as long as the recorded PID is unset or its own, and exits with status 0. -Start and restart stop any other supervisor whose PID is recorded for the -workload before they spawn a new one, whatever the current status is. They never -signal their own PID. +For container workloads, start and restart try to stop any other supervisor +whose PID is recorded for the workload before they spawn a new one, whatever +the current status is. This uses the same best-effort stop, so a supervisor that +can't be verified or doesn't exit in time can still be running. They never +signal their own PID. A foreground `thv run` is the exception: it deletes its +workload when it exits, so start and restart leave it in charge and return as if +the workload were already running. Remote workloads in `Starting` keep their +existing supervisor. **Implementation**: `pkg/workloads/manager.go`, `pkg/process/toolhive_proxy.go` diff --git a/pkg/process/toolhive_proxy.go b/pkg/process/toolhive_proxy.go index a445280fa6..a0b7d3eeda 100644 --- a/pkg/process/toolhive_proxy.go +++ b/pkg/process/toolhive_proxy.go @@ -79,8 +79,9 @@ func IsToolHiveProxyForWorkload(pid int, workloadName string) (bool, error) { // IsTrackedToolHiveProxyForWorkload verifies a PID read from a workload's status. // Detached supervisors must match the workload name. Non-detached ToolHive // run/start/restart supervisors use recorded-PID binding without a process-birth-time check. -// An unnamed run may omit its derived workload name. Named runs must match; -// start/restart must include the name or select --all or --group. +// Only the subcommand and its ToolHive arguments before "--" are checked. +// An unnamed or --from-config run may omit its derived workload name. Named +// runs must match; start/restart must include the name or select --all or --group. // Port-discovered PIDs must use IsToolHiveProxyForWorkload instead. func IsTrackedToolHiveProxyForWorkload(pid int, workloadName string) (bool, error) { if pid <= 0 || workloadName == "" { @@ -112,21 +113,92 @@ func isTrackedToolHiveProxyForWorkload(p processMetadata, workloadName string) ( if !isToolHiveProcess(p) { return false, nil } - for i := 1; i < len(args); i++ { - switch args[i] { - case "run": - return trackedRunMatchesWorkload(args[i+1:], workloadName), nil - case "start", "restart": - return slices.ContainsFunc(args[i+1:], func(arg string) bool { - return arg == workloadName || arg == "--all" || arg == "--group" || strings.HasPrefix(arg, "--group=") - }), nil - } + switch command, rest := supervisorSubcommand(args); command { + case "run": + return trackedRunMatchesWorkload(rest, workloadName), nil + case "start", "restart": + return trackedStartMatchesWorkload(rest, workloadName), nil } return false, nil } +// IsForegroundRunSupervisorForWorkload reports whether pid is a non-detached +// `thv run` supervising workloadName. Such a process deletes its workload when +// it exits, so it cannot be replaced by another supervisor. +func IsForegroundRunSupervisorForWorkload(pid int, workloadName string) (bool, error) { + if pid <= 0 || workloadName == "" { + return false, nil + } + p, err := gopsutilprocess.NewProcess(int32(pid)) //nolint:gosec // G115: supported platform PIDs fit int32. + if err != nil { + return false, err + } + return isForegroundRunSupervisorForWorkload(p, workloadName) +} + +func isForegroundRunSupervisorForWorkload(p processMetadata, workloadName string) (bool, error) { + env, err := p.Environ() + if err != nil { + return false, err + } + if slices.Contains(env, ToolHiveDetachedEnv+"="+ToolHiveDetachedValue) { + return false, nil + } + args, err := p.CmdlineSlice() + if err != nil { + return false, err + } + if !isToolHiveProcess(p) { + return false, nil + } + command, rest := supervisorSubcommand(args) + return command == "run" && trackedRunMatchesWorkload(rest, workloadName), nil +} + +// supervisorSubcommand returns the first non-flag argument after argv[0] and +// the arguments that follow it, up to "--". The only root flag, --debug, takes +// no value, so the first non-flag argument is the subcommand. Arguments after +// "--" belong to the MCP server, not ToolHive. +func supervisorSubcommand(argv []string) (string, []string) { + for i := 1; i < len(argv); i++ { + if argv[i] == "--" { + return "", nil + } + if strings.HasPrefix(argv[i], "-") { + continue + } + rest := argv[i+1:] + if end := slices.Index(rest, "--"); end >= 0 { + rest = rest[:end] + } + return argv[i], rest + } + return "", nil +} + +// trackedStartMatchesWorkload accepts start/restart arguments that name the +// workload or select it through --all/-a or --group/-g. +func trackedStartMatchesWorkload(args []string, workloadName string) bool { + return slices.ContainsFunc(args, func(arg string) bool { + switch { + case arg == workloadName, arg == "--all", arg == "--group", strings.HasPrefix(arg, "--group="): + return true + case strings.HasPrefix(arg, "--all="): + return strings.TrimPrefix(arg, "--all=") != "false" + case strings.HasPrefix(arg, "--"): + return false + case strings.HasPrefix(arg, "-"): + // Shorthand cluster such as -a, -af, -g, or -g=name. + shorthands, _, _ := strings.Cut(arg[1:], "=") + return strings.ContainsAny(shorthands, "ag") + } + return false + }) +} + func trackedRunMatchesWorkload(args []string, workloadName string) bool { named := false + fromConfig := false for i := 0; i < len(args); i++ { switch { case args[i] == "--name": @@ -140,9 +212,12 @@ func trackedRunMatchesWorkload(args []string, workloadName string) bool { if strings.TrimPrefix(args[i], "--name=") != workloadName { return false } + case args[i] == "--from-config", strings.HasPrefix(args[i], "--from-config="): + // The workload name comes from the config file, like an unnamed run. + fromConfig = true } } - return named || slices.ContainsFunc(args, func(arg string) bool { + return named || fromConfig || slices.ContainsFunc(args, func(arg string) bool { return !strings.HasPrefix(arg, "-") }) } diff --git a/pkg/process/toolhive_proxy_test.go b/pkg/process/toolhive_proxy_test.go index ee9c231836..138c043da1 100644 --- a/pkg/process/toolhive_proxy_test.go +++ b/pkg/process/toolhive_proxy_test.go @@ -161,6 +161,19 @@ func TestIsTrackedToolHiveProxyForWorkload_ForegroundArguments(t *testing.T) { {name: "reject subcommand substring", args: []string{"thv", "serve", "--description= run img"}}, {name: "skip executable", args: []string{"run", "demo"}}, {name: "first subcommand wins", args: []string{"thv", "start", "other", "run", "img"}}, + {name: "serve flag value is not a subcommand", args: []string{"thv", "serve", "--sentry-environment", "run", "--port", "8080"}}, + {name: "server name does not override workload", args: []string{"thv", "run", "--foreground", "--name", "demo", "img", "--", "--name", "backend"}, expected: true}, + {name: "server name does not select workload", args: []string{"thv", "run", "--foreground", "--name", "backend", "img", "--", "--name", "demo"}}, + {name: "unnamed run with server name", args: []string{"thv", "run", "img", "--", "--name", "other"}, expected: true}, + {name: "start shorthand all", args: []string{"thv", "start", "-a", "-f"}, expected: true}, + {name: "restart shorthand cluster", args: []string{"thv", "restart", "-af"}, expected: true}, + {name: "start shorthand group", args: []string{"thv", "start", "-g", "servers", "-f"}, expected: true}, + {name: "restart shorthand equals group", args: []string{"thv", "restart", "-g=servers"}, expected: true}, + {name: "start explicit all true", args: []string{"thv", "start", "--all=true"}, expected: true}, + {name: "start explicit all false", args: []string{"thv", "start", "--all=false", "other"}}, + {name: "run config equals", args: []string{"thv", "run", "--foreground", "--from-config=demo.json"}, expected: true}, + {name: "run config argument", args: []string{"thv", "run", "--foreground", "--from-config", "demo.json"}, expected: true}, + {name: "separator before command", args: []string{"thv", "--", "run", "img"}}, {name: "empty argv"}, } { t.Run(tt.name, func(t *testing.T) { @@ -177,6 +190,36 @@ func TestIsTrackedToolHiveProxyForWorkload_ForegroundArguments(t *testing.T) { } } +func TestIsForegroundRunSupervisorForWorkload(t *testing.T) { + t.Parallel() + for _, tt := range []struct { + name string + detached bool + args []string + expected bool + }{ + {name: "detached run", detached: true, args: []string{"thv", "run", "--name", "demo", "img"}}, + {name: "foreground run", args: []string{"thv", "run", "--name", "demo", "img"}, expected: true}, + {name: "foreground start", args: []string{"thv", "start", "demo", "--foreground"}}, + {name: "different workload", args: []string{"thv", "run", "--name", "other", "img"}}, + } { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + metadata := mocks.NewMockProcessMetadata(gomock.NewController(t)) + if tt.detached { + metadata.EXPECT().Environ().Return([]string{ToolHiveDetachedEnv + "=" + ToolHiveDetachedValue}, nil) + } else { + metadata.EXPECT().Environ().Return(nil, nil).Times(2) + metadata.EXPECT().CmdlineSlice().Return(tt.args, nil) + metadata.EXPECT().Exe().Return("/usr/bin/thv", nil) + } + matched, err := isForegroundRunSupervisorForWorkload(metadata, "demo") + require.NoError(t, err) + assert.Equal(t, tt.expected, matched) + }) + } +} + func TestIsTrackedToolHiveProxyForWorkload_ForegroundDoesNotRelaxPortIdentity(t *testing.T) { t.Parallel() @@ -238,7 +281,9 @@ func startIdentityProcess(t *testing.T, detached bool, args ...string) int { require.NoError(t, os.Symlink(executable, thv)) executable = thv } - cmd := exec.Command(executable, append([]string{"-test.run=^TestToolHiveIdentityProcess$", "--"}, args...)...) + // Test flag parsing stops at the first non-flag argument, so the ToolHive + // subcommand can follow directly without a "--" that would hide it. + cmd := exec.Command(executable, append([]string{"-test.run=^TestToolHiveIdentityProcess$"}, args...)...) for _, entry := range os.Environ() { if !strings.HasPrefix(entry, ToolHiveDetachedEnv+"=") { cmd.Env = append(cmd.Env, entry) diff --git a/pkg/workloads/manager.go b/pkg/workloads/manager.go index 71c26ccb43..04fa0ec088 100644 --- a/pkg/workloads/manager.go +++ b/pkg/workloads/manager.go @@ -593,7 +593,7 @@ func (d *DefaultManager) stopContainerWorkload(ctx context.Context, name string, container, err := d.runtime.GetWorkloadInfo(ctx, name) found := err == nil if err != nil { - if !errors.Is(err, rt.ErrWorkloadNotFound) { + if !errors.Is(err, rt.ErrWorkloadNotFound) && !errors.Is(err, rt.ErrContainerNotFound) { return fmt.Errorf("failed to find workload %s: %w", name, err) } slog.Debug("container not found, proceeding with proxy cleanup", "workload", name) @@ -616,11 +616,11 @@ func (d *DefaultManager) stopContainerWorkload(ctx context.Context, name string, } } - // Only a running container or a recorded supervisor gives stop something to - // report. Otherwise the existing status (for example error or + // Only a running container or a live recorded supervisor gives stop + // 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.isSupervisorProcessAlive(ctx, labels.GetContainerBaseName(container.Labels)) + live := (found && container.IsRunning()) || d.hasLiveSupervisorPID(ctx, labels.GetContainerBaseName(container.Labels)) if live { if err := d.statuses.SetWorkloadStatus(ctx, name, rt.WorkloadStatusStopping, ""); err != nil { slog.Debug("failed to set workload status to stopping", "workload", name, "error", err) @@ -1209,6 +1209,35 @@ func (d *DefaultManager) isSupervisorProcessAlive(ctx context.Context, name stri return true } +// hasLiveSupervisorPID reports whether the workload records a PID whose process +// still exists. A PID that cannot be inspected counts as live. +func (d *DefaultManager) hasLiveSupervisorPID(ctx context.Context, name string) bool { + if name == "" { + return false + } + pid, err := d.statuses.GetWorkloadPID(ctx, name) + if err != nil || pid <= 0 { + return false + } + alive, err := process.FindProcess(pid) + return err != nil || alive +} + +// foregroundRunSupervisor returns the PID of a live non-detached `thv run` +// recorded for the workload, or 0. That process deletes the workload when it +// exits, so start and restart leave it in charge instead of replacing it. +func (d *DefaultManager) foregroundRunSupervisor(ctx context.Context, name string) int { + pid, err := d.statuses.GetWorkloadPID(ctx, name) + if err != nil || pid <= 0 || pid == os.Getpid() { + return 0 + } + foreground, err := process.IsForegroundRunSupervisorForWorkload(pid, name) + if err != nil || !foreground { + return 0 + } + return pid +} + // proxyStopResult describes the outcome of stopping a tracked proxy PID. type proxyStopResult int @@ -1701,6 +1730,14 @@ func (d *DefaultManager) maybeSetupContainerWorkload(ctx context.Context, name s slog.Debug("workload is running but supervisor is dead, cleaning up before restart", "workload", workloadName) } + if !labels.IsAuxiliaryWorkload(container.Labels) { + if pid := d.foregroundRunSupervisor(ctx, workloadName); pid != 0 { + slog.Info("workload is supervised by a foreground thv run, leaving it in charge", + "workload", workloadName, "pid", pid) + return "", nil, nil + } + } + // Check if we need to stop the workload before restarting // This happens when: 1) container is running, or 2) inconsistent state shouldStop := false diff --git a/pkg/workloads/manager_test.go b/pkg/workloads/manager_test.go index a448579971..dd49022ea6 100644 --- a/pkg/workloads/manager_test.go +++ b/pkg/workloads/manager_test.go @@ -845,7 +845,7 @@ func TestDefaultManager_restartContainerWorkload(t *testing.T) { Status: runtime.WorkloadStatusRunning, }, nil) // Check if supervisor is alive - return error (supervisor is dead) - sm.EXPECT().GetWorkloadPID(gomock.Any(), "container-workload").Return(0, errors.New("no PID found")) + sm.EXPECT().GetWorkloadPID(gomock.Any(), "container-workload").Return(0, errors.New("no PID found")).Times(2) // With dead supervisor, restart proceeds with cleanup and restart sm.EXPECT().SetWorkloadStatus(gomock.Any(), "container-workload", runtime.WorkloadStatusStopping, "").Return(nil) sm.EXPECT().GetWorkloadPID(gomock.Any(), "container-workload").Return(0, errors.New("no PID found")) @@ -1077,7 +1077,7 @@ func TestDefaultManager_restartLogicConsistency(t *testing.T) { }, nil) // Check if supervisor is alive - return error (dead supervisor) - statusMgr.EXPECT().GetWorkloadPID(gomock.Any(), "test-workload").Return(0, errors.New("no PID found")) + statusMgr.EXPECT().GetWorkloadPID(gomock.Any(), "test-workload").Return(0, errors.New("no PID found")).Times(2) // When supervisor is dead, expect stop logic to be called statusMgr.EXPECT().SetWorkloadStatus(gomock.Any(), "test-workload", runtime.WorkloadStatusStopping, "").Return(nil) @@ -1124,7 +1124,7 @@ func TestDefaultManager_restartLogicConsistency(t *testing.T) { }, nil) // PID 0 with nil error - simulates ResetWorkloadPID setting process_id to 0 - statusMgr.EXPECT().GetWorkloadPID(gomock.Any(), "test-workload").Return(0, nil) + statusMgr.EXPECT().GetWorkloadPID(gomock.Any(), "test-workload").Return(0, nil).Times(2) // When supervisor is treated as dead, expect stop logic statusMgr.EXPECT().SetWorkloadStatus(gomock.Any(), "test-workload", runtime.WorkloadStatusStopping, "").Return(nil) @@ -2651,7 +2651,7 @@ func startProxyProcessFixture(t *testing.T, name string, ignoreSIGTERM, listen b require.NoError(t, os.Symlink(executable, thv)) executable = thv } - cmd := exec.Command(executable, append([]string{"-test.run=^TestWorkloadProxyProcess$", "--"}, args...)...) + cmd := exec.Command(executable, append([]string{"-test.run=^TestWorkloadProxyProcess$"}, args...)...) for _, entry := range os.Environ() { if !strings.HasPrefix(entry, "TOOLHIVE_DETACHED=") { cmd.Env = append(cmd.Env, entry) @@ -2775,6 +2775,7 @@ func TestDefaultManager_stopContainerWorkload_MissingContainerUsesSavedLabels(t for _, tt := range []struct { name string + inspectErr error runConfig *runner.RunConfig wantContainerName string }{ @@ -2796,6 +2797,12 @@ func TestDefaultManager_stopContainerWorkload_MissingContainerUsesSavedLabels(t }, wantContainerName: "requested-container-1730000000", }, + { + name: "wrapped container not found still stops saved container", + inspectErr: fmt.Errorf("inspect: %w", runtime.ErrContainerNotFound), + runConfig: &runner.RunConfig{BaseName: "requested-container", ContainerName: "requested-container-1730000000"}, + wantContainerName: "requested-container-1730000000", + }, { name: "missing saved container name falls back to workload base", runConfig: &runner.RunConfig{BaseName: "requested-container"}, @@ -2810,8 +2817,11 @@ func TestDefaultManager_stopContainerWorkload_MissingContainerUsesSavedLabels(t ctrl := gomock.NewController(t) sm := statusMocks.NewMockStatusManager(ctrl) rtMock := runtimeMocks.NewMockRuntime(ctrl) - rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), "requested-container").Return(runtime.ContainerInfo{}, - fmt.Errorf("inspect: %w", runtime.ErrWorkloadNotFound)) + inspectErr := tt.inspectErr + if inspectErr == nil { + inspectErr = fmt.Errorf("inspect: %w", runtime.ErrWorkloadNotFound) + } + rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), "requested-container").Return(runtime.ContainerInfo{}, inspectErr) sm.EXPECT().GetWorkloadPID(gomock.Any(), "requested-container").Return(0, runtime.ErrWorkloadNotFound).Times(2) fallbackCalls := 0 @@ -2921,8 +2931,16 @@ func TestDefaultManager_stopContainerWorkload_InactivePreservesStatusAndClients( t.Parallel() for _, status := range []runtime.WorkloadStatus{runtime.WorkloadStatusError, runtime.WorkloadStatusPolicyStopped} { - for _, missing := range []bool{false, true} { - t.Run(fmt.Sprintf("%s/missing=%t", status, missing), func(t *testing.T) { + for _, tt := range []struct { + name string + missing bool + stalePID bool + }{ + {name: "exited"}, + {name: "missing", missing: true}, + {name: "exited with reaped supervisor", stalePID: true}, + } { + t.Run(fmt.Sprintf("%s/%s", status, tt.name), func(t *testing.T) { t.Parallel() const name = "inactive-workload" const containerName = "inactive-workload-20260101" @@ -2932,8 +2950,23 @@ func TestDefaultManager_stopContainerWorkload_InactivePreservesStatusAndClients( cm := clientMocks.NewMockManager(ctrl) previous := core.Workload{Name: name, Status: status, StatusContext: "original failure or policy decision"} sm.EXPECT().GetWorkload(gomock.Any(), name).Return(previous, nil).AnyTimes() - sm.EXPECT().GetWorkloadPID(gomock.Any(), name).Return(0, nil).Times(2) - if missing { + pid := 0 + if tt.stalePID { + var exited <-chan struct{} + pid, exited = startKillableProcess(t) + child, err := os.FindProcess(pid) + require.NoError(t, err) + require.NoError(t, child.Kill()) + require.NoError(t, child.Release()) + select { + case <-exited: + case <-time.After(5 * time.Second): + t.Fatal("stale supervisor fixture was not reaped") + } + sm.EXPECT().ResetWorkloadPIDIfMatch(gomock.Any(), name, pid).Return(nil) + } + sm.EXPECT().GetWorkloadPID(gomock.Any(), name).Return(pid, nil).Times(2) + if tt.missing { rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), name).Return(runtime.ContainerInfo{}, runtime.ErrWorkloadNotFound) } else { rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), name).Return(runtime.ContainerInfo{ @@ -2966,6 +2999,33 @@ func TestDefaultManager_stopContainerWorkload_InactivePreservesStatusAndClients( } } +func TestDefaultManager_maybeSetupContainerWorkload_ForegroundRunKeepsOwnership(t *testing.T) { + t.Parallel() + const name = "foreground-restart-backoff" + proxy := startVerifiedProxyProcess(t, "", "run", "--foreground", "--name", name, "example/server") + ctrl := gomock.NewController(t) + rtMock := runtimeMocks.NewMockRuntime(ctrl) + sm := statusMocks.NewMockStatusManager(ctrl) + rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), name).Return(runtime.ContainerInfo{ + Name: name, State: "exited", Labels: map[string]string{labels.LabelBaseName: name}, + }, nil) + sm.EXPECT().GetWorkload(gomock.Any(), name).Return(core.Workload{ + Name: name, Status: runtime.WorkloadStatusStarting, + }, nil) + sm.EXPECT().GetWorkloadPID(gomock.Any(), name).Return(proxy.pid, nil) + manager := &DefaultManager{runtime: rtMock, statuses: sm} + + gotName, gotRunner, err := manager.maybeSetupContainerWorkload(context.Background(), name) + require.NoError(t, err) + assert.Empty(t, gotName) + assert.Nil(t, gotRunner) + select { + case <-proxy.exited: + t.Error("foreground run must retain ownership during restart backoff") + default: + } +} + //nolint:paralleltest // runner setup loads saved state func TestDefaultManager_maybeSetupContainerWorkload_StartingSupervisor(t *testing.T) { isolateWorkloadStopState(t) @@ -2989,9 +3049,9 @@ func TestDefaultManager_maybeSetupContainerWorkload_StartingSupervisor(t *testin Name: rc.ContainerName, State: "exited", Labels: map[string]string{labels.LabelBaseName: name}, }, nil) sm.EXPECT().GetWorkload(gomock.Any(), name).Return(core.Workload{Name: name, Status: runtime.WorkloadStatusStarting}, nil) - pidCall := sm.EXPECT().GetWorkloadPID(gomock.Any(), name).Return(pid, nil) + pidCall := sm.EXPECT().GetWorkloadPID(gomock.Any(), name).Return(pid, nil).Times(2) if !ownPID { - pidCall.Times(2) + pidCall.Times(3) sm.EXPECT().ResetWorkloadPIDIfMatch(gomock.Any(), name, pid).Return(nil) } sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusStarting, ""). From ad66f89fcd563be4f864022cd7fb158af35372ec Mon Sep 17 00:00:00 2001 From: Jairus Christensen Date: Thu, 12 Nov 2026 12:02:25 -0700 Subject: [PATCH 6/7] Require supervisor handoff before start and delete 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 --- docs/arch/08-workloads-lifecycle.md | 65 ++++-- pkg/workloads/manager.go | 252 +++++++++++++++------ pkg/workloads/manager_supervisor_test.go | 154 +++++++++++++ pkg/workloads/manager_test.go | 33 ++- pkg/workloads/statuses/file_status.go | 26 ++- pkg/workloads/statuses/file_status_test.go | 16 +- pkg/workloads/statuses/status.go | 7 +- 7 files changed, 428 insertions(+), 125 deletions(-) create mode 100644 pkg/workloads/manager_supervisor_test.go diff --git a/docs/arch/08-workloads-lifecycle.md b/docs/arch/08-workloads-lifecycle.md index 23e4e89e47..7e4d36300d 100644 --- a/docs/arch/08-workloads-lifecycle.md +++ b/docs/arch/08-workloads-lifecycle.md @@ -91,10 +91,12 @@ supervisor that is waiting in restart backoff. Auxiliary workloads have no proxy to clean up. Stop writes `Stopping` and then `Stopped`, and removes client configuration, -only when something was live: the container was running or the recorded -supervisor PID belongs to a running process. Otherwise stop leaves the current -status alone, so an `Error` or `PolicyStopped` workload keeps its status and -reason, even if a stale PID is still recorded. +only when something was live: the container was running or the recorded PID is +the workload's running supervisor. Otherwise stop leaves the current status +alone, so an `Error` or `PolicyStopped` workload keeps its status and reason, +even if a stale PID is still recorded. If the recorded PID is alive but can't be +inspected, stop fails instead, because it can neither signal that process nor +know that it has stopped. See [Proxy termination](#proxy-termination). `thv stop --all` and `--group` skip `Starting` workloads, including supervisors waiting in restart backoff. Stop them by name. @@ -149,9 +151,10 @@ The Docker runtime only deletes networks that carry the `toolhive=true` and workload name labels. It leaves unlabelled networks alone, even when their names match ToolHive's naming scheme. -Stopping the supervisor is best-effort. A foreground supervisor runs its own -cleanup when it gets SIGTERM, and that cleanup can overlap with delete if the -supervisor takes longer than the exit wait. See +Delete fails, sets the status to `Error`, and keeps the container and saved +state if the supervisor can't be confirmed gone: it was signalled but is still +exiting after the wait, or its recorded PID is alive but can't be inspected. +Retry once the supervisor has exited. See [Proxy termination](#proxy-termination). **Remote workload**: Stops proxy → deletes state @@ -200,33 +203,45 @@ checked, because everything after `--` goes to the MCP server. accepted without a name, because its name comes from the image or the file. There is no process start-time check, so if the OS reuses the PID for another -matching `thv` command, ToolHive can't tell. A PID that is alive but can't be -verified is left alone. +matching `thv` command, ToolHive can't tell. A recorded PID is never signalled +unless it passes this check: + +- A process that was inspected and doesn't match, for example after the OS + reused the PID, is left alone and its PID stays recorded. Stop and delete + carry on as if no supervisor were running. +- A process that is alive but can't be inspected, for example because it + belongs to another user, makes stop, delete, start, and restart fail with an + error. It could still be the supervisor, and ToolHive won't report success + while it may be restarting the container. +- A PID whose process has exited is cleared. On Unix, stop sends SIGTERM and does not escalate. On Windows, it uses TerminateProcess, which is a hard stop. Both wait up to five seconds for the process to exit. If the process was signalled but is still exiting after the -wait, stop doesn't signal it again. If there is no PID to signal, or it can't be -verified, stop falls back to freeing the proxy port when the saved configuration -allows it. The port holder must match the workload exactly, and the fallback -also waits up to five seconds. Cleanup is best-effort and can leave a proxy +wait, it isn't signalled again: stop carries on, while delete, start, and +restart fail so that the old supervisor's shutdown can't tear down what they do +next. If there is no PID to signal, or the process doesn't match, stop and +delete fall back to freeing the proxy port when the saved configuration allows +it. The port holder must match the workload exactly, and the fallback also +waits up to five seconds. This fallback is best-effort and can leave a proxy running or its port in use. The supervisor owns its PID entry. It keeps the PID registered across container restart attempts, including backoff, and shutdown cancels the backoff. When it exits, it clears the PID only if the entry still holds its own PID. If it was -cancelled by a signal while `Starting` or `Running`, it writes `Stopped` under -the status file lock, as long as the recorded PID is unset or its own, and exits -with status 0. - -For container workloads, start and restart try to stop any other supervisor -whose PID is recorded for the workload before they spawn a new one, whatever -the current status is. This uses the same best-effort stop, so a supervisor that -can't be verified or doesn't exit in time can still be running. They never -signal their own PID. A foreground `thv run` is the exception: it deletes its -workload when it exits, so start and restart leave it in charge and return as if -the workload were already running. Remote workloads in `Starting` keep their -existing supervisor. +cancelled, by a signal or by reaching a deadline, it exits with status 0, and +under one status file lock clears its PID and changes `Starting` or `Running` to +`Stopped`. It writes nothing unless the recorded PID is its own, so a +replacement that has written `Starting` but not yet recorded its PID keeps its +status. + +Start and restart stop any other supervisor whose PID is recorded for the +workload before they spawn a new one, whatever the current status is. They +return an error, without spawning, unless that supervisor is confirmed gone. +They never signal their own PID. A foreground `thv run` is the exception: it +deletes its workload when it exits, so start and restart leave it in charge and +return success without doing anything, including while it waits in restart +backoff. These rules apply to container and remote workloads. **Implementation**: `pkg/workloads/manager.go`, `pkg/process/toolhive_proxy.go` diff --git a/pkg/workloads/manager.go b/pkg/workloads/manager.go index 04fa0ec088..d2ecb72f29 100644 --- a/pkg/workloads/manager.go +++ b/pkg/workloads/manager.go @@ -539,8 +539,8 @@ func (d *DefaultManager) stopRemoteWorkload(ctx context.Context, name string, ru // Stop the proxy and free its port even when the status is missing or not // running — an orphaned proxy can still be holding the port. - if runConfig.BaseName != "" { - d.ensureProxyStopped(ctx, name, runConfig.BaseName, runConfig) + if err := d.stopRemoteProxy(ctx, name, runConfig, stoppable); err != nil { + return err } if stoppable { @@ -549,6 +549,18 @@ func (d *DefaultManager) stopRemoteWorkload(ctx context.Context, name string, ru return nil } +func (d *DefaultManager) stopRemoteProxy(ctx context.Context, name string, runConfig *runner.RunConfig, stoppable bool) error { + if runConfig.BaseName == "" { + return nil + } + result := d.ensureProxyStopped(ctx, name, runConfig.BaseName, runConfig) + err := supervisorStopError(name, result, false) + if err != nil && stoppable { + d.recordSupervisorStopError(ctx, name, err) + } + return err +} + func (d *DefaultManager) finishRemoteWorkloadStop(ctx context.Context, name string, runConfig *runner.RunConfig) error { exists, err := d.savedWorkloadStillExists(ctx, name, runConfig, false) if err != nil { @@ -600,7 +612,9 @@ func (d *DefaultManager) stopContainerWorkload(ctx context.Context, name string, if runConfig == nil { // Without saved state, attempt cleanup by the requested name without // creating a status entry or changing client configurations. - d.ensureProxyStopped(ctx, name, name, nil) + if err := supervisorStopError(name, d.ensureProxyStopped(ctx, name, name, nil), false); err != nil { + return err + } if err := d.runtime.StopWorkload(ctx, name); err != nil { return fmt.Errorf("failed to stop container: %w", err) } @@ -620,7 +634,13 @@ func (d *DefaultManager) stopContainerWorkload(ctx context.Context, name string, // 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)) + live := found && container.IsRunning() + if !live { + live, err = d.hasLiveSupervisorPID(ctx, labels.GetContainerBaseName(container.Labels)) + if err != nil { + return err + } + } if live { if err := d.statuses.SetWorkloadStatus(ctx, name, rt.WorkloadStatusStopping, ""); err != nil { slog.Debug("failed to set workload status to stopping", "workload", name, "error", err) @@ -743,16 +763,16 @@ func (d *DefaultManager) RunWorkload(ctx context.Context, runConfig *runner.RunC func (d *DefaultManager) finishWorkloadRun(ctx context.Context, name string, runErr error) error { cleanupCtx, cancel := context.WithTimeout(context.Background(), workloadPIDCleanupTimeout) defer cancel() - if err := d.statuses.ResetWorkloadPIDIfMatch(cleanupCtx, name, os.Getpid()); err != nil { - slog.Warn("failed to reset workload PID", "workload", name, "error", err) - } if ctx.Err() == nil { + if err := d.statuses.ResetWorkloadPIDIfMatch(cleanupCtx, name, os.Getpid()); err != nil { + slog.Warn("failed to reset workload PID", "workload", name, "error", err) + } return runErr } // A cancellation that does not come from stop or delete (for example // SIGTERM or Ctrl-C) would otherwise leave the status at starting or - // running. The guarded write leaves newer statuses and replacement - // supervisors alone. + // running. The PID reset and status write happen together so a + // replacement that has written starting but no PID yet is left alone. if err := d.statuses.SetWorkloadStoppedIfOwned(cleanupCtx, name, os.Getpid()); err != nil { slog.Warn("failed to set workload status to stopped", "workload", name, "error", err) } @@ -1057,7 +1077,10 @@ func (d *DefaultManager) deleteRemoteWorkload(ctx context.Context, name string, // Stop proxy if running if runConfig.BaseName != "" { - d.ensureProxyStopped(ctx, name, runConfig.BaseName, runConfig) + result := d.ensureProxyStopped(ctx, name, runConfig.BaseName, runConfig) + if err := d.failDeleteOnSupervisor(ctx, name, result); err != nil { + return err + } } // Clean up associated resources (remote workloads are not auxiliary) @@ -1106,9 +1129,10 @@ func (d *DefaultManager) deleteContainerWorkload(ctx context.Context, name strin } isAuxiliary := labels.IsAuxiliaryWorkload(containerLabels) - // Attempt supervisor shutdown before removal, rather than letting removal - // itself trigger a restart. Shutdown is best-effort and may time out; - // foreground SIGTERM cleanup can then overlap this deletion. + // Stop the supervisor before removal, rather than letting removal itself + // trigger a restart. Delete fails while a signalled supervisor is still + // exiting or the recorded one cannot be verified, since either could + // still act on the workload. // Auxiliary workloads like inspector do not use proxy processes. if !isAuxiliary { proxyConfig := runConfig @@ -1117,7 +1141,10 @@ func (d *DefaultManager) deleteContainerWorkload(ctx context.Context, name strin configCopy.BaseName = baseName proxyConfig = &configCopy } - d.ensureProxyStopped(ctx, name, baseName, proxyConfig) + result := d.ensureProxyStopped(ctx, name, baseName, proxyConfig) + if err := d.failDeleteOnSupervisor(ctx, name, result); err != nil { + return err + } } else { slog.Debug("skipping proxy-runner stop for auxiliary workload", "workload", name) } @@ -1137,6 +1164,24 @@ func (d *DefaultManager) deleteContainerWorkload(ctx context.Context, name strin return nil } +// failDeleteOnSupervisor records an error status when delete cannot confirm +// that the supervisor has stopped. +func (d *DefaultManager) failDeleteOnSupervisor(ctx context.Context, name string, result proxyStopResult) error { + err := supervisorStopError(name, result, true) + if err != nil { + d.recordSupervisorStopError(ctx, name, err) + } + return err +} + +// recordSupervisorStopError replaces a stopping or removing status that would +// otherwise be left behind when the supervisor could not be stopped. +func (d *DefaultManager) recordSupervisorStopError(ctx context.Context, name string, err error) { + if statusErr := d.statuses.SetWorkloadStatus(ctx, name, rt.WorkloadStatusError, err.Error()); statusErr != nil { + slog.Warn("Failed to set workload status to error", "workload", name, "error", statusErr) + } +} + // removeWorkloadContainer removes the workload's container during delete. // container is the result of the initial lookup and may be nil. func (d *DefaultManager) removeWorkloadContainer( @@ -1209,33 +1254,75 @@ func (d *DefaultManager) isSupervisorProcessAlive(ctx context.Context, name stri return true } -// hasLiveSupervisorPID reports whether the workload records a PID whose process -// still exists. A PID that cannot be inspected counts as live. -func (d *DefaultManager) hasLiveSupervisorPID(ctx context.Context, name string) bool { +// hasLiveSupervisorPID reports whether the workload records a PID that is its +// live supervisor. It fails when that PID is alive but cannot be inspected, +// because stop would neither signal it nor know that it is gone. +func (d *DefaultManager) hasLiveSupervisorPID(ctx context.Context, name string) (bool, error) { if name == "" { - return false + return false, nil } pid, err := d.statuses.GetWorkloadPID(ctx, name) if err != nil || pid <= 0 { - return false + return false, nil + } + switch identifySupervisor(pid, name) { + case supervisorVerified: + return true, nil + case supervisorUnverifiable: + return false, fmt.Errorf("workload %s: %w", name, errSupervisorUnverifiable) + case supervisorGone, supervisorForeign: } - alive, err := process.FindProcess(pid) - return err != nil || alive + return false, nil } -// foregroundRunSupervisor returns the PID of a live non-detached `thv run` -// recorded for the workload, or 0. That process deletes the workload when it -// exits, so start and restart leave it in charge instead of replacing it. -func (d *DefaultManager) foregroundRunSupervisor(ctx context.Context, name string) int { - pid, err := d.statuses.GetWorkloadPID(ctx, name) - if err != nil || pid <= 0 || pid == os.Getpid() { - return 0 +type supervisorIdentity int + +const ( + supervisorGone supervisorIdentity = iota + supervisorVerified + // supervisorForeign is a live process that was inspected and is not this + // workload's supervisor, for example after PID reuse. + supervisorForeign + // supervisorUnverifiable is a live process (or one whose liveness is + // unknown) whose identity could not be inspected. + supervisorUnverifiable +) + +var ( + errSupervisorUnverifiable = errors.New( + "its recorded supervisor process is running but could not be verified, so it was not stopped") + errSupervisorExiting = errors.New("its supervisor process is still exiting; retry once it has stopped") +) + +func identifySupervisor(pid int, name string) supervisorIdentity { + verified, identityErr := process.IsTrackedToolHiveProxyForWorkload(pid, name) + if identityErr == nil && verified { + return supervisorVerified } - foreground, err := process.IsForegroundRunSupervisorForWorkload(pid, name) - if err != nil || !foreground { - return 0 + alive, findErr := process.FindProcess(pid) + switch { + case findErr == nil && !alive: + return supervisorGone + case identityErr != nil || findErr != nil: + slog.Warn("could not verify tracked proxy identity", "workload", name, "pid", pid, + "identityError", identityErr, "error", findErr) + return supervisorUnverifiable + default: + return supervisorForeign } - return pid +} + +// supervisorStopError reports a stop result that leaves the supervisor's +// state unknown. Delete and start also require a signalled supervisor to have +// exited, so it cannot tear down what they do next. +func supervisorStopError(name string, result proxyStopResult, requireExit bool) error { + switch { + case result == proxyUnverifiable: + return fmt.Errorf("workload %s: %w", name, errSupervisorUnverifiable) + case result == proxyExiting && requireExit: + return fmt.Errorf("workload %s: %w", name, errSupervisorExiting) + } + return nil } // proxyStopResult describes the outcome of stopping a tracked proxy PID. @@ -1250,6 +1337,9 @@ const ( // proxyExiting means the verified proxy was signalled but had not exited // when the wait timed out. Signalling it again would not help. proxyExiting + // proxyUnverifiable means the recorded PID is alive but its identity could + // not be inspected, so it was not signalled. + proxyUnverifiable ) // stopProcess stops the proxy process associated with the container. @@ -1269,22 +1359,20 @@ func (d *DefaultManager) stopProcess(ctx context.Context, name string) proxyStop // Foreground runs rely on the status entry for workload binding; detached // supervisors additionally have a verifiable workload name in their command. - isToolHiveProxy, err := process.IsTrackedToolHiveProxyForWorkload(pid, name) - if err != nil || !isToolHiveProxy { - alive, findErr := process.FindProcess(pid) - if findErr != nil || alive { - slog.Warn("could not verify tracked proxy identity, preserving PID without signaling", - "workload", name, "pid", pid, "identityError", err, "error", findErr) - return proxyNotStopped - } + switch identifySupervisor(pid, name) { + case supervisorVerified: + return d.stopVerifiedProxy(ctx, name, pid, process.KillProcess) + case supervisorUnverifiable: + return proxyUnverifiable + case supervisorForeign: + slog.Warn("tracked PID is not this workload's proxy, preserving it without signaling", "workload", name, "pid", pid) + case supervisorGone: slog.Debug("tracked proxy is gone, clearing PID", "workload", name, "pid", pid) if err := d.statuses.ResetWorkloadPIDIfMatch(ctx, name, pid); err != nil { slog.Warn("failed to reset workload PID", "workload", name, "error", err) } - return proxyNotStopped } - - return d.stopVerifiedProxy(ctx, name, pid, process.KillProcess) + return proxyNotStopped } // stopVerifiedProxy terminates a proxy whose identity the caller has verified. @@ -1329,11 +1417,16 @@ func (d *DefaultManager) stopProxyIfNeeded(ctx context.Context, name, baseName s // still exiting is not signalled again. // runConfig may be nil (no port fallback then). Used by the stop and delete // paths; the restart path instead frees the port itself, just before the child -// re-binds. -func (d *DefaultManager) ensureProxyStopped(ctx context.Context, name, baseName string, runConfig *runner.RunConfig) { - if d.stopProxyIfNeeded(ctx, name, baseName) == proxyNotStopped { +// re-binds. Callers fail with supervisorStopError rather than report success +// while the supervisor may still be managing the workload. +func (d *DefaultManager) ensureProxyStopped( + ctx context.Context, name, baseName string, runConfig *runner.RunConfig, +) proxyStopResult { + result := d.stopProxyIfNeeded(ctx, name, baseName) + if result == proxyNotStopped { d.portFreerOrDefault()(ctx, runConfig) } + return result } // freePortHolderIfNeeded kills the process holding the proxy port if it is in @@ -1631,15 +1724,26 @@ func (d *DefaultManager) maybeSetupRemoteWorkload( slog.Debug("remote workload is running but supervisor is dead, cleaning up before restart", "workload", name) } - // Run cleanup (Stopping → stop proxy → remove client configs → Stopped) for all - // known workload states except Starting. Skip when workload not found (first-time start) + // Same handoff rules as container workloads: a foreground `thv run` stays + // in charge, and any other supervisor must be gone before a new one starts. + pid, stopErr := d.stopOtherSupervisor(ctx, runConfig.BaseName) + if stopErr != nil { + return nil, stopErr + } + if pid != 0 { + slog.Info("workload is supervised by a foreground thv run, leaving it in charge", + "workload", name, "pid", pid) + return nil, nil + } + + // Run cleanup (Stopping → remove client configs → Stopped) for all known + // workload states except Starting. Skip when workload not found (first-time start) // or status is Starting (parent set this before spawning the child process). needsCleanup := err == nil && workload.Status != rt.WorkloadStatusStarting if needsCleanup { if err := d.statuses.SetWorkloadStatus(ctx, name, rt.WorkloadStatusStopping, ""); err != nil { slog.Debug("failed to set workload status to stopping", "workload", name, "error", err) } - d.stopProxyIfNeeded(ctx, name, runConfig.BaseName) if err := d.removeClientConfigurations(name, false); err != nil { slog.Warn("failed to remove client configurations", "error", err) } @@ -1730,8 +1834,15 @@ func (d *DefaultManager) maybeSetupContainerWorkload(ctx context.Context, name s slog.Debug("workload is running but supervisor is dead, cleaning up before restart", "workload", workloadName) } + // Stop any remaining supervisor, including one in restart backoff while + // the container has exited, so two supervisors never manage the same + // workload. if !labels.IsAuxiliaryWorkload(container.Labels) { - if pid := d.foregroundRunSupervisor(ctx, workloadName); pid != 0 { + pid, stopErr := d.stopOtherSupervisor(ctx, workloadName) + if stopErr != nil { + return "", nil, stopErr + } + if pid != 0 { slog.Info("workload is supervised by a foreground thv run, leaving it in charge", "workload", workloadName, "pid", pid) return "", nil, nil @@ -1758,12 +1869,6 @@ func (d *DefaultManager) maybeSetupContainerWorkload(ctx context.Context, name s slog.Debug("Failed to set workload status to stopping", "workload", workloadName, "error", err) } - // Stop the supervisor process (proxy) if it exists (may already be dead) - // This ensures we clean up any orphaned supervisor processes - if !labels.IsAuxiliaryWorkload(container.Labels) { - d.stopOtherSupervisor(ctx, workloadName) - } - // Now stop the container if it's running if container.IsRunning() { if err := d.runtime.StopWorkload(ctx, containerName); err != nil { @@ -1784,11 +1889,6 @@ func (d *DefaultManager) maybeSetupContainerWorkload(ctx context.Context, name s if err := d.statuses.SetWorkloadStatus(ctx, workloadName, rt.WorkloadStatusStopped, ""); err != nil { slog.Debug("Failed to set workload status to stopped", "workload", workloadName, "error", err) } - } else if !labels.IsAuxiliaryWorkload(container.Labels) { - // A supervisor can still be alive in restart backoff while the status - // is starting and the container has exited. Stop it so two supervisors - // do not manage the same workload. - d.stopOtherSupervisor(ctx, workloadName) } // Load runner configuration from state @@ -1816,15 +1916,26 @@ func (d *DefaultManager) maybeSetupContainerWorkload(ctx context.Context, name s return workloadName, mcpRunner, nil } -// stopOtherSupervisor stops the supervisor recorded for the workload unless it -// is this process, which happens when a detached `start --foreground` child -// sets up its own workload. -func (d *DefaultManager) stopOtherSupervisor(ctx context.Context, name string) { +// stopOtherSupervisor stops the supervisor recorded for the workload before +// start or restart replaces it, unless it is this process, which happens when +// a detached `start --foreground` child sets up its own workload. +// +// A live non-detached `thv run` deletes the workload when it exits, so it is +// left in charge and its PID returned instead. Any other supervisor must be +// confirmed gone: one that is still exiting stops its container on the way +// out and would take down the replacement's. +func (d *DefaultManager) stopOtherSupervisor(ctx context.Context, name string) (foregroundRunPID int, err error) { + if name == "" { + return 0, nil + } pid, err := d.statuses.GetWorkloadPID(ctx, name) if err != nil || pid <= 0 || pid == os.Getpid() { - return + return 0, nil } - d.stopProcess(ctx, name) + if foreground, err := process.IsForegroundRunSupervisorForWorkload(pid, name); err == nil && foreground { + return pid, nil + } + return 0, supervisorStopError(name, d.stopProcess(ctx, name), true) } // startWorkload starts the workload in either foreground or background mode @@ -1942,8 +2053,11 @@ func (d *DefaultManager) stopSingleContainerWorkload( // Stop the proxy process (skip for auxiliary workloads like inspector) if isAuxiliary { slog.Debug("skipping proxy stop for auxiliary workload", "workload", name) - } else { - d.ensureProxyStopped(ctx, name, name, runConfig) + } else if err := supervisorStopError(name, d.ensureProxyStopped(ctx, name, name, runConfig), false); err != nil { + if live { + d.recordSupervisorStopError(childCtx, name, err) + } + return err } slog.Debug("stopping containers", "workload", name) diff --git a/pkg/workloads/manager_supervisor_test.go b/pkg/workloads/manager_supervisor_test.go new file mode 100644 index 0000000000..acc7990433 --- /dev/null +++ b/pkg/workloads/manager_supervisor_test.go @@ -0,0 +1,154 @@ +// SPDX-FileCopyrightText: Copyright 2025 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package workloads + +import ( + "context" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.uber.org/mock/gomock" + + "github.com/stacklok/toolhive/pkg/container/runtime" + runtimeMocks "github.com/stacklok/toolhive/pkg/container/runtime/mocks" + "github.com/stacklok/toolhive/pkg/core" + "github.com/stacklok/toolhive/pkg/labels" + "github.com/stacklok/toolhive/pkg/runner" + statusMocks "github.com/stacklok/toolhive/pkg/workloads/statuses/mocks" +) + +// unverifiableSupervisorPID returns a live PID whose identity this test +// process cannot inspect. PID 1 belongs to another user unless tests run as +// root, in which case the scenario cannot be reproduced. +func unverifiableSupervisorPID(t *testing.T, name string) int { + t.Helper() + if identifySupervisor(1, name) != supervisorUnverifiable { + t.Skip("PID 1 can be inspected by this user") + } + return 1 +} + +func TestDefaultManager_UnverifiableSupervisorFailsStopDeleteAndStart(t *testing.T) { + t.Parallel() + const name = "unverifiable-supervisor" + pid := unverifiableSupervisorPID(t, name) + exited := runtime.ContainerInfo{Name: name, State: "exited", Labels: map[string]string{labels.LabelBaseName: name}} + + t.Run("stop", func(t *testing.T) { + t.Parallel() + ctrl := gomock.NewController(t) + rtMock := runtimeMocks.NewMockRuntime(ctrl) + sm := statusMocks.NewMockStatusManager(ctrl) + rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), name).Return(exited, nil) + sm.EXPECT().GetWorkloadPID(gomock.Any(), name).Return(pid, nil) + // No status writes or runtime stop: stop must not report a supervisor + // it could neither signal nor rule out as stopped. + manager := &DefaultManager{runtime: rtMock, statuses: sm} + + err := manager.stopContainerWorkload(context.Background(), name, &runner.RunConfig{BaseName: name}) + require.ErrorIs(t, err, errSupervisorUnverifiable) + }) + + t.Run("delete", func(t *testing.T) { + t.Parallel() + ctrl := gomock.NewController(t) + rtMock := runtimeMocks.NewMockRuntime(ctrl) + sm := statusMocks.NewMockStatusManager(ctrl) + rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), name).Return(exited, nil) + sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusRemoving, "").Return(nil) + sm.EXPECT().GetWorkloadPID(gomock.Any(), name).Return(pid, nil) + sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusError, gomock.Any()).Return(nil) + // No container removal or status deletion while the supervisor may live. + manager := &DefaultManager{runtime: rtMock, statuses: sm} + + err := manager.deleteContainerWorkload(context.Background(), name, nil) + require.ErrorIs(t, err, errSupervisorUnverifiable) + }) + + t.Run("start", func(t *testing.T) { + t.Parallel() + ctrl := gomock.NewController(t) + sm := statusMocks.NewMockStatusManager(ctrl) + sm.EXPECT().GetWorkloadPID(gomock.Any(), name).Return(pid, nil).Times(2) + manager := &DefaultManager{statuses: sm} + + foregroundPID, err := manager.stopOtherSupervisor(context.Background(), name) + require.ErrorIs(t, err, errSupervisorUnverifiable) + assert.Zero(t, foregroundPID) + }) +} + +func TestDefaultManager_ExitingSupervisorFailsDeleteAndStart(t *testing.T) { + t.Parallel() + + t.Run("start", func(t *testing.T) { + t.Parallel() + const name = "exiting-supervisor-start" + proxy := startProxyProcess(t, name, true) + ctrl := gomock.NewController(t) + rtMock := runtimeMocks.NewMockRuntime(ctrl) + sm := statusMocks.NewMockStatusManager(ctrl) + rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), name).Return(runtime.ContainerInfo{ + Name: name, State: "exited", Labels: map[string]string{labels.LabelBaseName: name}, + }, nil) + sm.EXPECT().GetWorkload(gomock.Any(), name).Return(core.Workload{Name: name, Status: runtime.WorkloadStatusStarting}, nil) + sm.EXPECT().GetWorkloadPID(gomock.Any(), name).Return(proxy.pid, nil).Times(2) + // No starting status: the replacement must not be spawned while the + // old supervisor can still stop the container on its way out. + manager := &DefaultManager{runtime: rtMock, statuses: sm} + withProxyExitTimeout(50 * time.Millisecond)(manager) + + _, gotRunner, err := manager.maybeSetupContainerWorkload(context.Background(), name) + require.ErrorIs(t, err, errSupervisorExiting) + assert.Nil(t, gotRunner) + }) + + t.Run("delete", func(t *testing.T) { + t.Parallel() + const name = "exiting-supervisor-delete" + proxy := startProxyProcess(t, name, true) + ctrl := gomock.NewController(t) + rtMock := runtimeMocks.NewMockRuntime(ctrl) + sm := statusMocks.NewMockStatusManager(ctrl) + rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), name).Return(runtime.ContainerInfo{ + Name: name, State: "running", Labels: map[string]string{labels.LabelBaseName: name}, + }, nil) + sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusRemoving, "").Return(nil) + sm.EXPECT().GetWorkloadPID(gomock.Any(), name).Return(proxy.pid, nil) + sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusError, gomock.Any()).Return(nil) + manager := &DefaultManager{runtime: rtMock, statuses: sm} + withProxyExitTimeout(50 * time.Millisecond)(manager) + withPortFreer(func(context.Context, *runner.RunConfig) { + t.Error("a signalled supervisor must not be signalled again through port cleanup") + })(manager) + + err := manager.deleteContainerWorkload(context.Background(), name, nil) + require.ErrorIs(t, err, errSupervisorExiting) + }) +} + +func TestDefaultManager_maybeSetupRemoteWorkload_ForegroundRunKeepsOwnership(t *testing.T) { + t.Parallel() + const name = "foreground-remote" + proxy := startVerifiedProxyProcess(t, "", "run", "--name", name, "https://example.com/mcp") + ctrl := gomock.NewController(t) + sm := statusMocks.NewMockStatusManager(ctrl) + sm.EXPECT().GetWorkload(gomock.Any(), name).Return(core.Workload{Name: name, Status: runtime.WorkloadStatusUnhealthy}, nil) + sm.EXPECT().GetWorkloadPID(gomock.Any(), name).Return(proxy.pid, nil) + // No status writes: the foreground run would delete the workload if it + // were signalled during restart. + manager := &DefaultManager{statuses: sm} + + gotRunner, err := manager.maybeSetupRemoteWorkload(context.Background(), name, + &runner.RunConfig{BaseName: name, RemoteURL: "https://example.com/mcp"}) + require.NoError(t, err) + assert.Nil(t, gotRunner) + select { + case <-proxy.exited: + t.Error("foreground run must keep ownership of its remote workload") + case <-time.After(100 * time.Millisecond): + } +} diff --git a/pkg/workloads/manager_test.go b/pkg/workloads/manager_test.go index dd49022ea6..347124a1ef 100644 --- a/pkg/workloads/manager_test.go +++ b/pkg/workloads/manager_test.go @@ -848,7 +848,6 @@ func TestDefaultManager_restartContainerWorkload(t *testing.T) { sm.EXPECT().GetWorkloadPID(gomock.Any(), "container-workload").Return(0, errors.New("no PID found")).Times(2) // With dead supervisor, restart proceeds with cleanup and restart sm.EXPECT().SetWorkloadStatus(gomock.Any(), "container-workload", runtime.WorkloadStatusStopping, "").Return(nil) - sm.EXPECT().GetWorkloadPID(gomock.Any(), "container-workload").Return(0, errors.New("no PID found")) rm.EXPECT().StopWorkload(gomock.Any(), "container-workload").Return(nil) // Allow any subsequent status updates sm.EXPECT().SetWorkloadStatus(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).AnyTimes().Return(nil) @@ -1081,7 +1080,6 @@ func TestDefaultManager_restartLogicConsistency(t *testing.T) { // When supervisor is dead, expect stop logic to be called statusMgr.EXPECT().SetWorkloadStatus(gomock.Any(), "test-workload", runtime.WorkloadStatusStopping, "").Return(nil) - statusMgr.EXPECT().GetWorkloadPID(gomock.Any(), "test-workload").Return(0, errors.New("no PID found")) runtimeMgr.EXPECT().StopWorkload(gomock.Any(), "test-workload").Return(nil) // Allow any subsequent status updates (starting, error, etc.) - we don't care about the exact sequence @@ -1128,7 +1126,6 @@ func TestDefaultManager_restartLogicConsistency(t *testing.T) { // When supervisor is treated as dead, expect stop logic statusMgr.EXPECT().SetWorkloadStatus(gomock.Any(), "test-workload", runtime.WorkloadStatusStopping, "").Return(nil) - statusMgr.EXPECT().GetWorkloadPID(gomock.Any(), "test-workload").Return(0, nil) runtimeMgr.EXPECT().StopWorkload(gomock.Any(), "test-workload").Return(nil) statusMgr.EXPECT().SetWorkloadStatus(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).AnyTimes().Return(nil) @@ -1255,9 +1252,9 @@ func (f *fakeRunnerFactory) factory() mcpRunnerFactory { } } -func expectSupervisorPIDCleanup(t *testing.T, sm *statusMocks.MockStatusManager, name string) *gomock.Call { +func expectSupervisorPIDCleanup(t *testing.T, sm *statusMocks.MockStatusManager, name string) { t.Helper() - return sm.EXPECT().ResetWorkloadPIDIfMatch(gomock.Any(), name, os.Getpid()). + sm.EXPECT().ResetWorkloadPIDIfMatch(gomock.Any(), name, os.Getpid()). DoAndReturn(func(ctx context.Context, _ string, _ int) error { assert.NoError(t, ctx.Err(), "PID cleanup must survive supervisor cancellation") _, bounded := ctx.Deadline() @@ -1268,8 +1265,9 @@ func expectSupervisorPIDCleanup(t *testing.T, sm *statusMocks.MockStatusManager, func expectSupervisorCancellationCleanup(t *testing.T, sm *statusMocks.MockStatusManager, name string) { t.Helper() - resetPID := expectSupervisorPIDCleanup(t, sm, name) - sm.EXPECT().SetWorkloadStoppedIfOwned(gomock.Any(), name, os.Getpid()).After(resetPID). + // The PID reset happens inside the guarded write; a separate reset first + // would let the guard mistake a replacement's PID-less starting status. + sm.EXPECT().SetWorkloadStoppedIfOwned(gomock.Any(), name, os.Getpid()). DoAndReturn(func(ctx context.Context, _ string, _ int) error { assert.NoError(t, ctx.Err(), "status cleanup must survive supervisor cancellation") _, bounded := ctx.Deadline() @@ -3049,9 +3047,9 @@ func TestDefaultManager_maybeSetupContainerWorkload_StartingSupervisor(t *testin Name: rc.ContainerName, State: "exited", Labels: map[string]string{labels.LabelBaseName: name}, }, nil) sm.EXPECT().GetWorkload(gomock.Any(), name).Return(core.Workload{Name: name, Status: runtime.WorkloadStatusStarting}, nil) - pidCall := sm.EXPECT().GetWorkloadPID(gomock.Any(), name).Return(pid, nil).Times(2) + pidCall := sm.EXPECT().GetWorkloadPID(gomock.Any(), name).Return(pid, nil) if !ownPID { - pidCall.Times(3) + pidCall.Times(2) sm.EXPECT().ResetWorkloadPIDIfMatch(gomock.Any(), name, pid).Return(nil) } sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusStarting, ""). @@ -3416,6 +3414,17 @@ func TestDefaultManager_stopProcess(t *testing.T) { }, want: proxyStopped, }, + { + name: "live PID that cannot be inspected is reported, not ignored", + workload: "test-workload", + setupMocks: func(t *testing.T, sm *statusMocks.MockStatusManager) { + t.Helper() + pid := unverifiableSupervisorPID(t, "test-workload") + // No reset: the process may still be the supervisor. + sm.EXPECT().GetWorkloadPID(gomock.Any(), "test-workload").Return(pid, nil) + }, + want: proxyUnverifiable, + }, } for _, tt := range tests { @@ -3484,7 +3493,8 @@ func TestDefaultManager_ensureProxyStopped_UnverifiedLivePIDIsPreservedWithoutSi ctrl := gomock.NewController(t) sm := statusMocks.NewMockStatusManager(ctrl) sm.EXPECT().GetWorkloadPID(gomock.Any(), name).Return(pid, nil) - // No reset expectation: an unverifiable live process must remain tracked. + // No reset expectation: a live process that is not this workload's + // supervisor must remain tracked. manager := &DefaultManager{statuses: sm} rc := &runner.RunConfig{BaseName: name, Port: 54321} fallbackCalls := 0 @@ -3493,7 +3503,8 @@ func TestDefaultManager_ensureProxyStopped_UnverifiedLivePIDIsPreservedWithoutSi fallbackCalls++ })(manager) - manager.ensureProxyStopped(context.Background(), name, name, rc) + result := manager.ensureProxyStopped(context.Background(), name, name, rc) + assert.Equal(t, proxyNotStopped, result, "an inspected foreign process must not block stop or delete") assert.Equal(t, 1, fallbackCalls, "unverified PID must not suppress port cleanup") select { case <-exited: diff --git a/pkg/workloads/statuses/file_status.go b/pkg/workloads/statuses/file_status.go index 917808db67..ceed2b4ebd 100644 --- a/pkg/workloads/statuses/file_status.go +++ b/pkg/workloads/statuses/file_status.go @@ -519,12 +519,15 @@ func (f *fileStatusManager) ResetWorkloadPIDIfMatch(ctx context.Context, workloa return err } -// SetWorkloadStoppedIfOwned marks a workload stopped only if, re-checked under -// the file lock, its status file still exists, still claims starting or -// running, and records no PID or ownerPID. A supervisor cancelled by a signal -// uses it so it neither recreates a deleted workload's status nor overrides a -// replacement supervisor or a newer stopping/removing status. +// SetWorkloadStoppedIfOwned clears the PID and marks the workload stopped in +// one locked write, only if its status file still exists and records ownerPID. +// The status changes only from starting or running. A supervisor cancelled by +// a signal uses it so it neither recreates a deleted workload's status nor +// overrides a replacement supervisor or a newer stopping/removing status. func (f *fileStatusManager) SetWorkloadStoppedIfOwned(ctx context.Context, workloadName string, ownerPID int) error { + if err := removePIDFile(workloadName); err != nil { + slog.Debug("no PID for workload was removed", "workload", workloadName) + } return f.withFileLock(ctx, workloadName, func(statusFilePath string) error { if _, err := os.Stat(statusFilePath); os.IsNotExist(err) { return nil @@ -536,18 +539,17 @@ func (f *fileStatusManager) SetWorkloadStoppedIfOwned(ctx context.Context, workl if err != nil { return fmt.Errorf("failed to read existing status for workload %s: %w", workloadName, err) } - if statusFile.Status != rt.WorkloadStatusStarting && statusFile.Status != rt.WorkloadStatusRunning { - slog.Debug("skipping stopped mark: status changed", "workload", workloadName, "status", statusFile.Status) - return nil - } - if statusFile.ProcessID != 0 && statusFile.ProcessID != ownerPID { + if statusFile.ProcessID != ownerPID { slog.Debug("skipping stopped mark: workload owned by another process", "workload", workloadName, "current_pid", statusFile.ProcessID, "owner_pid", ownerPID) return nil } - statusFile.Status = rt.WorkloadStatusStopped - statusFile.StatusContext = "" + statusFile.ProcessID = 0 + if statusFile.Status == rt.WorkloadStatusStarting || statusFile.Status == rt.WorkloadStatusRunning { + statusFile.Status = rt.WorkloadStatusStopped + statusFile.StatusContext = "" + } statusFile.UpdatedAt = time.Now() return f.writeStatusFile(statusFilePath, *statusFile) }) diff --git a/pkg/workloads/statuses/file_status_test.go b/pkg/workloads/statuses/file_status_test.go index ae0aced44e..b62be0e3cd 100644 --- a/pkg/workloads/statuses/file_status_test.go +++ b/pkg/workloads/statuses/file_status_test.go @@ -1920,13 +1920,19 @@ func TestFileStatusManager_SetWorkloadStoppedIfOwned(t *testing.T) { pid int wantStatus rt.WorkloadStatus wantContext string + wantPID int }{ - {name: "starting without PID", status: rt.WorkloadStatusStarting, wantStatus: rt.WorkloadStatusStopped}, {name: "running with owner PID", status: rt.WorkloadStatusRunning, pid: ownerPID, wantStatus: rt.WorkloadStatusStopped}, - {name: "replacement PID", status: rt.WorkloadStatusStarting, pid: 99999, + {name: "starting with owner PID", status: rt.WorkloadStatusStarting, pid: ownerPID, wantStatus: rt.WorkloadStatusStopped}, + // A replacement supervisor writes starting before it records its PID. + {name: "replacement without PID yet", status: rt.WorkloadStatusStarting, wantStatus: rt.WorkloadStatusStarting, wantContext: "original"}, - {name: "removing", status: rt.WorkloadStatusRemoving, wantStatus: rt.WorkloadStatusRemoving, wantContext: "original"}, - {name: "error", status: rt.WorkloadStatusError, wantStatus: rt.WorkloadStatusError, wantContext: "original"}, + {name: "replacement PID", status: rt.WorkloadStatusStarting, pid: 99999, + wantStatus: rt.WorkloadStatusStarting, wantContext: "original", wantPID: 99999}, + {name: "removing with owner PID clears only PID", status: rt.WorkloadStatusRemoving, pid: ownerPID, + wantStatus: rt.WorkloadStatusRemoving, wantContext: "original"}, + {name: "error with another PID", status: rt.WorkloadStatusError, pid: 99999, + wantStatus: rt.WorkloadStatusError, wantContext: "original", wantPID: 99999}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -1946,7 +1952,7 @@ func TestFileStatusManager_SetWorkloadStoppedIfOwned(t *testing.T) { require.NoError(t, json.Unmarshal(data, &statusFileData)) assert.Equal(t, tt.wantStatus, statusFileData.Status) assert.Equal(t, tt.wantContext, statusFileData.StatusContext) - assert.Equal(t, tt.pid, statusFileData.ProcessID) + assert.Equal(t, tt.wantPID, statusFileData.ProcessID) }) } diff --git a/pkg/workloads/statuses/status.go b/pkg/workloads/statuses/status.go index c78ccddbfb..b2d2a3d0b2 100644 --- a/pkg/workloads/statuses/status.go +++ b/pkg/workloads/statuses/status.go @@ -42,9 +42,10 @@ type StatusManager interface { // dying process from clobbering the PID written by a replacement process // that started in the meantime. ResetWorkloadPIDIfMatch(ctx context.Context, workloadName string, expectedPID int) error - // SetWorkloadStoppedIfOwned marks a workload stopped only if its status - // still exists, is starting or running, and records either no PID or - // ownerPID. It never creates a status entry or overrides a newer status. + // SetWorkloadStoppedIfOwned atomically clears the PID and marks a workload + // stopped only if its status still exists and records ownerPID. Only a + // starting or running status becomes stopped. It never creates a status + // entry or overrides a newer status. SetWorkloadStoppedIfOwned(ctx context.Context, workloadName string, ownerPID int) error // GetWorkloadPID retrieves the PID of a workload by its name. // Returns 0 if the workload does not exist or if PID is not available. From e90abd30aa102da6f667ab50fbcf6cd4033e7c00 Mon Sep 17 00:00:00 2001 From: Jairus Christensen Date: Thu, 12 Nov 2026 14:32:58 -0700 Subject: [PATCH 7/7] Kill supervisors that outlast start and delete 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 --- docs/arch/08-workloads-lifecycle.md | 22 ++++---- pkg/process/kill.go | 25 +++++++++ pkg/workloads/manager.go | 52 +++++++++++------- pkg/workloads/manager_supervisor_test.go | 67 ++++++++++++++++++------ pkg/workloads/manager_test.go | 8 +-- 5 files changed, 127 insertions(+), 47 deletions(-) create mode 100644 pkg/process/kill.go diff --git a/docs/arch/08-workloads-lifecycle.md b/docs/arch/08-workloads-lifecycle.md index 7e4d36300d..49dc03118f 100644 --- a/docs/arch/08-workloads-lifecycle.md +++ b/docs/arch/08-workloads-lifecycle.md @@ -152,8 +152,8 @@ workload name labels. It leaves unlabelled networks alone, even when their names match ToolHive's naming scheme. Delete fails, sets the status to `Error`, and keeps the container and saved -state if the supervisor can't be confirmed gone: it was signalled but is still -exiting after the wait, or its recorded PID is alive but can't be inspected. +state if the supervisor can't be confirmed gone: it is still running after +being killed, or its recorded PID is alive but can't be inspected. Retry once the supervisor has exited. See [Proxy termination](#proxy-termination). @@ -215,13 +215,17 @@ unless it passes this check: while it may be restarting the container. - A PID whose process has exited is cleared. -On Unix, stop sends SIGTERM and does not escalate. On Windows, it uses -TerminateProcess, which is a hard stop. Both wait up to five seconds for the -process to exit. If the process was signalled but is still exiting after the -wait, it isn't signalled again: stop carries on, while delete, start, and -restart fail so that the old supervisor's shutdown can't tear down what they do -next. If there is no PID to signal, or the process doesn't match, stop and -delete fall back to freeing the proxy port when the saved configuration allows +On Unix, ToolHive sends SIGTERM. On Windows, it uses TerminateProcess, which is +a hard stop. Either way it waits up to five seconds for the process to exit. +A supervisor's shutdown stops its containers one at a time with the runtime's +stop timeout, so it can take a minute when a container ignores SIGTERM. Stop +carries on and leaves it to finish. Delete, start, and restart can't overlap +with that shutdown, so they kill a supervisor that is still exiting (SIGKILL on +Unix), wait up to five more seconds, and fail if it is still running. Delete +then removes the containers itself, and start and restart replace them. + +If there is no PID to signal, or the process doesn't match, stop and delete +fall back to freeing the proxy port when the saved configuration allows it. The port holder must match the workload exactly, and the fallback also waits up to five seconds. This fallback is best-effort and can leave a proxy running or its port in use. diff --git a/pkg/process/kill.go b/pkg/process/kill.go new file mode 100644 index 0000000000..322dc98ea7 --- /dev/null +++ b/pkg/process/kill.go @@ -0,0 +1,25 @@ +// SPDX-FileCopyrightText: Copyright 2025 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package process + +import ( + "fmt" + "os" +) + +// ForceKillProcess kills a process without letting it clean up: SIGKILL on +// Unix and TerminateProcess on Windows. +func ForceKillProcess(pid int) error { + if pid <= 0 { + return fmt.Errorf("invalid PID: %d", pid) + } + process, err := os.FindProcess(pid) + if err != nil { + return fmt.Errorf("failed to find process: %w", err) + } + if err := process.Kill(); err != nil { + return fmt.Errorf("failed to kill process: %w", err) + } + return nil +} diff --git a/pkg/workloads/manager.go b/pkg/workloads/manager.go index d2ecb72f29..9ab39141ab 100644 --- a/pkg/workloads/manager.go +++ b/pkg/workloads/manager.go @@ -553,7 +553,7 @@ func (d *DefaultManager) stopRemoteProxy(ctx context.Context, name string, runCo if runConfig.BaseName == "" { return nil } - result := d.ensureProxyStopped(ctx, name, runConfig.BaseName, runConfig) + result := d.ensureProxyStopped(ctx, name, runConfig.BaseName, runConfig, false) err := supervisorStopError(name, result, false) if err != nil && stoppable { d.recordSupervisorStopError(ctx, name, err) @@ -612,7 +612,8 @@ func (d *DefaultManager) stopContainerWorkload(ctx context.Context, name string, if runConfig == nil { // Without saved state, attempt cleanup by the requested name without // creating a status entry or changing client configurations. - if err := supervisorStopError(name, d.ensureProxyStopped(ctx, name, name, nil), false); err != nil { + result := d.ensureProxyStopped(ctx, name, name, nil, false) + if err := supervisorStopError(name, result, false); err != nil { return err } if err := d.runtime.StopWorkload(ctx, name); err != nil { @@ -1077,7 +1078,7 @@ func (d *DefaultManager) deleteRemoteWorkload(ctx context.Context, name string, // Stop proxy if running if runConfig.BaseName != "" { - result := d.ensureProxyStopped(ctx, name, runConfig.BaseName, runConfig) + result := d.ensureProxyStopped(ctx, name, runConfig.BaseName, runConfig, true) if err := d.failDeleteOnSupervisor(ctx, name, result); err != nil { return err } @@ -1141,7 +1142,7 @@ func (d *DefaultManager) deleteContainerWorkload(ctx context.Context, name strin configCopy.BaseName = baseName proxyConfig = &configCopy } - result := d.ensureProxyStopped(ctx, name, baseName, proxyConfig) + result := d.ensureProxyStopped(ctx, name, baseName, proxyConfig, true) if err := d.failDeleteOnSupervisor(ctx, name, result); err != nil { return err } @@ -1344,8 +1345,9 @@ const ( // stopProcess stops the proxy process associated with the container. // Unverified PIDs are cleared only if the process is confirmed gone; otherwise -// they remain available for a later retry. -func (d *DefaultManager) stopProcess(ctx context.Context, name string) proxyStopResult { +// they remain available for a later retry. With requireExit, a verified +// supervisor that is still exiting after SIGTERM is killed. +func (d *DefaultManager) stopProcess(ctx context.Context, name string, requireExit bool) proxyStopResult { if name == "" { slog.Warn("could not find base container name in labels") return proxyNotStopped @@ -1361,7 +1363,15 @@ func (d *DefaultManager) stopProcess(ctx context.Context, name string) proxyStop // supervisors additionally have a verifiable workload name in their command. switch identifySupervisor(pid, name) { case supervisorVerified: - return d.stopVerifiedProxy(ctx, name, pid, process.KillProcess) + result := d.stopVerifiedProxy(ctx, name, pid, process.KillProcess) + if result == proxyExiting && requireExit { + // Its shutdown stops containers one by one with the runtime's stop + // timeout, which can take a minute. The caller takes over that + // cleanup, so it must not overlap with what the caller does next. + slog.Warn("supervisor is still exiting, killing it", "workload", name, "pid", pid) + result = d.stopVerifiedProxy(ctx, name, pid, process.ForceKillProcess) + } + return result case supervisorUnverifiable: return proxyUnverifiable case supervisorForeign: @@ -1400,12 +1410,14 @@ func (d *DefaultManager) stopVerifiedProxy(ctx context.Context, name string, pid // stopProxyIfNeeded stops the proxy process if the workload has a base name // (see stopProcess). -func (d *DefaultManager) stopProxyIfNeeded(ctx context.Context, name, baseName string) proxyStopResult { +func (d *DefaultManager) stopProxyIfNeeded( + ctx context.Context, name, baseName string, requireExit bool, +) proxyStopResult { slog.Debug("removing proxy process", "workload", name) if baseName == "" { return proxyNotStopped } - return d.stopProcess(ctx, baseName) + return d.stopProcess(ctx, baseName, requireExit) } // ensureProxyStopped makes a best-effort attempt to stop the workload's proxy @@ -1414,15 +1426,16 @@ func (d *DefaultManager) stopProxyIfNeeded(ctx context.Context, name, baseName s // signalled — no PID is recorded, identity verification fails, or the signal // fails — it falls back to port-based cleanup, which only kills a process // verified to be this workload's own proxy. A proxy that was signalled but is -// still exiting is not signalled again. +// still exiting is not signalled through the port again; with requireExit it +// is killed instead. // runConfig may be nil (no port fallback then). Used by the stop and delete // paths; the restart path instead frees the port itself, just before the child // re-binds. Callers fail with supervisorStopError rather than report success // while the supervisor may still be managing the workload. func (d *DefaultManager) ensureProxyStopped( - ctx context.Context, name, baseName string, runConfig *runner.RunConfig, + ctx context.Context, name, baseName string, runConfig *runner.RunConfig, requireExit bool, ) proxyStopResult { - result := d.stopProxyIfNeeded(ctx, name, baseName) + result := d.stopProxyIfNeeded(ctx, name, baseName, requireExit) if result == proxyNotStopped { d.portFreerOrDefault()(ctx, runConfig) } @@ -1923,7 +1936,7 @@ func (d *DefaultManager) maybeSetupContainerWorkload(ctx context.Context, name s // A live non-detached `thv run` deletes the workload when it exits, so it is // left in charge and its PID returned instead. Any other supervisor must be // confirmed gone: one that is still exiting stops its container on the way -// out and would take down the replacement's. +// out and would take down the replacement's, so it is killed. func (d *DefaultManager) stopOtherSupervisor(ctx context.Context, name string) (foregroundRunPID int, err error) { if name == "" { return 0, nil @@ -1935,7 +1948,7 @@ func (d *DefaultManager) stopOtherSupervisor(ctx context.Context, name string) ( if foreground, err := process.IsForegroundRunSupervisorForWorkload(pid, name); err == nil && foreground { return pid, nil } - return 0, supervisorStopError(name, d.stopProcess(ctx, name), true) + return 0, supervisorStopError(name, d.stopProcess(ctx, name, true), true) } // startWorkload starts the workload in either foreground or background mode @@ -2053,11 +2066,14 @@ func (d *DefaultManager) stopSingleContainerWorkload( // Stop the proxy process (skip for auxiliary workloads like inspector) if isAuxiliary { slog.Debug("skipping proxy stop for auxiliary workload", "workload", name) - } else if err := supervisorStopError(name, d.ensureProxyStopped(ctx, name, name, runConfig), false); err != nil { - if live { - d.recordSupervisorStopError(childCtx, name, err) + } else { + result := d.ensureProxyStopped(ctx, name, name, runConfig, false) + if err := supervisorStopError(name, result, false); err != nil { + if live { + d.recordSupervisorStopError(childCtx, name, err) + } + return err } - return err } slog.Debug("stopping containers", "workload", name) diff --git a/pkg/workloads/manager_supervisor_test.go b/pkg/workloads/manager_supervisor_test.go index acc7990433..e75c65f899 100644 --- a/pkg/workloads/manager_supervisor_test.go +++ b/pkg/workloads/manager_supervisor_test.go @@ -81,29 +81,46 @@ func TestDefaultManager_UnverifiableSupervisorFailsStopDeleteAndStart(t *testing }) } -func TestDefaultManager_ExitingSupervisorFailsDeleteAndStart(t *testing.T) { +// A supervisor's shutdown stops its containers one by one with the runtime's +// stop timeout, so it can outlast stop's wait. Delete and start must not +// overlap with it, but `thv stop` followed by `thv start` or `thv rm` must not +// fail either, so they kill a supervisor that is still exiting. +func TestDefaultManager_ExitingSupervisorIsKilledBeforeDeleteAndStart(t *testing.T) { t.Parallel() + t.Run("stop leaves it exiting", func(t *testing.T) { + t.Parallel() + const name = "exiting-supervisor-stop" + proxy := startProxyProcess(t, name, true) + ctrl := gomock.NewController(t) + sm := statusMocks.NewMockStatusManager(ctrl) + sm.EXPECT().GetWorkloadPID(gomock.Any(), name).Return(proxy.pid, nil) + manager := &DefaultManager{statuses: sm} + withProxyExitTimeout(50 * time.Millisecond)(manager) + + require.Equal(t, proxyExiting, manager.stopProcess(context.Background(), name, false)) + select { + case <-proxy.exited: + t.Error("stop must not kill a supervisor that is shutting down") + default: + } + }) + t.Run("start", func(t *testing.T) { t.Parallel() const name = "exiting-supervisor-start" proxy := startProxyProcess(t, name, true) ctrl := gomock.NewController(t) - rtMock := runtimeMocks.NewMockRuntime(ctrl) sm := statusMocks.NewMockStatusManager(ctrl) - rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), name).Return(runtime.ContainerInfo{ - Name: name, State: "exited", Labels: map[string]string{labels.LabelBaseName: name}, - }, nil) - sm.EXPECT().GetWorkload(gomock.Any(), name).Return(core.Workload{Name: name, Status: runtime.WorkloadStatusStarting}, nil) sm.EXPECT().GetWorkloadPID(gomock.Any(), name).Return(proxy.pid, nil).Times(2) - // No starting status: the replacement must not be spawned while the - // old supervisor can still stop the container on its way out. - manager := &DefaultManager{runtime: rtMock, statuses: sm} + sm.EXPECT().ResetWorkloadPIDIfMatch(gomock.Any(), name, proxy.pid).Return(nil) + manager := &DefaultManager{statuses: sm} withProxyExitTimeout(50 * time.Millisecond)(manager) - _, gotRunner, err := manager.maybeSetupContainerWorkload(context.Background(), name) - require.ErrorIs(t, err, errSupervisorExiting) - assert.Nil(t, gotRunner) + foregroundPID, err := manager.stopOtherSupervisor(context.Background(), name) + require.NoError(t, err) + assert.Zero(t, foregroundPID) + requireExited(t, proxy) }) t.Run("delete", func(t *testing.T) { @@ -118,18 +135,36 @@ func TestDefaultManager_ExitingSupervisorFailsDeleteAndStart(t *testing.T) { }, nil) sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusRemoving, "").Return(nil) sm.EXPECT().GetWorkloadPID(gomock.Any(), name).Return(proxy.pid, nil) - sm.EXPECT().SetWorkloadStatus(gomock.Any(), name, runtime.WorkloadStatusError, gomock.Any()).Return(nil) - manager := &DefaultManager{runtime: rtMock, statuses: sm} + sm.EXPECT().ResetWorkloadPIDIfMatch(gomock.Any(), name, proxy.pid).Return(nil) + rtMock.EXPECT().RemoveWorkload(gomock.Any(), name).DoAndReturn(func(context.Context, string) error { + requireExited(t, proxy) + return nil + }) + rtMock.EXPECT().GetWorkloadInfo(gomock.Any(), name).Return(runtime.ContainerInfo{}, runtime.ErrWorkloadNotFound) + sm.EXPECT().DeleteWorkloadStatus(gomock.Any(), name).Return(nil) + manager := &DefaultManager{ + runtime: rtMock, statuses: sm, + clientManagers: testClientManagerProvider(unavailableClientManager), + } withProxyExitTimeout(50 * time.Millisecond)(manager) withPortFreer(func(context.Context, *runner.RunConfig) { t.Error("a signalled supervisor must not be signalled again through port cleanup") })(manager) - err := manager.deleteContainerWorkload(context.Background(), name, nil) - require.ErrorIs(t, err, errSupervisorExiting) + require.NoError(t, manager.deleteContainerWorkload(context.Background(), name, nil)) }) } +func requireExited(t *testing.T, proxy *workloadProxyProcess) { + t.Helper() + // The helper's Wait goroutine closes exited just after reaping the process. + select { + case <-proxy.exited: + case <-time.After(time.Second): + t.Fatal("the old supervisor must be gone before the caller proceeds") + } +} + func TestDefaultManager_maybeSetupRemoteWorkload_ForegroundRunKeepsOwnership(t *testing.T) { t.Parallel() const name = "foreground-remote" diff --git a/pkg/workloads/manager_test.go b/pkg/workloads/manager_test.go index 347124a1ef..273aeda2f0 100644 --- a/pkg/workloads/manager_test.go +++ b/pkg/workloads/manager_test.go @@ -3439,7 +3439,7 @@ func TestDefaultManager_stopProcess(t *testing.T) { manager := &DefaultManager{statuses: sm} - got := manager.stopProcess(context.Background(), tt.workload) + got := manager.stopProcess(context.Background(), tt.workload, false) assert.Equal(t, tt.want, got) }) } @@ -3468,7 +3468,7 @@ func TestDefaultManager_ensureProxyStopped_ExitedPIDCleanupFailureStillFallsBack fallbackCalls := 0 withPortFreer(func(context.Context, *runner.RunConfig) { fallbackCalls++ })(manager) - manager.ensureProxyStopped(ctx, name, name, &runner.RunConfig{BaseName: name}) + manager.ensureProxyStopped(ctx, name, name, &runner.RunConfig{BaseName: name}, false) assert.Equal(t, 1, fallbackCalls, "clearing a stale PID is not proof that the port is free") } @@ -3503,7 +3503,7 @@ func TestDefaultManager_ensureProxyStopped_UnverifiedLivePIDIsPreservedWithoutSi fallbackCalls++ })(manager) - result := manager.ensureProxyStopped(context.Background(), name, name, rc) + result := manager.ensureProxyStopped(context.Background(), name, name, rc, false) assert.Equal(t, proxyNotStopped, result, "an inspected foreign process must not block stop or delete") assert.Equal(t, 1, fallbackCalls, "unverified PID must not suppress port cleanup") select { @@ -3533,7 +3533,7 @@ func TestDefaultManager_ensureProxyStopped_ExitTimeoutPreservesVerifiedPIDWithou fallbackCalls++ })(manager) - manager.ensureProxyStopped(context.Background(), name, name, runConfig) + manager.ensureProxyStopped(context.Background(), name, name, runConfig, false) assert.Zero(t, fallbackCalls, "a signalled proxy must not be signalled again through port cleanup") select { case <-proxy.exited: