From 8761a68b43bcb4b1654c453c24260460335f6938 Mon Sep 17 00:00:00 2001 From: Alex Castillo Date: Tue, 3 Nov 2026 16:51:25 -0500 Subject: [PATCH 1/5] fix(docker): clean up isolation resources when workload setup fails DeployWorkload creates the internal network and the dns/egress/ingress containers before the MCP container exists. If any later step failed, they were left behind and `thv rm` could not find them because it derives their names from the MCP container. Remove them on the error path. Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Alex Castillo --- pkg/container/docker/client.go | 27 +++++++++- pkg/container/docker/client_deploy_test.go | 57 ++++++++++++++++++++++ 2 files changed, 83 insertions(+), 1 deletion(-) diff --git a/pkg/container/docker/client.go b/pkg/container/docker/client.go index 05482a6d4a..b43cad6c68 100644 --- a/pkg/container/docker/client.go +++ b/pkg/container/docker/client.go @@ -122,6 +122,9 @@ type deployOps interface { ) error getContainerNetworkIP(ctx context.Context, containerName, networkName string) (string, error) discoverBridgeGateways(ctx context.Context) ([]netip.Addr, error) + // cleanupFailedIsolation best-effort removes the auxiliary containers and + // the internal network created for a workload whose setup failed. + cleanupFailedIsolation(ctx context.Context, name, networkName string) } // Client implements the Deployer interface for Docker (and compatible runtimes) @@ -183,7 +186,7 @@ func (c *Client) DeployWorkload( transportType string, options *runtime.DeployWorkloadOptions, isolateNetwork bool, -) (int, error) { +) (_ int, retErr error) { // Get permission config from profile var ignoreConfig *ignore.Config if options != nil { @@ -261,6 +264,14 @@ func (c *Client) DeployWorkload( if err != nil { return 0, fmt.Errorf("failed to create internal network: %w", err) } + // The internal network and the dns/egress/ingress containers are not + // tied to the MCP container yet, so `thv rm` cannot find them if setup + // fails from here on. Remove whatever was created before returning. + defer func() { + if retErr != nil { + c.ops.cleanupFailedIsolation(context.WithoutCancel(ctx), name, networkName) + } + }() // Start or reuse DNS normally before reading Podman's generated hosts. dnsContainerName := fmt.Sprintf("%s-dns", name) @@ -1375,6 +1386,20 @@ func (c *Client) deleteNetwork(ctx context.Context, name string) error { return nil } +// cleanupFailedIsolation best-effort removes the dns, egress and ingress +// containers and the internal network of a workload whose setup failed. +// Failures are logged: the original setup error is what the caller needs. +func (c *Client) cleanupFailedIsolation(ctx context.Context, name, networkName string) { + labels := map[string]string{} + lb.AddNetworkIsolationLabel(labels, true) + if err := c.removeProxyContainers(ctx, name, labels); err != nil { + slog.Warn("failed to remove proxy containers after failed setup", "name", name, "error", err) + } + if err := c.deleteNetwork(ctx, networkName); err != nil { + slog.Warn("failed to remove internal network after failed setup", "name", networkName, "error", err) + } +} + // removeContainer removes a container by ID, without removing any associated networks or proxy containers. func (c *Client) removeContainer(ctx context.Context, containerID string) error { _, err := c.api.ContainerRemove(ctx, containerID, mobyclient.ContainerRemoveOptions{ diff --git a/pkg/container/docker/client_deploy_test.go b/pkg/container/docker/client_deploy_test.go index 3df7f96e18..449a455096 100644 --- a/pkg/container/docker/client_deploy_test.go +++ b/pkg/container/docker/client_deploy_test.go @@ -62,6 +62,9 @@ type fakeDeployOps struct { // callOrder tracks the sequence of operation calls for ordering assertions. callOrder *[]string + // cleanupCalls records cleanupFailedIsolation invocations as "workload/network". + cleanupCalls []string + // error injection errExternalNetworks error errCreateNetwork error @@ -110,6 +113,13 @@ func (f *fakeDeployOps) createDnsContainer(_ context.Context, _ string, _ bool, return f.dnsID, f.dnsIP, f.errDNS } +func (f *fakeDeployOps) cleanupFailedIsolation(_ context.Context, name, networkName string) { + if f.callOrder != nil { + *f.callOrder = append(*f.callOrder, "cleanupFailedIsolation") + } + f.cleanupCalls = append(f.cleanupCalls, name+"/"+networkName) +} + func (f *fakeDeployOps) getContainerNetworkIP(_ context.Context, _, _ string) (string, error) { return f.mcpIP, f.errMcpIP } @@ -594,6 +604,53 @@ func TestDeployWorkload_GatewayDiscoveryFailsClosed(t *testing.T) { assert.False(t, fops.mcpCalled) } +func TestDeployWorkload_IsolatedSetupFailure_CleansUpNetworkAndDNS(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + fops *fakeDeployOps + fproxy *fakeNetworkProxy + wantCleanup bool + }{ + {name: "dns container creation fails", fops: &fakeDeployOps{errDNS: errors.New("boom")}, fproxy: &fakeNetworkProxy{}, wantCleanup: true}, + {name: "gateway discovery fails", fops: &fakeDeployOps{errGateways: errors.New("boom")}, fproxy: &fakeNetworkProxy{}, wantCleanup: true}, + {name: "egress setup fails", fops: &fakeDeployOps{}, fproxy: &fakeNetworkProxy{err: errors.New("boom")}, wantCleanup: true}, + {name: "mcp container creation fails", fops: &fakeDeployOps{errMcp: errors.New("boom")}, fproxy: &fakeNetworkProxy{}, wantCleanup: true}, + {name: "internal network creation fails", fops: &fakeDeployOps{errCreateNetwork: errors.New("boom")}, fproxy: &fakeNetworkProxy{}, wantCleanup: false}, + {name: "success keeps resources", fops: &fakeDeployOps{}, fproxy: &fakeNetworkProxy{}, wantCleanup: false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + client := newClientWithOpsAndProxy(tt.fops, tt.fproxy) + _, err := client.DeployWorkload( + t.Context(), "image", "app", nil, nil, map[string]string{}, + &permissions.Profile{}, "stdio", runtime.NewDeployWorkloadOptions(), true, + ) + if tt.wantCleanup { + require.Error(t, err) + assert.Equal(t, []string{"app/toolhive-app-internal"}, tt.fops.cleanupCalls) + } else { + assert.Empty(t, tt.fops.cleanupCalls) + } + }) + } +} + +func TestDeployWorkload_NoIsolationFailure_DoesNotCleanUp(t *testing.T) { + t.Parallel() + + fops := &fakeDeployOps{errMcp: errors.New("boom")} + client := newClientWithOps(fops) + _, err := client.DeployWorkload( + t.Context(), "image", "app", nil, nil, map[string]string{}, + &permissions.Profile{}, "stdio", runtime.NewDeployWorkloadOptions(), false, + ) + require.Error(t, err) + assert.Empty(t, fops.cleanupCalls) +} + func TestDeployWorkload_PodmanHostDiscovery(t *testing.T) { t.Parallel() for _, allow := range []bool{false, true} { From 2200b49c775744dfe5c328289587ae1efba6aaf5 Mon Sep 17 00:00:00 2001 From: Alex Castillo Date: Tue, 3 Nov 2026 16:53:49 -0500 Subject: [PATCH 2/5] fix(docker): only clean up isolation resources before the MCP container exists Once the MCP container is created, thv rm already finds the dns/egress/ ingress containers and the network through it. Removing them on a later ingress failure would leave the MCP container without its network. Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Alex Castillo --- pkg/container/docker/client.go | 9 +++++++-- pkg/container/docker/client_deploy_test.go | 23 ++++++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/pkg/container/docker/client.go b/pkg/container/docker/client.go index b43cad6c68..caefe78d69 100644 --- a/pkg/container/docker/client.go +++ b/pkg/container/docker/client.go @@ -249,6 +249,10 @@ func (c *Client) DeployWorkload( } networkIsolation := false + // mcpCreated is set once the MCP container exists. From then on `thv rm` + // can find the auxiliary containers and network through it, and removing + // them here would leave the MCP container without its network. + mcpCreated := false // pspec and egress are populated in the isolation block and reused by // SetupIngress after the MCP container is created. var ( @@ -266,9 +270,9 @@ func (c *Client) DeployWorkload( } // The internal network and the dns/egress/ingress containers are not // tied to the MCP container yet, so `thv rm` cannot find them if setup - // fails from here on. Remove whatever was created before returning. + // fails before the MCP container is created. Remove them in that case. defer func() { - if retErr != nil { + if retErr != nil && !mcpCreated { c.ops.cleanupFailedIsolation(context.WithoutCancel(ctx), name, networkName) } }() @@ -350,6 +354,7 @@ func (c *Client) DeployWorkload( if err != nil { return 0, fmt.Errorf("failed to create mcp container: %w", err) } + mcpCreated = true // Don't try and set up an ingress proxy if the transport type is stdio. if transportType == "stdio" { diff --git a/pkg/container/docker/client_deploy_test.go b/pkg/container/docker/client_deploy_test.go index 449a455096..eb27b41a0e 100644 --- a/pkg/container/docker/client_deploy_test.go +++ b/pkg/container/docker/client_deploy_test.go @@ -638,6 +638,29 @@ func TestDeployWorkload_IsolatedSetupFailure_CleansUpNetworkAndDNS(t *testing.T) } } +func TestDeployWorkload_IngressFailureAfterMcpCreated_DoesNotCleanUp(t *testing.T) { + t.Parallel() + + for name, fops := range map[string]*fakeDeployOps{ + "mcp ip lookup fails": {errMcpIP: errors.New("boom")}, + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + client := newClientWithOps(fops) + opts := runtime.NewDeployWorkloadOptions() + opts.ExposedPorts = map[string]struct{}{"8080/tcp": {}} + opts.PortBindings = map[string][]runtime.PortBinding{"8080/tcp": {{HostIP: "127.0.0.1", HostPort: ""}}} + _, err := client.DeployWorkload( + t.Context(), "image", "app", nil, nil, map[string]string{}, + &permissions.Profile{}, "sse", opts, true, + ) + require.Error(t, err) + assert.True(t, fops.mcpCalled) + assert.Empty(t, fops.cleanupCalls, "MCP container exists, so thv rm can clean up") + }) + } +} + func TestDeployWorkload_NoIsolationFailure_DoesNotCleanUp(t *testing.T) { t.Parallel() From df1e8705cd485219b36a01ddb2806ff99e559adc Mon Sep 17 00:00:00 2001 From: Alex Castillo Date: Thu, 19 Nov 2026 21:53:43 -0400 Subject: [PATCH 3/5] Keep isolation resources on restart failure A restart reaches DeployWorkload with the stopped MCP container still in place, so the internal network and sidecars belong to the existing workload. Skip the failed-setup cleanup in that case and only roll back for new workloads. Treat a failed existence lookup as existing. Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Alex Castillo --- pkg/container/docker/client.go | 13 +++++++-- pkg/container/docker/client_deploy_test.go | 31 ++++++++++++++++++++++ 2 files changed, 42 insertions(+), 2 deletions(-) diff --git a/pkg/container/docker/client.go b/pkg/container/docker/client.go index caefe78d69..c3b2a0dc1a 100644 --- a/pkg/container/docker/client.go +++ b/pkg/container/docker/client.go @@ -262,6 +262,14 @@ func (c *Client) DeployWorkload( if effectiveIsolation { networkIsolation = true + // A restart reaches this point with the stopped MCP container still in + // place, so the network and sidecars below belong to an existing + // workload and must survive a failed attempt. If the lookup fails, + // assume the container exists: leaving resources behind beats removing + // ones a workload depends on. + existingMcpID, lookupErr := c.findExistingContainer(ctx, name) + mcpExisted := lookupErr != nil || existingMcpID != "" + internalNetworkLabels := map[string]string{} lb.AddNetworkLabels(internalNetworkLabels, networkName) err := c.ops.createNetwork(ctx, networkName, internalNetworkLabels, true) @@ -270,9 +278,10 @@ func (c *Client) DeployWorkload( } // The internal network and the dns/egress/ingress containers are not // tied to the MCP container yet, so `thv rm` cannot find them if setup - // fails before the MCP container is created. Remove them in that case. + // fails before the MCP container is created. Remove them in that case, + // but only for a new workload (see mcpExisted above). defer func() { - if retErr != nil && !mcpCreated { + if retErr != nil && !mcpCreated && !mcpExisted { c.ops.cleanupFailedIsolation(context.WithoutCancel(ctx), name, networkName) } }() diff --git a/pkg/container/docker/client_deploy_test.go b/pkg/container/docker/client_deploy_test.go index eb27b41a0e..b4216afcf8 100644 --- a/pkg/container/docker/client_deploy_test.go +++ b/pkg/container/docker/client_deploy_test.go @@ -13,7 +13,9 @@ import ( "net/netip" "testing" + "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" @@ -638,6 +640,35 @@ func TestDeployWorkload_IsolatedSetupFailure_CleansUpNetworkAndDNS(t *testing.T) } } +func TestDeployWorkload_RestartFailureBeforeMcp_KeepsExistingResources(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + listErr error + items []container.Summary + }{ + {name: "stopped MCP container exists", items: []container.Summary{{ID: "mcp-id", Names: []string{"/app"}}}}, + {name: "existence lookup fails", listErr: errors.New("daemon unavailable")}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + fops := &fakeDeployOps{errDNS: errors.New("boom")} + client := newClientWithOpsAndProxy(fops, &fakeNetworkProxy{}) + client.api = &fakeDockerAPI{listFunc: func(_ context.Context, _ mobyclient.ContainerListOptions) ([]container.Summary, error) { + return tt.items, tt.listErr + }} + _, err := client.DeployWorkload( + t.Context(), "image", "app", nil, nil, map[string]string{}, + &permissions.Profile{}, "stdio", runtime.NewDeployWorkloadOptions(), true, + ) + require.Error(t, err) + assert.Empty(t, fops.cleanupCalls, "network and sidecars belong to the existing workload") + }) + } +} + func TestDeployWorkload_IngressFailureAfterMcpCreated_DoesNotCleanUp(t *testing.T) { t.Parallel() From 9a749be78370fa3eaaf9252225baf2dd2fe7e279 Mon Sep 17 00:00:00 2001 From: Alex Castillo Date: Thu, 19 Nov 2026 23:24:02 -0400 Subject: [PATCH 4/5] Test isolation cleanup against a fake daemon Address review feedback: run cleanupFailedIsolation against a fake Docker daemon, attempt every sidecar and always delete the network, bound the cleanup with a timeout detached from the caller's cancellation, and tighten the deploy tests (expected errors per case, invalid port binding, ingress failure injection, merged no-cleanup table). Signed-off-by: Alex Castillo --- pkg/container/docker/client.go | 37 ++++-- pkg/container/docker/client_cleanup_test.go | 121 +++++++++++++++++++ pkg/container/docker/client_deploy_test.go | 125 ++++++++++++++------ 3 files changed, 237 insertions(+), 46 deletions(-) create mode 100644 pkg/container/docker/client_cleanup_test.go diff --git a/pkg/container/docker/client.go b/pkg/container/docker/client.go index c3b2a0dc1a..fb2ee50326 100644 --- a/pkg/container/docker/client.go +++ b/pkg/container/docker/client.go @@ -282,7 +282,11 @@ func (c *Client) DeployWorkload( // but only for a new workload (see mcpExisted above). defer func() { if retErr != nil && !mcpCreated && !mcpExisted { - c.ops.cleanupFailedIsolation(context.WithoutCancel(ctx), name, networkName) + // Detach from the caller's cancellation so a cancelled request + // still cleans up, but bound the cleanup so it cannot hang. + cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second) + defer cancel() + c.ops.cleanupFailedIsolation(cleanupCtx, name, networkName) } }() @@ -1400,17 +1404,32 @@ func (c *Client) deleteNetwork(ctx context.Context, name string) error { return nil } -// cleanupFailedIsolation best-effort removes the dns, egress and ingress -// containers and the internal network of a workload whose setup failed. -// Failures are logged: the original setup error is what the caller needs. +// cleanupFailedIsolation best-effort removes the egress, ingress and dns +// containers and the internal network of a workload whose setup failed. Every +// sidecar is attempted and the network is always deleted, even when an earlier +// step fails. Failures are logged: the original setup error is what the caller +// needs. func (c *Client) cleanupFailedIsolation(ctx context.Context, name, networkName string) { - labels := map[string]string{} - lb.AddNetworkIsolationLabel(labels, true) - if err := c.removeProxyContainers(ctx, name, labels); err != nil { - slog.Warn("failed to remove proxy containers after failed setup", "name", name, "error", err) + var errs []error + for _, suffix := range []string{"egress", "ingress", "dns"} { + sidecarName := fmt.Sprintf("%s-%s", name, suffix) + id, err := c.findExistingContainer(ctx, sidecarName) + if err != nil { + errs = append(errs, fmt.Errorf("find %s container: %w", suffix, err)) + continue + } + if id == "" { + continue + } + if err := c.removeContainer(ctx, id); err != nil { + errs = append(errs, fmt.Errorf("remove %s container: %w", suffix, err)) + } } if err := c.deleteNetwork(ctx, networkName); err != nil { - slog.Warn("failed to remove internal network after failed setup", "name", networkName, "error", err) + errs = append(errs, fmt.Errorf("remove internal network %s: %w", networkName, err)) + } + if err := errors.Join(errs...); err != nil { + slog.Warn("failed to fully clean up after failed setup", "name", name, "error", err) } } diff --git a/pkg/container/docker/client_cleanup_test.go b/pkg/container/docker/client_cleanup_test.go new file mode 100644 index 0000000000..9d21fee6d5 --- /dev/null +++ b/pkg/container/docker/client_cleanup_test.go @@ -0,0 +1,121 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package docker + +import ( + "encoding/json" + "net/http" + "strings" + "sync" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// fakeDaemon is a minimal Docker daemon that serves container and network +// lookups for the given names and records every removal request. +type fakeDaemon struct { + mu sync.Mutex + containers map[string]bool // container names that exist + networks map[string]bool // network names that exist + failRemove map[string]bool // container IDs whose removal returns 500 + removed []string // "container/" or "network/" +} + +func (d *fakeDaemon) handler(t *testing.T) http.HandlerFunc { + t.Helper() + // nameFilter extracts the single "name" filter value of a list request. + nameFilter := func(r *http.Request) string { + var filters map[string]map[string]bool + require.NoError(t, json.Unmarshal([]byte(r.URL.Query().Get("filters")), &filters)) + for name := range filters["name"] { + return name + } + return "" + } + return func(w http.ResponseWriter, r *http.Request) { + d.mu.Lock() + defer d.mu.Unlock() + path := strings.TrimPrefix(r.URL.Path, "/v1.44") + switch { + case r.Method == http.MethodGet && path == "/containers/json": + name := nameFilter(r) + list := []map[string]any{} + if d.containers[name] { + list = append(list, map[string]any{"Id": "id-" + name, "Names": []string{"/" + name}}) + } + assert.NoError(t, json.NewEncoder(w).Encode(list)) + case r.Method == http.MethodDelete && strings.HasPrefix(path, "/containers/"): + id := strings.TrimPrefix(path, "/containers/") + d.removed = append(d.removed, "container/"+id) + if d.failRemove[id] { + http.Error(w, `{"message":"cannot remove"}`, http.StatusInternalServerError) + return + } + w.WriteHeader(http.StatusNoContent) + case r.Method == http.MethodGet && path == "/networks": + name := nameFilter(r) + list := []map[string]any{} + if d.networks[name] { + list = append(list, map[string]any{"Name": name, "Id": "net-" + name}) + } + assert.NoError(t, json.NewEncoder(w).Encode(list)) + case r.Method == http.MethodDelete && strings.HasPrefix(path, "/networks/"): + d.removed = append(d.removed, "network/"+strings.TrimPrefix(path, "/networks/")) + w.WriteHeader(http.StatusNoContent) + default: + t.Errorf("unexpected request %s %s", r.Method, r.URL.Path) + http.Error(w, "unexpected", http.StatusNotImplemented) + } + } +} + +func TestCleanupFailedIsolation(t *testing.T) { + t.Parallel() + + const network = "toolhive-app-internal" + tests := []struct { + name string + daemon *fakeDaemon + wantRemoved []string + }{ + { + name: "removes all sidecars and the network", + daemon: &fakeDaemon{ + containers: map[string]bool{"app-egress": true, "app-ingress": true, "app-dns": true}, + networks: map[string]bool{network: true}, + }, + wantRemoved: []string{"container/id-app-egress", "container/id-app-ingress", "container/id-app-dns", "network/net-" + network}, + }, + { + name: "a sidecar that fails to remove does not stop the network deletion", + daemon: &fakeDaemon{ + containers: map[string]bool{"app-egress": true, "app-ingress": true, "app-dns": true}, + networks: map[string]bool{network: true}, + failRemove: map[string]bool{"id-app-egress": true}, + }, + wantRemoved: []string{"container/id-app-egress", "container/id-app-ingress", "container/id-app-dns", "network/net-" + network}, + }, + { + name: "absent network is not an error", + daemon: &fakeDaemon{ + containers: map[string]bool{"app-dns": true}, + networks: map[string]bool{}, + }, + wantRemoved: []string{"container/id-app-dns"}, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + api := discoveryHTTPClient(t, tt.daemon.handler(t)) + client := &Client{client: api, api: api} + + client.cleanupFailedIsolation(t.Context(), "app", network) + + assert.Equal(t, tt.wantRemoved, tt.daemon.removed) + }) + } +} diff --git a/pkg/container/docker/client_deploy_test.go b/pkg/container/docker/client_deploy_test.go index b4216afcf8..a8f1364ccb 100644 --- a/pkg/container/docker/client_deploy_test.go +++ b/pkg/container/docker/client_deploy_test.go @@ -11,6 +11,7 @@ import ( "fmt" "net/http" "net/netip" + "strconv" "testing" "github.com/moby/moby/api/types/container" @@ -66,6 +67,9 @@ type fakeDeployOps struct { // cleanupCalls records cleanupFailedIsolation invocations as "workload/network". cleanupCalls []string + // cleanupCtxErr and cleanupHasDeadline describe the context cleanup ran with. + cleanupCtxErr error + cleanupHasDeadline bool // error injection errExternalNetworks error @@ -115,11 +119,10 @@ func (f *fakeDeployOps) createDnsContainer(_ context.Context, _ string, _ bool, return f.dnsID, f.dnsIP, f.errDNS } -func (f *fakeDeployOps) cleanupFailedIsolation(_ context.Context, name, networkName string) { - if f.callOrder != nil { - *f.callOrder = append(*f.callOrder, "cleanupFailedIsolation") - } +func (f *fakeDeployOps) cleanupFailedIsolation(ctx context.Context, name, networkName string) { f.cleanupCalls = append(f.cleanupCalls, name+"/"+networkName) + f.cleanupCtxErr = ctx.Err() + _, f.cleanupHasDeadline = ctx.Deadline() } func (f *fakeDeployOps) getContainerNetworkIP(_ context.Context, _, _ string) (string, error) { @@ -165,8 +168,9 @@ type fakeNetworkProxy struct { setupCalled bool // SetupEgress was called ingressCalled bool // SetupIngress was called capturedSpec proxySpec - ingressPort int // returned by SetupIngress - err error + ingressPort int // returned by SetupIngress + err error // returned by SetupEgress (and SetupIngress when errIngress is nil) + errIngress error // returned by SetupIngress only, when set // callOrder tracks cross-component ordering when shared with fakeDeployOps. callOrder *[]string } @@ -191,6 +195,9 @@ func (f *fakeNetworkProxy) SetupIngress(_ context.Context, spec proxySpec, _ egr } f.ingressCalled = true f.capturedSpec = spec + if f.errIngress != nil { + return 0, f.errIngress + } if f.err != nil { return 0, f.err } @@ -606,32 +613,53 @@ func TestDeployWorkload_GatewayDiscoveryFailsClosed(t *testing.T) { assert.False(t, fops.mcpCalled) } +var errBoom = errors.New("boom") + func TestDeployWorkload_IsolatedSetupFailure_CleansUpNetworkAndDNS(t *testing.T) { t.Parallel() + badPortBinding := func() *runtime.DeployWorkloadOptions { + opts := runtime.NewDeployWorkloadOptions() + opts.ExposedPorts = map[string]struct{}{"8080/tcp": {}} + opts.PortBindings = map[string][]runtime.PortBinding{"8080/tcp": {{HostIP: "127.0.0.1", HostPort: "not-a-port"}}} + return opts + } + tests := []struct { name string fops *fakeDeployOps fproxy *fakeNetworkProxy + opts *runtime.DeployWorkloadOptions // nil means defaults + wantErr error wantCleanup bool }{ - {name: "dns container creation fails", fops: &fakeDeployOps{errDNS: errors.New("boom")}, fproxy: &fakeNetworkProxy{}, wantCleanup: true}, - {name: "gateway discovery fails", fops: &fakeDeployOps{errGateways: errors.New("boom")}, fproxy: &fakeNetworkProxy{}, wantCleanup: true}, - {name: "egress setup fails", fops: &fakeDeployOps{}, fproxy: &fakeNetworkProxy{err: errors.New("boom")}, wantCleanup: true}, - {name: "mcp container creation fails", fops: &fakeDeployOps{errMcp: errors.New("boom")}, fproxy: &fakeNetworkProxy{}, wantCleanup: true}, - {name: "internal network creation fails", fops: &fakeDeployOps{errCreateNetwork: errors.New("boom")}, fproxy: &fakeNetworkProxy{}, wantCleanup: false}, - {name: "success keeps resources", fops: &fakeDeployOps{}, fproxy: &fakeNetworkProxy{}, wantCleanup: false}, + {name: "dns container creation fails", fops: &fakeDeployOps{errDNS: errBoom}, fproxy: &fakeNetworkProxy{}, wantErr: errBoom, wantCleanup: true}, + {name: "gateway discovery fails", fops: &fakeDeployOps{errGateways: errBoom}, fproxy: &fakeNetworkProxy{}, wantErr: errBoom, wantCleanup: true}, + {name: "egress setup fails", fops: &fakeDeployOps{}, fproxy: &fakeNetworkProxy{err: errBoom}, wantErr: errBoom, wantCleanup: true}, + {name: "port binding is invalid", fops: &fakeDeployOps{}, fproxy: &fakeNetworkProxy{}, opts: badPortBinding(), wantErr: strconv.ErrSyntax, wantCleanup: true}, + {name: "mcp container creation fails", fops: &fakeDeployOps{errMcp: errBoom}, fproxy: &fakeNetworkProxy{}, wantErr: errBoom, wantCleanup: true}, + {name: "internal network creation fails", fops: &fakeDeployOps{errCreateNetwork: errBoom}, fproxy: &fakeNetworkProxy{}, wantErr: errBoom, wantCleanup: false}, + {name: "success keeps resources", fops: &fakeDeployOps{}, fproxy: &fakeNetworkProxy{}, wantErr: nil, wantCleanup: false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { t.Parallel() client := newClientWithOpsAndProxy(tt.fops, tt.fproxy) + opts := tt.opts + if opts == nil { + opts = runtime.NewDeployWorkloadOptions() + } _, err := client.DeployWorkload( t.Context(), "image", "app", nil, nil, map[string]string{}, - &permissions.Profile{}, "stdio", runtime.NewDeployWorkloadOptions(), true, + &permissions.Profile{}, "stdio", opts, true, ) - if tt.wantCleanup { + if tt.wantErr != nil { require.Error(t, err) + require.ErrorIs(t, err, tt.wantErr) + } else { + require.NoError(t, err) + } + if tt.wantCleanup { assert.Equal(t, []string{"app/toolhive-app-internal"}, tt.fops.cleanupCalls) } else { assert.Empty(t, tt.fops.cleanupCalls) @@ -640,6 +668,29 @@ func TestDeployWorkload_IsolatedSetupFailure_CleansUpNetworkAndDNS(t *testing.T) } } +// TestDeployWorkload_CleanupSurvivesCancelledContextWithDeadline pins that the +// cleanup is detached from the caller's cancellation (a cancelled request must +// still remove its leaked resources) and is bounded by its own timeout. +func TestDeployWorkload_CleanupSurvivesCancelledContextWithDeadline(t *testing.T) { + t.Parallel() + + ctx, cancel := context.WithCancel(t.Context()) + // Cancel from inside the failing step so the deploy fails with a cancelled + // context, as when a request is aborted mid-setup. + fops := &fakeDeployOps{errDNS: context.Canceled} + client := newClientWithOpsAndProxy(fops, &fakeNetworkProxy{}) + cancel() + + _, err := client.DeployWorkload( + ctx, "image", "app", nil, nil, map[string]string{}, + &permissions.Profile{}, "stdio", runtime.NewDeployWorkloadOptions(), true, + ) + require.ErrorIs(t, err, context.Canceled) + require.Equal(t, []string{"app/toolhive-app-internal"}, fops.cleanupCalls) + require.NoError(t, fops.cleanupCtxErr, "cleanup must not inherit the caller's cancellation") + require.True(t, fops.cleanupHasDeadline, "cleanup must be bounded by its own timeout") +} + func TestDeployWorkload_RestartFailureBeforeMcp_KeepsExistingResources(t *testing.T) { t.Parallel() @@ -669,42 +720,42 @@ func TestDeployWorkload_RestartFailureBeforeMcp_KeepsExistingResources(t *testin } } -func TestDeployWorkload_IngressFailureAfterMcpCreated_DoesNotCleanUp(t *testing.T) { +// TestDeployWorkload_FailureLeavesResourcesForRemove covers failures where the +// deferred isolation cleanup must not run: after the MCP container exists +// (`thv rm` cleans up through RemoveWorkload) and without network isolation. +func TestDeployWorkload_FailureLeavesResourcesForRemove(t *testing.T) { t.Parallel() - for name, fops := range map[string]*fakeDeployOps{ - "mcp ip lookup fails": {errMcpIP: errors.New("boom")}, - } { - t.Run(name, func(t *testing.T) { + tests := []struct { + name string + fops *fakeDeployOps + fproxy *fakeNetworkProxy + isolate bool + transport string + wantErr error + }{ + {name: "mcp ip lookup fails", fops: &fakeDeployOps{errMcpIP: errBoom}, fproxy: &fakeNetworkProxy{}, isolate: true, transport: "sse", wantErr: errBoom}, + {name: "ingress setup fails", fops: &fakeDeployOps{}, fproxy: &fakeNetworkProxy{errIngress: errBoom}, isolate: true, transport: "sse", wantErr: errBoom}, + {name: "no isolation, mcp container creation fails", fops: &fakeDeployOps{errMcp: errBoom}, fproxy: &fakeNetworkProxy{}, isolate: false, transport: "stdio", wantErr: errBoom}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { t.Parallel() - client := newClientWithOps(fops) + client := newClientWithOpsAndProxy(tt.fops, tt.fproxy) opts := runtime.NewDeployWorkloadOptions() opts.ExposedPorts = map[string]struct{}{"8080/tcp": {}} opts.PortBindings = map[string][]runtime.PortBinding{"8080/tcp": {{HostIP: "127.0.0.1", HostPort: ""}}} _, err := client.DeployWorkload( t.Context(), "image", "app", nil, nil, map[string]string{}, - &permissions.Profile{}, "sse", opts, true, + &permissions.Profile{}, tt.transport, opts, tt.isolate, ) - require.Error(t, err) - assert.True(t, fops.mcpCalled) - assert.Empty(t, fops.cleanupCalls, "MCP container exists, so thv rm can clean up") + require.ErrorIs(t, err, tt.wantErr) + assert.True(t, tt.fops.mcpCalled) + assert.Empty(t, tt.fops.cleanupCalls) }) } } -func TestDeployWorkload_NoIsolationFailure_DoesNotCleanUp(t *testing.T) { - t.Parallel() - - fops := &fakeDeployOps{errMcp: errors.New("boom")} - client := newClientWithOps(fops) - _, err := client.DeployWorkload( - t.Context(), "image", "app", nil, nil, map[string]string{}, - &permissions.Profile{}, "stdio", runtime.NewDeployWorkloadOptions(), false, - ) - require.Error(t, err) - assert.Empty(t, fops.cleanupCalls) -} - func TestDeployWorkload_PodmanHostDiscovery(t *testing.T) { t.Parallel() for _, allow := range []bool{false, true} { From 316a7f5eab978858f958d03212bdeeee253c07bd Mon Sep 17 00:00:00 2001 From: Alex Castillo Date: Thu, 19 Nov 2026 23:42:07 -0400 Subject: [PATCH 5/5] Merge isolation cleanup tests into one table Rename by behavior (cleanup only before the MCP container exists) and fold the restart/remove cases into a single table. Cancel the context inside the failing step so the cancellation test also holds against a real daemon. --- pkg/container/docker/client_deploy_test.go | 142 +++++++++------------ 1 file changed, 59 insertions(+), 83 deletions(-) diff --git a/pkg/container/docker/client_deploy_test.go b/pkg/container/docker/client_deploy_test.go index a8f1364ccb..222dfd16ca 100644 --- a/pkg/container/docker/client_deploy_test.go +++ b/pkg/container/docker/client_deploy_test.go @@ -76,6 +76,9 @@ type fakeDeployOps struct { errCreateNetwork error errDNS error errMcp error + + // onCreateDNS, when set, runs inside createDnsContainer before it returns. + onCreateDNS func() } func (f *fakeDeployOps) createExternalNetworks(_ context.Context) error { @@ -116,6 +119,9 @@ func (f *fakeDeployOps) createDnsContainer(_ context.Context, _ string, _ bool, *f.callOrder = append(*f.callOrder, "createDnsContainer") } f.dnsCalled = true + if f.onCreateDNS != nil { + f.onCreateDNS() + } return f.dnsID, f.dnsIP, f.errDNS } @@ -615,7 +621,13 @@ func TestDeployWorkload_GatewayDiscoveryFailsClosed(t *testing.T) { var errBoom = errors.New("boom") -func TestDeployWorkload_IsolatedSetupFailure_CleansUpNetworkAndDNS(t *testing.T) { +// TestDeployWorkload_SetupFailureCleanup pins when a failed deploy removes the +// isolation resources (internal network, DNS, proxies): only for a new +// workload that failed before its MCP container exists. Once the MCP container +// exists, `thv rm` cleans up through RemoveWorkload; a restart keeps the +// resources that belong to the existing workload; without isolation there is +// nothing to clean up. +func TestDeployWorkload_SetupFailureCleanup(t *testing.T) { t.Parallel() badPortBinding := func() *runtime.DeployWorkloadOptions { @@ -624,41 +636,63 @@ func TestDeployWorkload_IsolatedSetupFailure_CleansUpNetworkAndDNS(t *testing.T) opts.PortBindings = map[string][]runtime.PortBinding{"8080/tcp": {{HostIP: "127.0.0.1", HostPort: "not-a-port"}}} return opts } + ingressOpts := func() *runtime.DeployWorkloadOptions { + opts := runtime.NewDeployWorkloadOptions() + opts.ExposedPorts = map[string]struct{}{"8080/tcp": {}} + opts.PortBindings = map[string][]runtime.PortBinding{"8080/tcp": {{HostIP: "127.0.0.1", HostPort: ""}}} + return opts + } + existingMcp := &existingLookup{items: []container.Summary{{ID: "mcp-id", Names: []string{"/app"}}}} + failedLookup := &existingLookup{err: errors.New("daemon unavailable")} tests := []struct { name string fops *fakeDeployOps fproxy *fakeNetworkProxy - opts *runtime.DeployWorkloadOptions // nil means defaults + transport string + isolate bool + opts func() *runtime.DeployWorkloadOptions // nil means defaults + existing *existingLookup // nil means no existing MCP container wantErr error wantCleanup bool + wantMcp bool }{ - {name: "dns container creation fails", fops: &fakeDeployOps{errDNS: errBoom}, fproxy: &fakeNetworkProxy{}, wantErr: errBoom, wantCleanup: true}, - {name: "gateway discovery fails", fops: &fakeDeployOps{errGateways: errBoom}, fproxy: &fakeNetworkProxy{}, wantErr: errBoom, wantCleanup: true}, - {name: "egress setup fails", fops: &fakeDeployOps{}, fproxy: &fakeNetworkProxy{err: errBoom}, wantErr: errBoom, wantCleanup: true}, - {name: "port binding is invalid", fops: &fakeDeployOps{}, fproxy: &fakeNetworkProxy{}, opts: badPortBinding(), wantErr: strconv.ErrSyntax, wantCleanup: true}, - {name: "mcp container creation fails", fops: &fakeDeployOps{errMcp: errBoom}, fproxy: &fakeNetworkProxy{}, wantErr: errBoom, wantCleanup: true}, - {name: "internal network creation fails", fops: &fakeDeployOps{errCreateNetwork: errBoom}, fproxy: &fakeNetworkProxy{}, wantErr: errBoom, wantCleanup: false}, - {name: "success keeps resources", fops: &fakeDeployOps{}, fproxy: &fakeNetworkProxy{}, wantErr: nil, wantCleanup: false}, + {name: "dns container creation fails", fops: &fakeDeployOps{errDNS: errBoom}, fproxy: &fakeNetworkProxy{}, transport: "stdio", isolate: true, wantErr: errBoom, wantCleanup: true}, + {name: "gateway discovery fails", fops: &fakeDeployOps{errGateways: errBoom}, fproxy: &fakeNetworkProxy{}, transport: "stdio", isolate: true, wantErr: errBoom, wantCleanup: true}, + {name: "egress setup fails", fops: &fakeDeployOps{}, fproxy: &fakeNetworkProxy{err: errBoom}, transport: "stdio", isolate: true, wantErr: errBoom, wantCleanup: true}, + {name: "port binding is invalid", fops: &fakeDeployOps{}, fproxy: &fakeNetworkProxy{}, transport: "stdio", isolate: true, opts: badPortBinding, wantErr: strconv.ErrSyntax, wantCleanup: true}, + {name: "mcp container creation fails", fops: &fakeDeployOps{errMcp: errBoom}, fproxy: &fakeNetworkProxy{}, transport: "stdio", isolate: true, wantErr: errBoom, wantCleanup: true, wantMcp: true}, + {name: "internal network creation fails", fops: &fakeDeployOps{errCreateNetwork: errBoom}, fproxy: &fakeNetworkProxy{}, transport: "stdio", isolate: true, wantErr: errBoom}, + {name: "success keeps resources", fops: &fakeDeployOps{}, fproxy: &fakeNetworkProxy{}, transport: "stdio", isolate: true, wantMcp: true}, + {name: "mcp ip lookup fails after mcp container exists", fops: &fakeDeployOps{errMcpIP: errBoom}, fproxy: &fakeNetworkProxy{}, transport: "sse", isolate: true, opts: ingressOpts, wantErr: errBoom, wantMcp: true}, + {name: "ingress setup fails after mcp container exists", fops: &fakeDeployOps{}, fproxy: &fakeNetworkProxy{errIngress: errBoom}, transport: "sse", isolate: true, opts: ingressOpts, wantErr: errBoom, wantMcp: true}, + {name: "no isolation, mcp container creation fails", fops: &fakeDeployOps{errMcp: errBoom}, fproxy: &fakeNetworkProxy{}, transport: "stdio", isolate: false, opts: ingressOpts, wantErr: errBoom, wantMcp: true}, + {name: "restart with stopped mcp container keeps resources", fops: &fakeDeployOps{errDNS: errBoom}, fproxy: &fakeNetworkProxy{}, transport: "stdio", isolate: true, existing: existingMcp, wantErr: errBoom}, + {name: "restart with failed existence lookup keeps resources", fops: &fakeDeployOps{errDNS: errBoom}, fproxy: &fakeNetworkProxy{}, transport: "stdio", isolate: true, existing: failedLookup, wantErr: errBoom}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { t.Parallel() client := newClientWithOpsAndProxy(tt.fops, tt.fproxy) - opts := tt.opts - if opts == nil { - opts = runtime.NewDeployWorkloadOptions() + if tt.existing != nil { + client.api = &fakeDockerAPI{listFunc: func(_ context.Context, _ mobyclient.ContainerListOptions) ([]container.Summary, error) { + return tt.existing.items, tt.existing.err + }} + } + opts := runtime.NewDeployWorkloadOptions() + if tt.opts != nil { + opts = tt.opts() } _, err := client.DeployWorkload( t.Context(), "image", "app", nil, nil, map[string]string{}, - &permissions.Profile{}, "stdio", opts, true, + &permissions.Profile{}, tt.transport, opts, tt.isolate, ) if tt.wantErr != nil { - require.Error(t, err) require.ErrorIs(t, err, tt.wantErr) } else { require.NoError(t, err) } + assert.Equal(t, tt.wantMcp, tt.fops.mcpCalled) if tt.wantCleanup { assert.Equal(t, []string{"app/toolhive-app-internal"}, tt.fops.cleanupCalls) } else { @@ -668,6 +702,13 @@ func TestDeployWorkload_IsolatedSetupFailure_CleansUpNetworkAndDNS(t *testing.T) } } +// existingLookup is what the fake Docker API returns when DeployWorkload looks +// for an already existing MCP container by name. +type existingLookup struct { + items []container.Summary + err error +} + // TestDeployWorkload_CleanupSurvivesCancelledContextWithDeadline pins that the // cleanup is detached from the caller's cancellation (a cancelled request must // still remove its leaked resources) and is bounded by its own timeout. @@ -675,11 +716,11 @@ func TestDeployWorkload_CleanupSurvivesCancelledContextWithDeadline(t *testing.T t.Parallel() ctx, cancel := context.WithCancel(t.Context()) - // Cancel from inside the failing step so the deploy fails with a cancelled - // context, as when a request is aborted mid-setup. - fops := &fakeDeployOps{errDNS: context.Canceled} + // Cancel from inside the failing step (after the existing-container lookup + // has run) so the deploy fails with a cancelled context, as when a request + // is aborted mid-setup. + fops := &fakeDeployOps{errDNS: context.Canceled, onCreateDNS: cancel} client := newClientWithOpsAndProxy(fops, &fakeNetworkProxy{}) - cancel() _, err := client.DeployWorkload( ctx, "image", "app", nil, nil, map[string]string{}, @@ -691,71 +732,6 @@ func TestDeployWorkload_CleanupSurvivesCancelledContextWithDeadline(t *testing.T require.True(t, fops.cleanupHasDeadline, "cleanup must be bounded by its own timeout") } -func TestDeployWorkload_RestartFailureBeforeMcp_KeepsExistingResources(t *testing.T) { - t.Parallel() - - tests := []struct { - name string - listErr error - items []container.Summary - }{ - {name: "stopped MCP container exists", items: []container.Summary{{ID: "mcp-id", Names: []string{"/app"}}}}, - {name: "existence lookup fails", listErr: errors.New("daemon unavailable")}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - t.Parallel() - fops := &fakeDeployOps{errDNS: errors.New("boom")} - client := newClientWithOpsAndProxy(fops, &fakeNetworkProxy{}) - client.api = &fakeDockerAPI{listFunc: func(_ context.Context, _ mobyclient.ContainerListOptions) ([]container.Summary, error) { - return tt.items, tt.listErr - }} - _, err := client.DeployWorkload( - t.Context(), "image", "app", nil, nil, map[string]string{}, - &permissions.Profile{}, "stdio", runtime.NewDeployWorkloadOptions(), true, - ) - require.Error(t, err) - assert.Empty(t, fops.cleanupCalls, "network and sidecars belong to the existing workload") - }) - } -} - -// TestDeployWorkload_FailureLeavesResourcesForRemove covers failures where the -// deferred isolation cleanup must not run: after the MCP container exists -// (`thv rm` cleans up through RemoveWorkload) and without network isolation. -func TestDeployWorkload_FailureLeavesResourcesForRemove(t *testing.T) { - t.Parallel() - - tests := []struct { - name string - fops *fakeDeployOps - fproxy *fakeNetworkProxy - isolate bool - transport string - wantErr error - }{ - {name: "mcp ip lookup fails", fops: &fakeDeployOps{errMcpIP: errBoom}, fproxy: &fakeNetworkProxy{}, isolate: true, transport: "sse", wantErr: errBoom}, - {name: "ingress setup fails", fops: &fakeDeployOps{}, fproxy: &fakeNetworkProxy{errIngress: errBoom}, isolate: true, transport: "sse", wantErr: errBoom}, - {name: "no isolation, mcp container creation fails", fops: &fakeDeployOps{errMcp: errBoom}, fproxy: &fakeNetworkProxy{}, isolate: false, transport: "stdio", wantErr: errBoom}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - t.Parallel() - client := newClientWithOpsAndProxy(tt.fops, tt.fproxy) - opts := runtime.NewDeployWorkloadOptions() - opts.ExposedPorts = map[string]struct{}{"8080/tcp": {}} - opts.PortBindings = map[string][]runtime.PortBinding{"8080/tcp": {{HostIP: "127.0.0.1", HostPort: ""}}} - _, err := client.DeployWorkload( - t.Context(), "image", "app", nil, nil, map[string]string{}, - &permissions.Profile{}, tt.transport, opts, tt.isolate, - ) - require.ErrorIs(t, err, tt.wantErr) - assert.True(t, tt.fops.mcpCalled) - assert.Empty(t, tt.fops.cleanupCalls) - }) - } -} - func TestDeployWorkload_PodmanHostDiscovery(t *testing.T) { t.Parallel() for _, allow := range []bool{false, true} {