← Back to Pull requests

fix(trainer): clean up network on container setup failure #822

Merged
dlanov merged 2 files (101 lines) on Oct 31, 2026 21:14 UTC
View on GitHub
dlanov dlanov commented on Oct 05, 2026 21:51 UTC
Author

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() after container_ids had 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:

  • failure after network creation but before container creation

  • failure before network creation

  • failure after partial container creation

  • cleanup failure preserving the original setup exception
  • Validation:

  • uv run pytest -q kubeflow/trainer/backends/container/backend_test.py — 46 passed

  • make verify — passed

  • git diff --check — passed
  • Which 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 included if any changes are user facing
  • 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.

    Diff: 101 lines (+80 / -21) across 2 files Reviewer: abhishekKokadwar Review duration: 37402m
    All Vouch review confidence checks passed
    Residual risk 0.02 = Change Risk (0.32) × (1 − Review Confidence (0.93)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.32 · 101 lines diff across 2 files
    0.32
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.95 · 5 substantive comment(s)
    0.95
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    93%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.277
    Real PR Conversation Timeline
    12 items
    github-actions[bot] github-actions[bot] commented on Oct 05, 2026 21:52 UTC
    Bot

    🎉 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:

  • If you haven't already, please check out our Contributing Guide for repo-specific guidelines and the Kubeflow Contributor Guide for general community standards

  • Our team will review your PR soon! cc @kubeflow/kubeflow-sdk-team
  • Join the community:

  • Slack: Join our #kubeflow-ml-experience and #kubeflow-trainer Slack channels

  • Meetings: Attend the Kubeflow SDK and ML Experience bi-weekly meetings
  • Feel free to ask questions in the comments if you need any help or clarification!
    Thanks again for contributing to Kubeflow! 🙏

    abhishekKokadwar abhishekKokadwar commented on Oct 07, 2026 14:34 UTC
    Reviewer

    I ran this locally on Windows with Python 3.12.

  • pytest kubeflow/trainer/backends/container/backend_test.py: 46 passed

  • ruff check and ruff format --check on the container backend: clean

  • I also ran the new test_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.

    dlanov dlanov commented on Oct 07, 2026 23:40 UTC
    Author

    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.

    abhishekKokadwar abhishekKokadwar commented on Oct 08, 2026 03:54 UTC
    Contributor

    Makes sense on both, keeping the scope to the network leak is the right call. Tests and lint were clean on my side.

    /lgtm

    coveralls coveralls commented on Oct 30, 2026 23:57 UTC
    Contributor

    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


  • Coverage increased (+0.2%) from the base build.

  • Patch coverage: 43 of 43 lines across 2 files are fully covered (100%).

  • No coverage regressions found.
  • Uncovered Changes


    No uncovered changes found.

    Coverage Regressions


    No coverage regressions found.

    ---

    Coverage Stats

    | | ![Coverage Status](https://coveralls.io/builds/82728122) |
    | :-- | --: |
    | Relevant Lines: | 7439 |
    | Covered Lines: | 6374 |
    | Line Coverage: | 85.68% |
    | Coverage Strength: | 1.71 hits per line |

    ---
    ##### 💛 - Coveralls

    andreyvelich andreyvelich commented on Oct 31, 2026 00:03 UTC
    Reviewer

    /ok-to-test

    andreyvelich andreyvelich commented on Oct 31, 2026 00:05 UTC
    Reviewer

    Thanks @dlanov for the fix and the regression tests! 🙏 This review was done with the help of AI tools.

    andreyvelich andreyvelich commented on code on Oct 31, 2026 00:05 UTC
    Code Review
    kubeflow/trainer/backends/container/backend_test.py:1
    @@ -693,6 +693,110 @@ def mock_create_with_status(*args, **kwargs):
         print("test execution complete")
     
     
    +@pytest.mark.parametrize(
    +    "test_case",
    +    [
    +        TestCase(
    +            name="network creation fails",
    +            expected_status=FAILED,
    +            config={
    +                "fail_at": "create_network",
    +                "expected_containers_removed": [],
    +                "expected_network_deleted": False,
    +            },
    +            expected_error=RuntimeError,
    +        ),
    +        TestCase(
    +            name="image pull fails after network creation",
    +            expected_status=FAILED,
    +            config={
    +                "fail_at": "pull_image",
    +                "expected_containers_removed": [],
    +                "expected_network_deleted": True,
    +            },
    +            expected_error=RuntimeError,
    +        ),
    +        TestCase(
    +            name="container creation fails after some containers were created",
    +            expected_status=FAILED,
    +            config={
    +                "fail_at": "create_container",
    +                "num_nodes": 3,
    +                "expected_containers_removed": ["container-0", "container-1"],
    +                "expected_network_deleted": True,
    +            },
    +            expected_error=RuntimeError,
    +        ),
    +        TestCase(
    +            name="cleanup failure preserves original error",
    +            expected_status=FAILED,
    +            config={"fail_at": "cleanup"},
    +            expected_error=RuntimeError,
    +        ),
    +    ],
    +)
    +def test_train_cleanup_on_failure(container_backend, tmp_path, test_case):

    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.

    dlanov dlanov commented on code on Oct 31, 2026 20:13 UTC
    Code Review
    kubeflow/trainer/backends/container/backend_test.py:1
    @@ -693,6 +693,110 @@ def mock_create_with_status(*args, **kwargs):
         print("test execution complete")
     
     
    +@pytest.mark.parametrize(
    +    "test_case",
    +    [
    +        TestCase(
    +            name="network creation fails",
    +            expected_status=FAILED,
    +            config={
    +                "fail_at": "create_network",
    +                "expected_containers_removed": [],
    +                "expected_network_deleted": False,
    +            },
    +            expected_error=RuntimeError,
    +        ),
    +        TestCase(
    +            name="image pull fails after network creation",
    +            expected_status=FAILED,
    +            config={
    +                "fail_at": "pull_image",
    +                "expected_containers_removed": [],
    +                "expected_network_deleted": True,
    +            },
    +            expected_error=RuntimeError,
    +        ),
    +        TestCase(
    +            name="container creation fails after some containers were created",
    +            expected_status=FAILED,
    +            config={
    +                "fail_at": "create_container",
    +                "num_nodes": 3,
    +                "expected_containers_removed": ["container-0", "container-1"],
    +                "expected_network_deleted": True,
    +            },
    +            expected_error=RuntimeError,
    +        ),
    +        TestCase(
    +            name="cleanup failure preserves original error",
    +            expected_status=FAILED,
    +            config={"fail_at": "cleanup"},
    +            expected_error=RuntimeError,
    +        ),
    +    ],
    +)
    +def test_train_cleanup_on_failure(container_backend, tmp_path, test_case):

    Thanks @andreyvelich — I’ve updated the tests as suggested.

  • Folded the four cleanup cases into the existing test_train parametrization

  • Added the generic cleanup assertions so the existing initializer failure cases are covered as well

  • Removed the separate test_train_cleanup_on_failure

  • Removed the extra pull_policy = "Always" path

  • Kept 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.

    andreyvelich andreyvelich commented on Oct 31, 2026 20:27 UTC
    Reviewer

    Thanks for this work @dlanov!
    /ok-to-test
    /lgtm
    /approve

    google-oss-prow[bot] google-oss-prow[bot] commented on Oct 31, 2026 20:27 UTC
    Bot

    [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:

  • ~~OWNERS~~ [andreyvelich]
  • 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":[]} -->

    Assignees
    dlanov dlanov
    Labels
    risk: low confidence: 93.2% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 32.1% (LOW) · Higher = larger blast radius
    32.1%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 93.2% · Lower = rushed or shallow review
    93.2%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 2.2% · Safe to merge
    2.2%
    Repository