fix(trainer): clean up network on container setup failure #822
🎉 Welcome to the Kubeflow SDK! 🎉
Thanks for opening your first PR! We're happy to have you as part of our community 🚀
Here's what happens next:
Join the community:
Feel free to ask questions in the comments if you need any help or clarification!
Thanks again for contributing to Kubeflow! 🙏
I ran this locally on Windows with Python 3.12.
pytest kubeflow/trainer/backends/container/backend_test.py: 46 passedruff check and ruff format --check on the container backend: cleantest_train_cleanup_on_failure cases against backend.py from main. Only "image pull fails after network creation" fails there, which is the leak from #820, so the test does catch the bug. The other three pass on main as well, which makes sense since they pin behaviour that already worked.Dropping the inline network cleanup around _run_initializers looks right to me. With the unconditional cleanup in the outer handler, keeping it would delete the network twice.
Two small things, neither blocking:
1. In the "cleanup failure preserves original error" case the test returns before checking the workdir. shutil.rmtree sits in the same try, after _cleanup_container_resources, so a cleanup error would skip removing the workdir. _cleanup_container_resources swallows its own errors today, so this cannot happen in practice, but moving the rmtree out of that try would make it independent.
2. The issue reproduced three failure points (script generation, image preparation, env construction) and the tests cover image preparation. All three go through the same handler so that is enough to prove the fix. Just mentioning it.
#823 targets the same issue. I left a note there about the initializer path.
Thanks for testing this and for the detailed review.
Agreed on both points. For the workdir cleanup case, _cleanup_container_resources() currently contains its own error handling, so I’d prefer to keep that structure unchanged in this PR rather than broaden the fix beyond the network leak in #820.
For the regression coverage, I intentionally kept one representative early-setup failure because the script/image/environment paths all reach the same outer handler. I also kept the partial-container and cleanup-exception cases to cover the surrounding cleanup behavior.
Thanks also for checking the initializer path. Removing its inline network deletion was specifically to ensure that cleanup happens in one place and the network is not deleted twice.
Makes sense on both, keeping the scope to the network leak is the right call. Tests and lint were clean on my side.
/lgtm
Coverage Report for CI Build 37378708026
[!WARNING]
Build has drifted: This PR's base is out of sync with its target branch, so coverage data may include unrelated changes.
Quick fix: rebase this PR. Learn more →
Coverage increased (+0.2%) to 85.684%
Details
Uncovered Changes
No uncovered changes found.
Coverage Regressions
No coverage regressions found.
---
Coverage Stats
| |  |
| :-- | --: |
| Relevant Lines: | 7439 |
| Covered Lines: | 6374 |
| Line Coverage: | 85.68% |
| Coverage Strength: | 1.71 hits per line |
---
##### 💛 - Coveralls
/ok-to-test
Thanks @dlanov for the fix and the regression tests! 🙏 This review was done with the help of AI tools.
Can we fold these cases into test_train instead of adding a separate test? test_train already has FAILED cases (initializer exit code / timeout) using the same expected_error pattern, and those cases go through the cleanup path this PR changes (the initializer-specific delete_network was removed). Right now nothing checks that cleanup.
Replace the per-case expected_containers_removed / expected_network_deleted with one generic check in the except branch. Then the initializer failure cases get covered too:
<details><summary>Sketch (verified locally: 19 passed; the pull_image case fails on pre-fix code)</summary>
# new cases appended to test_train's parametrize list
TestCase(name="network creation fails", expected_status=FAILED,
config={"fail_method": "create_network"}, expected_error=RuntimeError),
TestCase(name="image pull fails after network creation", expected_status=FAILED,
config={"fail_method": "pull_image"}, expected_error=RuntimeError),
TestCase(name="container creation fails after some containers were created",
expected_status=FAILED,
config={"num_nodes": 3, "fail_method": "create_and_start_container",
"fail_after_calls": 2},
expected_error=RuntimeError),
TestCase(name="cleanup failure preserves original error", expected_status=FAILED,
config={"fail_method": "pull_image", "cleanup_error": True},
expected_error=RuntimeError),
def test_train(container_backend, tmp_path, monkeypatch, test_case):
adapter = container_backend._adapter
workdir = tmp_path / "job"
workdir.mkdir()
monkeypatch.setattr(
"kubeflow.trainer.backends.container.utils.create_workdir", lambda _: str(workdir)
)
try:
# Make an adapter call fail to exercise cleanup in train()
fail_method = test_case.config.get("fail_method")
if fail_method:
original_method = getattr(adapter, fail_method)
calls_before_failure = test_case.config.get("fail_after_calls", 0)
def mock_fail(*args, **kwargs):
nonlocal calls_before_failure
if calls_before_failure == 0:
raise RuntimeError("setup failed")
calls_before_failure -= 1
return original_method(*args, **kwargs)
monkeypatch.setattr(adapter, fail_method, mock_fail)
if test_case.config.get("cleanup_error"):
# OSError != RuntimeError, so the type check proves the original error is re-raised
monkeypatch.setattr(container_backend, "_cleanup_container_resources",
Mock(side_effect=OSError("cleanup failed")))
... # existing body unchanged
except Exception as e:
assert type(e) is test_case.expected_error
# A failed train() must clean up every resource it created
if not test_case.config.get("cleanup_error"):
created_ids = [c["id"] for c in adapter.containers_created]
assert sorted(adapter.containers_removed) == sorted(created_ids)
assert adapter.networks_deleted == [n["id"] for n in adapter.networks_created]
assert not workdir.exists()
</details>
This also drops the nullcontext conditional, the early return, and pull_policy = "Always", which isn't needed because the default IfNotPresent already pulls with the mock adapter.
Thanks @andreyvelich — I’ve updated the tests as suggested.
test_train parametrization
test_train_cleanup_on_failure
pull_policy = "Always" path
backend.py unchanged
Validation:
uv run pytest -q kubeflow/trainer/backends/container/backend_test.py — 46 passed
make verify — passed
git diff --check — passed
I also verified the image-pull case still fails against the pre-fix backend.py, so it continues to guard #820.
Thanks for this work @dlanov!
/ok-to-test
/lgtm
/approve
[APPROVALNOTIFIER] This PR is APPROVED
This pull-request has been approved by: <a href="https://github.com/kubeflow/sdk/pull/822#pullrequestreview-5724787693" title="Approved">andreyvelich</a>
The full list of commands accepted by this bot can be found here.
The pull request process is described here
<details >
Needs approval from an approver in each of these files:
Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment
</details>
<!-- META={"approvers":[]} -->
abhishekKokadwar
dlanov
What this PR does / why we need it:
ContainerBackend.train()created the per-job network before several setup steps, but the failure cleanup only called_cleanup_container_resources()aftercontainer_idshad been initialized.As a result, failures during training script generation, image preparation, or environment setup could leave the job network behind.
This change initializes resource tracking before setup begins and routes all failures through the common cleanup path. It also removes the separate initializer network cleanup so the network is deleted in one place.
Regression coverage includes:
Validation:
uv run pytest -q kubeflow/trainer/backends/container/backend_test.py— 46 passedmake verify— passedgit diff --check— passedWhich issue(s) this PR fixes _(optional, in
Fixes #<issue number>, #<issue number>, ...format, will close the issue(s) when PR gets merged)_:Fixes #820
Checklist:
Docs are not needed because this fixes internal cleanup behavior without changing the public API or user-facing configuration.
AI usage:
Claude Code was used to analyze the cleanup flow, implement the fix and regression tests, and run validation. I reviewed the changes and verified the regression test fails against the original code and passes with the fix.