← Back to Pull requests

fix(spark): clean up session and port-forward on failure #779

Merged
shreya-024 merged 7 files (334 lines) on Oct 07, 2026 16:08 UTC
View on GitHub
shreya-024 shreya-024 commented on Sep 01, 2026 20:21 UTC
Author

What this PR does / why we need it:

Fixes the SparkConnect resource handling gap identified in #476.

  • Map unrecognised CR states to SparkConnectState.UNKNOWN instead of PROVISIONING in get_spark_connect_info_from_cr

  • Delete the SparkConnect CR on failure in create_and_connect to prevent orphaned cluster resources

  • Terminate kubectl port-forward subprocess on connection/timeout failure

  • Added "unknown status" parametrized test case inside test_get_spark_connect_info_from_cr

  • Added test_create_and_connect_cleanup_on_failure in backend_test.py
  • Which issue(s) this PR fixes:

  • Fixes #476
  • Diff: 334 lines (+234 / -100) across 7 files Reviewer: tariq-hasan Review duration: 51587m
    All Vouch review confidence checks passed
    Residual risk 0.11 = Change Risk (0.47) × (1 − Review Confidence (0.76)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.47 · 334 lines diff across 7 files
    0.47
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.52 · 5 substantive comment(s)
    0.52
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    75%
    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.348
    Real PR Conversation Timeline
    33 items
    github-actions[bot] github-actions[bot] commented on Sep 01, 2026 20:21 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! 🙏

    tariq-hasan tariq-hasan commented on code on Sep 02, 2026 01:45 UTC
    Code Review
    kubeflow/spark/types/types.py:1
    @@ -32,6 +32,7 @@ class SparkConnectState(str, Enum):
         RUNNING = "Running"  # Operator may set this when server is up; treated as ready
         NOT_READY = "NotReady"
         FAILED = "Failed"
    +    UNKNOWN = "Unknown"

    This should be removed.

    tariq-hasan tariq-hasan commented on code on Sep 02, 2026 01:46 UTC
    Code Review
    kubeflow/spark/backends/kubernetes/utils.py:1
    @@ -632,7 +632,7 @@ def get_spark_connect_info_from_cr(
             try:
                 state = SparkConnectState(spark_connect_cr.status.state)
             except ValueError:
    -            state = SparkConnectState.PROVISIONING
    +            state = SparkConnectState.UNKNOWN
    tariq-hasan tariq-hasan commented on code on Sep 02, 2026 01:57 UTC
    Code Review
    kubeflow/spark/backends/kubernetes/backend.py:1

    The RUNNING state should be removed.

            if info.state == SparkConnectState.READY:
                logger.info(
    

    tariq-hasan tariq-hasan commented on code on Sep 02, 2026 01:59 UTC
    Code Review
    kubeflow/spark/types/types.py:1
    @@ -32,6 +32,7 @@ class SparkConnectState(str, Enum):
         RUNNING = "Running"  # Operator may set this when server is up; treated as ready

    The RUNNING state should be removed.

    tariq-hasan tariq-hasan commented on Sep 02, 2026 02:27 UTC
    Reviewer

    Hi @shreya-024! I have added a few comments.

    Please also follow these instructions to sign your commits: https://github.com/kubeflow/sdk/pull/779/checks?check_run_id=100012874640.

    tariq-hasan tariq-hasan commented on Sep 02, 2026 02:27 UTC
    Contributor

    /ok-to-test
    /retest

    tariq-hasan tariq-hasan commented on Sep 02, 2026 03:31 UTC
    Contributor

    /assign

    vjkumar2756 vjkumar2756 commented on Sep 02, 2026 15:26 UTC
    Reviewer

    LGTM
    @shreya-024
    I went through the changes, and the cleanup handling looks solid. Mapping unrecognized states to UNKNOWN, cleaning up the SparkConnect CR on failure, and terminating the port forward subprocess should prevent orphaned resources and state mismatches.

    tariq-hasan tariq-hasan commented on code on Sep 06, 2026 18:40 UTC
    Code Review
    kubeflow/spark/types/types.py:1
    @@ -32,6 +32,7 @@ class SparkConnectState(str, Enum):
         RUNNING = "Running"  # Operator may set this when server is up; treated as ready
         NOT_READY = "NotReady"
         FAILED = "Failed"
    +    UNKNOWN = "Unknown"

    Please remove UNKNOWN = "Unknown".

    tariq-hasan tariq-hasan commented on code on Sep 06, 2026 18:59 UTC
    Code Review
    kubeflow/spark/types/types.py:1

    Let's add import kubeflow.common.constants as common_constants.

    tariq-hasan tariq-hasan commented on code on Sep 06, 2026 19:01 UTC
    Code Review
    kubeflow/spark/types/types.py:1

    Let's rewrite as follows.

        state: str = common_constants.UNKNOWN
    

    tariq-hasan tariq-hasan commented on code on Sep 06, 2026 19:01 UTC
    Code Review
    kubeflow/spark/types/types.py:1

    Same here

        status: str = common_constants.UNKNOWN
    

    tariq-hasan tariq-hasan commented on code on Sep 06, 2026 19:02 UTC
    Code Review
    kubeflow/spark/backends/kubernetes/utils.py:1
    @@ -632,7 +632,7 @@ def get_spark_connect_info_from_cr(
             try:
                 state = SparkConnectState(spark_connect_cr.status.state)
             except ValueError:
    -            state = SparkConnectState.PROVISIONING
    +            state = SparkConnectState(common_constants.UNKNOWN)

                state = common_constants.UNKNOWN
    

    tariq-hasan tariq-hasan commented on code on Sep 06, 2026 19:59 UTC
    Code Review
    kubeflow/spark/backends/kubernetes/backend.py:1

    We need to be able to retry for transient errors.

    tariq-hasan tariq-hasan requested changes on Sep 06, 2026 20:00 UTC
    Changes Requested Reviewer

    Hi @shreya-024! I have added a few comments.

    tariq-hasan tariq-hasan commented on code on Sep 11, 2026 01:08 UTC
    Code Review
    kubeflow/spark/backends/kubernetes/backend.py:1
    @@ -678,10 +700,21 @@ def create_and_connect(
                 timeout,
             )
     
    -        info = self._wait_for_session_ready(info.name, timeout=timeout)
    -        logger.info("Session ready, connecting (service_name=%s)", info.service_name)
    -
    -        return self.connect(info, connect_timeout=connect_timeout)
    +        try:
    +            info = self._wait_for_session_ready(info.name, timeout=timeout)
    +            logger.info("Session ready, connecting (service_name=%s)", info.service_name)
    +            return self.connect(info, connect_timeout=connect_timeout)
    +        except Exception as e:
    +            logger.warning(
    +                "Failed to setup or connect to SparkConnect session %s/%s: %s. "
    +                "Cleaning up SparkConnect session.",
    +                info.namespace,
    +                info.name,
    +                e,
    +            )
    +            with contextlib.suppress(Exception):
    +                self.delete_session(info.name)
    +            raise

    We can rewrite this as follows. This is because Exception would not cover Ctrl+C keyboard interrupt for example. So to make the implementation more robust we use a finally block to always run session deletion if creation fails.

            success = False
    
            try:
                info = self._wait_for_session_ready(info.name, timeout=timeout)
    
                logger.info(
                    "Session ready, connecting (service_name=%s)",
                    info.service_name,
                )
    
                session = self.connect(
                    info,
                    connect_timeout=connect_timeout,
                )
    
                success = True
                return session
    
            finally:
                if not success:
                    logger.warning(
                        "Failed to setup or connect to SparkConnect session %s/%s. "
                        "Cleaning up SparkConnect session.",
                        info.namespace,
                        info.name,
                    )
    
                    try:
                        self.delete_session(info.name)
                    except Exception:
                        logger.exception(
                            "Failed to clean up SparkConnect session %s/%s",
                            info.namespace,
                            info.name,
                        )
    

    tariq-hasan tariq-hasan commented on code on Sep 12, 2026 14:22 UTC
    Code Review
    kubeflow/spark/backends/kubernetes/backend.py:1

    Please use the following implementation for _wait_for_session_ready. It handles transient errors with a retry mechanism.

        def _wait_for_session_ready(
            self,
            name: str,
            timeout: int = 300,
            polling_interval: int = 2,
        ) -> SparkConnectInfo:
            """Wait for a SparkConnect session to become ready.
    
            Args:
                name:
                    Name of the SparkConnect session.
    
                timeout:
                    Maximum time in seconds to wait.
    
                polling_interval:
                    Time in seconds between status checks.
    
            Returns:
                SparkConnectInfo containing information about the ready session.
    
            Raises:
                RuntimeError:
                    If the SparkConnect session reaches the failed state.
    
                TimeoutError:
                    If the session does not become ready within the timeout.
    
                Exception:
                    If getting the session fails with a non-transient error.
                """
            start_time = time.monotonic()
            last_log_time = start_time
            deadline = start_time + timeout
    
            while True:
                now = time.monotonic()
                if now >= deadline:
                    raise TimeoutError(
                        f"Timeout waiting for {constants.SPARK_CONNECT_KIND} to be ready: "
                        f"{self.namespace}/{name} (timeout: {timeout}s)"
                    )
    
                try:
                    info = self.get_session(name)
                except TimeoutError as e:
                    # The request itself timed out. This is transient, so retry
                    # as long as the overall wait deadline has not expired.
                    logger.warning(
                        "Timeout getting session %s/%s, retrying: %s",
                        self.namespace,
                        name,
                        e,
                    )
                except RuntimeError as e:
                    # get_session wraps ApiException in RuntimeError, so inspect the cause.
                    cause = e.__cause__
                    if not isinstance(cause, client.ApiException) or cause.status not in {
                        429,
                        500,
                        502,
                        503,
                        504,
                    }:
                        raise
    
                    logger.warning(
                        "Transient HTTP %s getting session %s/%s, retrying: %s",
                        cause.status,
                        self.namespace,
                        name,
                        e,
                    )
                else:
                    if info.state == SparkConnectState.READY:
                        logger.info(
                            "Session ready: %s/%s state=%s serviceName=%s (%.0fs)",
                            self.namespace,
                            name,
                            info.state,
                            info.service_name,
                            time.monotonic() - start_time,
                        )
                        return info
    
                    if info.state == SparkConnectState.FAILED:
                        raise RuntimeError(
                            f"{constants.SPARK_CONNECT_KIND} failed: "
                            f"{self.namespace}/{name}"
                        )
    
                    now = time.monotonic()
                    if now - last_log_time >= 10.0:
                        logger.info(
                            "Waiting for session: %s/%s state=%s serviceName=%s elapsed=%.0fs",
                            self.namespace,
                            name,
                            info.state,
                            info.service_name,
                            now - start_time,
                        )
                        last_log_time = now
    
                    if now >= deadline:
                        raise TimeoutError(
                            f"Timeout waiting for {constants.SPARK_CONNECT_KIND} to be ready: "
                            f"{self.namespace}/{name} (timeout: {timeout}s)"
                        )
    
                # Don't sleep beyond the overall deadline.
                remaining = deadline - time.monotonic()
                if remaining <= 0:
                    raise TimeoutError(
                        f"Timeout waiting for {constants.SPARK_CONNECT_KIND} to be ready: "
                        f"{self.namespace}/{name} (timeout: {timeout}s)"
                    )
    
                time.sleep(min(polling_interval, remaining))
    

    tariq-hasan tariq-hasan commented on code on Sep 12, 2026 14:42 UTC
    Code Review
    kubeflow/spark/backends/kubernetes/backend_test.py:1
    @@ -1941,3 +1941,24 @@ def test_get_job_logs(kubernetes_backend, test_case):
                 raise
     
         print("test execution complete")
    +
    +
    +def test_create_and_connect_cleanup_on_failure(kubernetes_backend):
    +    """Test that create_and_connect cleans up session when connect fails."""
    +    mock_info = MagicMock()
    +    mock_info.name = "test-session"
    +    mock_info.namespace = "default"
    +
    +    with (
    +        patch.object(kubernetes_backend, "_create_session", return_value=mock_info),
    +        patch.object(
    +            kubernetes_backend,
    +            "_wait_for_session_ready",
    +            side_effect=RuntimeError("Wait failed"),
    +        ),
    +        patch.object(kubernetes_backend, "delete_session") as mock_delete,
    +    ):
    +        with pytest.raises(RuntimeError, match="Wait failed"):
    +            kubernetes_backend.create_and_connect()
    +
    +        mock_delete.assert_called_once_with("test-session")

    Unit tests need to use the existing test_<method> function naming pattern with test cases using the TestCase helper.

    Please also add test cases that cover

  • create succeeds, connect succeeds

  • create succeeds, wait fails

  • create succeeds, connect fails

  • create itself fails
  • tariq-hasan tariq-hasan commented on code on Sep 12, 2026 15:11 UTC
    Code Review
    kubeflow/spark/backends/kubernetes/utils.py:1
    @@ -627,12 +627,12 @@ def get_spark_connect_info_from_cr(
             raise ValueError(f"SparkConnect CR is invalid: {spark_connect_cr}")
     
         # Parse state
    -    state = SparkConnectState.PROVISIONING
    +    state = common_constants.UNKNOWN

    Actually I think it's better for this one to be state = SparkConnectState.PROVISIONING.

    Granted the PROVISIONING state is not currently leveraged in the operator. At the same time it makes sense for the initial state on the client side to be a provisioning state and not an unknown state.

    Please also remove the ready state from the following since only the provisioning state can be captured after CR creation before it is read back out from the control plane.

    https://github.com/kubeflow/sdk/blob/3febcd7377d0cdb322bbb420207c3c26cbf7afd7/test/e2e/spark/test_spark_examples.py#L114

    tariq-hasan tariq-hasan requested changes on Sep 12, 2026 15:32 UTC
    Changes Requested Reviewer

    Hi @shreya-024! I have added a few more suggestions for changes.

    shreya-024 shreya-024 commented on code on Sep 16, 2026 10:30 UTC
    Code Review
    kubeflow/spark/backends/kubernetes/backend.py:1
    @@ -678,10 +700,21 @@ def create_and_connect(
                 timeout,
             )
     
    -        info = self._wait_for_session_ready(info.name, timeout=timeout)
    -        logger.info("Session ready, connecting (service_name=%s)", info.service_name)
    -
    -        return self.connect(info, connect_timeout=connect_timeout)
    +        try:
    +            info = self._wait_for_session_ready(info.name, timeout=timeout)
    +            logger.info("Session ready, connecting (service_name=%s)", info.service_name)
    +            return self.connect(info, connect_timeout=connect_timeout)
    +        except Exception as e:
    +            logger.warning(
    +                "Failed to setup or connect to SparkConnect session %s/%s: %s. "
    +                "Cleaning up SparkConnect session.",
    +                info.namespace,
    +                info.name,
    +                e,
    +            )
    +            with contextlib.suppress(Exception):
    +                self.delete_session(info.name)
    +            raise

    Done

    shreya-024 shreya-024 commented on code on Sep 16, 2026 10:30 UTC
    Code Review
    kubeflow/spark/backends/kubernetes/backend_test.py:1
    @@ -1941,3 +1941,24 @@ def test_get_job_logs(kubernetes_backend, test_case):
                 raise
     
         print("test execution complete")
    +
    +
    +def test_create_and_connect_cleanup_on_failure(kubernetes_backend):
    +    """Test that create_and_connect cleans up session when connect fails."""
    +    mock_info = MagicMock()
    +    mock_info.name = "test-session"
    +    mock_info.namespace = "default"
    +
    +    with (
    +        patch.object(kubernetes_backend, "_create_session", return_value=mock_info),
    +        patch.object(
    +            kubernetes_backend,
    +            "_wait_for_session_ready",
    +            side_effect=RuntimeError("Wait failed"),
    +        ),
    +        patch.object(kubernetes_backend, "delete_session") as mock_delete,
    +    ):
    +        with pytest.raises(RuntimeError, match="Wait failed"):
    +            kubernetes_backend.create_and_connect()
    +
    +        mock_delete.assert_called_once_with("test-session")

    Done

    shreya-024 shreya-024 commented on code on Sep 16, 2026 10:30 UTC
    Code Review
    kubeflow/spark/backends/kubernetes/utils.py:1
    @@ -627,12 +627,12 @@ def get_spark_connect_info_from_cr(
             raise ValueError(f"SparkConnect CR is invalid: {spark_connect_cr}")
     
         # Parse state
    -    state = SparkConnectState.PROVISIONING
    +    state = common_constants.UNKNOWN

    Done

    shreya-024 shreya-024 commented on code on Sep 16, 2026 10:31 UTC
    Code Review
    kubeflow/spark/backends/kubernetes/backend.py:1

    Done

    shreya-024 shreya-024 commented on Sep 16, 2026 10:31 UTC
    Author

    Hi @tariq-hasan, I've addressed all the review comments. Could you please take a look when you get a chance?

    tariq-hasan tariq-hasan commented on code on Oct 04, 2026 17:11 UTC
    Code Review
    kubeflow/spark/backends/kubernetes/backend_test.py:1
    @@ -1941,3 +1941,24 @@ def test_get_job_logs(kubernetes_backend, test_case):
                 raise
     
         print("test execution complete")
    +
    +
    +def test_create_and_connect_cleanup_on_failure(kubernetes_backend):
    +    """Test that create_and_connect cleans up session when connect fails."""
    +    mock_info = MagicMock()
    +    mock_info.name = "test-session"
    +    mock_info.namespace = "default"
    +
    +    with (
    +        patch.object(kubernetes_backend, "_create_session", return_value=mock_info),
    +        patch.object(
    +            kubernetes_backend,
    +            "_wait_for_session_ready",
    +            side_effect=RuntimeError("Wait failed"),
    +        ),
    +        patch.object(kubernetes_backend, "delete_session") as mock_delete,
    +    ):
    +        with pytest.raises(RuntimeError, match="Wait failed"):
    +            kubernetes_backend.create_and_connect()
    +
    +        mock_delete.assert_called_once_with("test-session")

    Please move all these test cases into test_create_and_connect.

    The pattern we follow is to group test cases under test_<method_name> in each unit test module.

    tariq-hasan tariq-hasan commented on Oct 04, 2026 19:53 UTC
    Contributor

    Thanks @shreya-024! Please sign the DCO commit as well: https://github.com/kubeflow/sdk/pull/779/checks?check_run_id=111507077564.

    shreya-024 shreya-024 commented on Oct 04, 2026 21:38 UTC
    Author

    @tariq-hasan I've signed the commit

    tariq-hasan tariq-hasan commented on Oct 07, 2026 15:03 UTC
    Contributor

    Thanks!
    /lgtm

    andreyvelich andreyvelich commented on Oct 07, 2026 16:05 UTC
    Reviewer

    /lgtm
    /approve

    google-oss-prow[bot] google-oss-prow[bot] commented on Oct 07, 2026 16:06 UTC
    Bot

    [APPROVALNOTIFIER] This PR is APPROVED

    This pull-request has been approved by: <a href="https://github.com/kubeflow/sdk/pull/779#pullrequestreview-5445002950" 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":[]} -->

    Reviewers
    Assignees
    shreya-024 shreya-024
    Labels
    risk: low confidence: 75.6% 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: 46.6% (MEDIUM) · Higher = larger blast radius
    46.6%
    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: 75.6% · Lower = rushed or shallow review
    75.6%
    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: 11.4% · Safe to merge
    11.4%
    Repository