Skip to content

Clean up isolation resources when workload setup fails - #7049

Open
pcbeingused333 wants to merge 6 commits into
stacklok:mainfrom
pcbeingused333:c0773-cleanup-failed-setup
Open

pcbeingused333 wants to merge 6 commits into
stacklok:mainfrom
pcbeingused333:c0773-cleanup-failed-setup

Conversation

@pcbeingused333

@pcbeingused333 pcbeingused333 commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Summary

When a network-isolated workload fails during setup before its MCP container exists, its toolhive-<name>-internal network and <name>-dns container (plus egress, if it was created) are left behind. thv rm cannot remove them, because RemoveWorkload derives their names from the MCP container. Each leaked network uses up one of Docker's address pools, so after enough failures every new workload fails with "all predefined address pools have been fully subnetted".

  • DeployWorkload now has a deferred hook, registered after the internal network is created. It runs a new cleanupFailedIsolation when setup fails before createMcpContainer succeeds.
  • cleanupFailedIsolation removes the egress, ingress and dns containers and the internal network. It is best-effort: failures are only logged, so the caller still gets the original error. It tries every sidecar and always deletes the network, even if an earlier removal fails. It runs with context.WithoutCancel plus a 30 s timeout, so a cancelled request still cleans up without being able to hang.
  • Cleanup only runs for a new workload. A restart reaches DeployWorkload with the stopped MCP container still in place, so the network and sidecars belong to the existing workload and are left alone when a restart attempt fails. If the existence lookup itself fails, it is treated as existing.
  • Failures after the MCP container exists are unchanged, as the issue describes, because thv rm already cleans up through RemoveWorkload in that case. Non-isolated deploys and a failed createNetwork are unchanged too.

Fixes #7045

Type of change

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

Test plan

  • Unit tests: go vet and go test ./pkg/container/docker/ (the changed package; the full task test was not run)
  • E2E tests (task test-e2e)
  • Linting (task lint-fix)
  • Manual testing (describe below)

TestDeployWorkload_SetupFailureCleanup is one table (transport, isolation, deploy options, existing MCP container) that pins when a failed deploy removes the isolation resources: only for a new workload that fails before its MCP container exists (DNS creation, gateway discovery, egress setup, an invalid host port, or MCP container creation). Each case also checks the returned error. Cleanup does not run when network creation fails, when the deploy succeeds, after the MCP container exists (MCP IP lookup or ingress setup failing, which thv rm handles), without isolation, or on a restart (existing MCP container, or a failed existence lookup). TestDeployWorkload_CleanupSurvivesCancelledContextWithDeadline cancels the caller's context from inside the failing DNS step and checks that cleanup still runs, with a live context that has its own deadline. TestCleanupFailedIsolation runs the real cleanup against a fake Docker daemon: all three sidecars and the network are removed, a sidecar that fails to remove does not stop the others or the network deletion, and an absent network is not an error. The cleanup cases fail on main and pass with this change; the restart cases fail without the existing-container check.

Does this introduce a user-facing change?

Yes. A failed setup of a network-isolated workload no longer leaves its internal network and DNS/egress containers behind.

Special notes for reviewers

The other trigger in #7043 (removing a workload whose start is still in flight) is not addressed here.

This change was prepared with the help of an AI coding assistant (Claude).

pcbeingused333 and others added 2 commits November 3, 2026 16:51
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 <noreply@anthropic.com>
Signed-off-by: Alex Castillo <alex.castillog33@gmail.com>
…er 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 <noreply@anthropic.com>
Signed-off-by: Alex Castillo <alex.castillog33@gmail.com>
@codecov

codecov Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 87.50000% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 81.61%. Comparing base (2d33d6b) to head (c8ac304).

Files with missing lines Patch % Lines
pkg/container/docker/client.go 87.50% 3 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #7049      +/-   ##
==========================================
+ Coverage   81.58%   81.61%   +0.02%     
==========================================
  Files         898      898              
  Lines       91550    91574      +24     
==========================================
+ Hits        74690    74737      +47     
+ Misses      16855    16832      -23     
  Partials        5        5              

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

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

@tgrunnagle tgrunnagle left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Review

The PR is a small bug fix in pkg/container/docker/client.go (about 110 added lines across two files). DeployWorkload now registers a deferred cleanup once the internal network exists, so a network-isolated workload that fails before its MCP container is created no longer leaks the toolhive-<name>-internal network and the dns/egress sidecars (#7045). It takes the issue's first acceptable fix (clean up on failed setup) and leaves #7043 and RemoveWorkload alone. For a fresh deploy the approach is sound: gating on mcpCreated keeps post-MCP failures on the existing thv rm path, and detaching the cleanup context from cancellation is the right call.

The main trade-off is that the gate asks whether this call created the MCP container, not whether this call created the network and sidecars. createNetwork, createDnsContainer and createContainer all reuse existing resources, and thv restart reaches DeployWorkload with the stopped MCP container still in place. A transient failure before createMcpContainer on a restart therefore removes the network and sidecars an existing workload depends on. The tests also only check the defer wiring through a fake; the real cleanupFailedIsolation and the WithoutCancel behavior are not covered.

No documentation update is needed. The user-visible effect is that failed setups stop leaking Docker resources.

Findings

# Severity Finding Location Raised by
1 MEDIUM Failure cleanup removes the reused network and sidecars of a restarted workload pkg/container/docker/client.go:271 correctness, scope discipline, tests
2 MEDIUM Real cleanupFailedIsolation is never exercised by a test pkg/container/docker/client_deploy_test.go:116 tests, readability
3 MEDIUM No test pins the context.WithoutCancel behavior pkg/container/docker/client_deploy_test.go:116 tests
4 MEDIUM Table omits the port-binding failure and never asserts the error outcome pkg/container/docker/client_deploy_test.go:616 tests
5 MEDIUM PR title and commit subjects use a Conventional Commits prefix PR title and commits readability
6 LOW Cleanup context has no timeout pkg/container/docker/client.go:276 correctness
7 LOW A failed sidecar removal stops the remaining removals and the network delete pkg/container/docker/client.go:1400 correctness
8 LOW Made-up label map in cleanupFailedIsolation is not explained pkg/container/docker/client.go:1398 readability
9 LOW Ingress test does not exercise SetupIngress; three tests overlap pkg/container/docker/client_deploy_test.go:641 tests, readability
10 LOW Dead callOrder append and unasserted cleanup ordering pkg/container/docker/client_deploy_test.go:117 tests, readability

Additional findings

  • [MEDIUM] PR title and commit subjects use a Conventional Commits prefix: the title and both commit subjects start with fix(docker):. CLAUDE.md says "Do NOT use Conventional Commits" and .claude/rules/pr-creation.md says "PR titles must NOT use conventional commit prefixes". The commit subjects also exceed the 50-character limit (the second wraps mid-word into its body). Because commits are squashed with the PR title, the title is what lands in history. Suggested title: Clean up isolation resources when workload setup fails. Raised by: readability.

How to test

  1. task test (or the pkg/container/docker package tests): the new TestDeployWorkload_* cases should pass.
  2. Mutation checks, which currently do not fail any test: delete the lb.AddNetworkIsolationLabel(labels, true) line in cleanupFailedIsolation, or replace context.WithoutCancel(ctx) with ctx at the defer. Both leave the suite green.
  3. Manual, fresh deploy: run a network-isolated workload with a step that fails after DNS startup (for example the bridge with no IPv6 gateway from #7045). Afterwards docker network ls | grep toolhive-<name>-internal and docker ps -a | grep <name>-dns should show nothing.
  4. Manual, restart: run an isolated workload, thv stop it, induce a failure before MCP creation (for example a bad port binding), then thv restart. Check whether the network and sidecars were removed and whether the next thv restart starts the stopped MCP container.

Reviewed by dev:review-pr (finders: correctness, readability, tests, scope discipline). Generated with Claude Code.

Comment on lines +271 to +278
// 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.
defer func() {
if retErr != nil && !mcpCreated {
c.ops.cleanupFailedIsolation(context.WithoutCancel(ctx), name, networkName)
}
}()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[MEDIUM] Failure cleanup removes the reused network and sidecars of a restarted workload

mcpCreated only says whether this call created the MCP container. thv restart stops the workload (StopWorkload leaves the MCP container and network in place) and then reaches DeployWorkload, where createNetwork, createDnsContainer and createContainer reuse what already exists. If a step before createMcpContainer fails (gateway discovery, egress setup, port bindings), this defer removes the network and the dns/egress/ingress containers of a workload whose MCP container is still there, so the comment above ("thv rm cannot find them") is not true on that path. Before this change the network survived and a retry could succeed. I could not confirm from the code whether Docker then refuses to start the old container against the recreated network, but createAndStartContainer already handles a start that fails because "its network vanished", so the failure mode is known.

Recommendation: only clean up what this call created. For example, check findExistingContainer(ctx, name) before createNetwork and skip the defer (or at least the network removal) when the MCP container already exists. If removing them is the intended trade-off, say so in a comment here. Either way, add a test with a pre-existing MCP container and a pre-MCP failure.

Raised by: correctness, scope discipline, tests. Verified: confirmed.

Comment thread pkg/container/docker/client.go Outdated
// fails before the MCP container is created. Remove them in that case.
defer func() {
if retErr != nil && !mcpCreated {
c.ops.cleanupFailedIsolation(context.WithoutCancel(ctx), name, networkName)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[LOW] Cleanup context has no timeout

context.WithoutCancel(ctx) correctly lets cleanup run after a cancelled request, but it also drops any deadline. cleanupFailedIsolation makes several Docker API calls (list and remove for three containers, then list and remove for the network). With a wedged daemon the DeployWorkload error return blocks, and a user who already cancelled cannot interrupt it.

Recommendation: bound the detached context, for example cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second) with defer cancel() around the call.

Raised by: correctness. Verified: confirmed.

Comment thread pkg/container/docker/client.go Outdated
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 {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[LOW] A failed sidecar removal stops the remaining removals and the network delete

removeProxyContainers returns on the first non-NotFound ContainerRemove error. If the egress removal fails, ingress and dns are skipped, and deleteNetwork then fails because dns is still attached. The new caller only logs a WARN, so the leak this PR targets can persist. A forced removal rarely fails, so this is unlikely, but a best-effort cleanup should keep going.

Recommendation: have the cleanup path try every sidecar and always attempt deleteNetwork, either by collecting errors with errors.Join in removeProxyContainers or by removing the -egress, -ingress and -dns containers directly in cleanupFailedIsolation.

Raised by: correctness. Verified: confirmed.

Comment thread pkg/container/docker/client.go Outdated
Comment on lines +1398 to +1400
labels := map[string]string{}
lb.AddNetworkIsolationLabel(labels, true)
if err := c.removeProxyContainers(ctx, name, labels); err != nil {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[LOW] The made-up label map is not explained

cleanupFailedIsolation builds an empty map and sets the isolation label only so removeProxyContainers gets past its HasNetworkIsolation early return. Nothing says so, and a reader has to open removeProxyContainers to find out. That function's doc comment ("removes the MCP server container and any proxy containers") also does not describe what it does.

Recommendation: add a short why-comment here (no MCP container exists to read the label from), or move the suffix loop into a helper that both callers share so no fake labels are needed.

Raised by: readability. Verified: confirmed.

Comment on lines +116 to +121
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)
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[MEDIUM] The real cleanupFailedIsolation is never exercised

This fake replaces Client.cleanupFailedIsolation, so the real method has no test: the isolation label, the -dns/-egress/-ingress names, the deleteNetwork call, and the behavior after a failed removal. Deleting the AddNetworkIsolationLabel call would turn removeProxyContainers into a no-op and bring back #7045 while every new test stays green. A fakeDockerAPI is not enough, because removeProxyContainers removes through the concrete c.client.ContainerRemove and deleteNetwork uses c.client.NetworkList/NetworkRemove.

Recommendation: add a table-driven test on the real method using an httptest-backed moby client, as hostdiscovery_test.go does. Assert that the three sidecars and the network are removed, that a failed sidecar removal still attempts the network delete, and that an absent network is not an error.

Raised by: tests, readability. Verified: confirmed.

return f.dnsID, f.dnsIP, f.errDNS
}

func (f *fakeDeployOps) cleanupFailedIsolation(_ context.Context, name, networkName string) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[MEDIUM] No test pins the context.WithoutCancel behavior

The fake ignores its context and every new test passes the live t.Context(). The PR description lists WithoutCancel as a feature, but replacing context.WithoutCancel(ctx) with ctx at the defer leaves the suite green.

Recommendation: record ctx.Err() at call time in the fake, then add a case that passes an already-cancelled context with a failing step and asserts the recorded error is nil and cleanup ran once.

Raised by: tests. Verified: confirmed.

Comment on lines +616 to +621
{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},

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[MEDIUM] The table omits the port-binding failure and never asserts the error outcome

#7045 names port-binding generation as a failure point, and generatePortBindings runs after the cleanup defer is registered, but no case covers it (an unparsable HostPort in opts.PortBindings triggers it). The wantCleanup: false rows also never check err: "success keeps resources" has no require.NoError and "internal network creation fails" has no require.Error, so either could pass for the wrong reason (.claude/rules/testing.md).

Recommendation: add a wantErr column and assert require.Error or require.NoError in every case (with ErrorIs on a sentinel, since the code wraps with %w), and add a port-binding case with a per-case opts field.

Raised by: tests. Verified: confirmed.

Comment on lines +641 to +662
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")
})
}
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[LOW] The ingress test does not exercise SetupIngress, and three tests overlap

Despite its name, this test only injects errMcpIP. The SetupIngress error return, the last failure point after mcpCreated = true, is untested because fakeNetworkProxy has one err field shared with SetupEgress. The loop over a one-entry map adds scaffolding for no benefit, and TestDeployWorkload_NoIsolationFailure_DoesNotCleanUp repeats the same setup. The first test's name (CleansUpNetworkAndDNS) also covers cases that assert no cleanup. .claude/rules/testing.md asks for table-driven tests, consolidation, and names that match what is asserted.

Recommendation: add an errIngress field to fakeNetworkProxy, fold the three tests into one table with transport, isolate and opts columns, and name it for the behavior (cleanup only before the MCP container exists).

Raised by: tests, readability. Verified: confirmed.

Comment on lines +117 to +120
if f.callOrder != nil {
*f.callOrder = append(*f.callOrder, "cleanupFailedIsolation")
}
f.cleanupCalls = append(f.cleanupCalls, name+"/"+networkName)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[LOW] The callOrder append is dead and cleanup ordering is not asserted

None of the new tests builds a fakeDeployOps with callOrder, so this append never runs, and nothing shows cleanup happens after the failing step. The "workload/network" joined string in cleanupCalls is also an ad hoc encoding.

Recommendation: wire a shared callOrder in the table and assert that cleanup follows the failing step (and is absent on success), or drop the callOrder lines. Storing a small struct instead of a joined string would be clearer.

Raised by: tests, readability. Verified: confirmed.

pcbeingused333 and others added 3 commits November 19, 2026 23:42
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 <noreply@anthropic.com>
Signed-off-by: Alex Castillo <alex.castillog33@gmail.com>
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 <alex.castillog33@gmail.com>
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.
@pcbeingused333 pcbeingused333 changed the title fix(docker): clean up isolation resources when workload setup fails Clean up isolation resources when workload setup fails Nov 20, 2026
@pcbeingused333

Copy link
Copy Markdown
Contributor Author

Thanks, @tgrunnagle. Pushed the follow-up for your review: cleanup now only runs if the MCP container did not exist before the attempt (so a restart failure keeps the existing network and sidecars), the isolation tests are merged into one behavior-named table and run against a fake Docker daemon, and the cancellation case is cancelled inside the failing step so it holds against a real daemon too. Commits are signed and the title/body are updated to match.

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Failed workload setup leaves its network and DNS container behind

2 participants