Skip to content

Clean up isolation resources when workload setup fails - #7049

Merged
ChrisJBurns merged 7 commits into
stacklok:mainfrom
pcbeingused333:c0773-cleanup-failed-setup
Nov 26, 2026
Merged

ChrisJBurns merged 7 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 only the sidecars this attempt started to create (DNS, and egress once its setup was reached; ingress is set up after the MCP container, so never), and only containers carrying the auxiliary workload label, so a user workload named like a sidecar (e.g. app-egress) survives. It then deletes the internal network. It is best-effort: failures are only logged, so the caller still gets the original error. It tries every such 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: the attempted sidecars and the network are removed, a sidecar that was never attempted or a same-named container without the auxiliary workload label is left alone, 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 <[email protected]>
Signed-off-by: Alex Castillo <[email protected]>
…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 <[email protected]>
Signed-off-by: Alex Castillo <[email protected]>
@codecov

codecov Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 91.17647% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 82.13%. Comparing base (2d33d6b) to head (dd454b6).
⚠️ Report is 60 commits behind head on main.

Files with missing lines Patch % Lines
pkg/container/docker/client.go 91.17% 3 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #7049      +/-   ##
==========================================
+ Coverage   81.58%   82.13%   +0.55%     
==========================================
  Files         898      931      +33     
  Lines       91550    94344    +2794     
==========================================
+ Hits        74692    77493    +2801     
+ Misses      16853    16846       -7     
  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 thread pkg/container/docker/client.go Resolved
Comment thread pkg/container/docker/client.go Resolved
Comment thread pkg/container/docker/client.go Resolved
Comment thread pkg/container/docker/client.go Resolved
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 <[email protected]>
Signed-off-by: Alex Castillo <[email protected]>
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 <[email protected]>
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.

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

See the inline comments.

Comment thread pkg/container/docker/client.go Resolved
Rollback derived all three sidecar names and force-removed any matching
container, so an unrelated workload named e.g. "app-ingress" was deleted
when deploying "app" failed. Remove only the sidecars this attempt
started to create (ingress is never one of them), and only when the
container carries the auxiliary workload label.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: Alex <[email protected]>
@ChrisJBurns
ChrisJBurns merged commit ac27d5e into stacklok:main Nov 26, 2026
46 checks passed
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

3 participants