diff --git a/README.md b/README.md index 05c7da59..17f3cf0e 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ requiring additional steps. For notebooks and interactive development, install with the `client` and `interactive` extras to get the lightweight `pyspark-client` package along with -the interactive extras (`explore_dataframe()`, `%dpip`, `%%sparksql`): +the interactive extras (`explore_dataframe()`, `%dpip`, `%%sparksql`, and `%cellmonitor` when `managed-spark-cell-monitoring` is installed): ```sh pip install 'google-cloud-spark-connect[client,interactive]' @@ -215,6 +215,12 @@ up a few interactive conveniences: [google-colabsqlviz](https://pypi.org/project/google-colabsqlviz/) is injected into your notebook globals. - The [`%dpip` and `%%sparksql`](#bundled-magics) magics are loaded. +- When `managed-spark-cell-monitoring` is installed separately (it is not pulled + in by the `interactive` extra; install e.g. `pip install 'managed-spark-cell-monitoring[connect]'` + or use a runtime image that pre-installs it), `%cellmonitor` is loaded + automatically. On supported Spark Connect runtimes it renders an inline cell + monitoring widget and suppresses the legacy per-operation links and `tqdm` + progress bars, falling back automatically on unsupported runtimes. ```python import google.cloud.managed_spark_connect # extras load here @@ -228,6 +234,8 @@ The extras won't override anything you've already set up, for example if `explor #### Opting out +To opt out of cell monitoring while keeping the other interactive extras, run `%cellmonitor off` (or set `MANAGED_SPARK_CELL_MONITORING_ENABLED=0` before starting the kernel). To disable all auto-loaded interactive extras: + Set the environment variable before starting the kernel: ```sh @@ -252,7 +260,7 @@ An explicit IPython setting takes precedence over the environment variable. ### Bundled Magics These are loaded with the interactive extras, or explicitly with -`%load_ext google.cloud.managed_spark_magics`. +`%load_ext google.cloud.managed_spark_magics` (and `%load_ext managed_spark_cell_monitoring.spark_connect` for `%cellmonitor`). #### `%dpip` diff --git a/google/cloud/managed_spark_connect/_cell_monitoring.py b/google/cloud/managed_spark_connect/_cell_monitoring.py new file mode 100644 index 00000000..ad5ebe7d --- /dev/null +++ b/google/cloud/managed_spark_connect/_cell_monitoring.py @@ -0,0 +1,227 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Thin lifecycle bridge to `managed_spark_cell_monitoring.spark_connect`.""" + +import logging +import re +import sys +import threading +from typing import Any, Callable, List, Optional + +logger = logging.getLogger(__name__) + +_CELL_MONITOR_EXTENSION = "managed_spark_cell_monitoring.spark_connect" +# Match structured cancellation tokens (brackets, parens, or error prefixes), +# avoiding false positives on user SQL echoed inside quotes (e.g. "'OPERATION_CANCELED'"). +_CANCELLED_MSG_RE = re.compile( + r"(?:\[|\(|:\s+|^)(?:OPERATION_CANCELED|SPARK_JOB_CANCELLED|JOB_CANCELLED)\b", + re.IGNORECASE, +) + + +def classify_exception_outcome(exc: BaseException) -> str: + """Classifies an `ExecutePlan` exception into `CANCELLED` or `FAILED`.""" + seen: set[int] = set() + cur: Optional[BaseException] = exc + while cur is not None and id(cur) not in seen: + seen.add(id(cur)) + if isinstance(cur, (KeyboardInterrupt, GeneratorExit)): + return "CANCELLED" + try: + code_fn = getattr(cur, "code", None) + if callable(code_fn): + code = code_fn() + if getattr(code, "name", None) == "CANCELLED": + return "CANCELLED" + except Exception: + pass + try: + grpc_code = getattr(cur, "grpc_status_code", None) + if getattr(grpc_code, "name", None) == "CANCELLED": + return "CANCELLED" + except Exception: + pass + try: + cond_fn = getattr(cur, "getCondition", None) or getattr( + cur, "getErrorClass", None + ) + if callable(cond_fn): + cond = cond_fn() + if isinstance(cond, str): + cond_upper = cond.upper() + if "CANCELED" in cond_upper or "CANCELLED" in cond_upper: + return "CANCELLED" + except Exception: + pass + try: + if _CANCELLED_MSG_RE.search(str(cur)): + return "CANCELLED" + except Exception: + pass + try: + cur = getattr(cur, "__cause__", None) or getattr( + cur, "__context__", None + ) + except Exception: + break + + return "FAILED" + + +def _disabled_by_ipython_extras() -> bool: + ipython_mod = sys.modules.get("google.cloud.managed_spark_connect._ipython") + checker = getattr( + ipython_mod, "_is_extension_disabled_for_current_shell", None + ) + if callable(checker): + try: + return bool(checker(_CELL_MONITOR_EXTENSION)) + except Exception: + return False + return False + + +class SessionCellMonitorBridge: + """Lazily delegates operation hooks to `managed-spark-cell-monitoring`. + + When `managed_spark_cell_monitoring.spark_connect` is not loaded in the + current Python process, all methods are fast no-ops with zero imports or + background threads. + """ + + def __init__( + self, + client: Any, + spark_ui_url_getter: Optional[Callable[[], str]] = None, + on_fallback: Optional[Callable[[List[str]], None]] = None, + ) -> None: + self._client = client + self._spark_ui_url_getter = spark_ui_url_getter + self._on_fallback = on_fallback + self._lock = threading.Lock() + self._poller: Any = None + self._closed = False + self._factory_failed = False + + def _resolve_poller(self) -> Any: + poller = self._poller + if poller is not None or self._closed or self._factory_failed: + return poller + if _disabled_by_ipython_extras(): + return None + mod = sys.modules.get(_CELL_MONITOR_EXTENSION) + if mod is None: + return None + factory = getattr(mod, "create_session_poller", None) + if not callable(factory): + return None + with self._lock: + if self._closed or self._factory_failed or self._client is None: + return None + if self._poller is None: + try: + self._poller = factory( + self._client, + spark_ui_url_getter=self._spark_ui_url_getter, + on_fallback=self._on_fallback, + ) + except Exception: + self._factory_failed = True + logger.debug( + "Failed creating Spark Connect cell monitor poller", + exc_info=True, + ) + return None + return self._poller + + def begin_operation(self, operation_id: Optional[str]) -> bool: + if not operation_id or self._closed or _disabled_by_ipython_extras(): + return False + poller = self._resolve_poller() + if poller is None: + return False + try: + return bool(poller.begin_operation(operation_id)) + except Exception: + logger.debug( + "Error in cell monitor begin_operation(%s)", + operation_id, + exc_info=True, + ) + return False + + def finish_operation( + self, + operation_id: Optional[str], + outcome: str = "SUCCEEDED", + ) -> None: + if not operation_id: + return + poller = self._poller + if poller is None: + return + try: + poller.finish_operation(operation_id, outcome=outcome) + except Exception: + logger.debug( + "Error in cell monitor finish_operation(%s)", + operation_id, + exc_info=True, + ) + + def note_spark_tasks_seen(self, operation_id: Optional[str]) -> None: + poller = self._poller + if poller is None or not operation_id: + return + try: + poller.note_spark_tasks_seen(operation_id) + except Exception: + logger.debug( + "Error recording Spark tasks for %s", + operation_id, + exc_info=True, + ) + + def should_suppress_progress_bar(self, operation_id: Optional[str]) -> bool: + poller = self._poller + if ( + poller is None + or not operation_id + or self._closed + or _disabled_by_ipython_extras() + ): + return False + try: + return bool(poller.should_suppress_progress_bar(operation_id)) + except Exception: + return False + + def close(self) -> None: + with self._lock: + if self._closed: + return + self._closed = True + poller = self._poller + self._poller = None + self._client = None + self._spark_ui_url_getter = None + self._on_fallback = None + if poller is not None: + try: + poller.close() + except Exception: + logger.debug( + "Error closing Spark Connect cell monitor poller", + exc_info=True, + ) diff --git a/google/cloud/managed_spark_connect/_ipython.py b/google/cloud/managed_spark_connect/_ipython.py index c1539bc9..752b94dd 100644 --- a/google/cloud/managed_spark_connect/_ipython.py +++ b/google/cloud/managed_spark_connect/_ipython.py @@ -38,6 +38,10 @@ "google.cloud.managed_spark_magics", (("line", "dpip"), ("line", "sparksql"), ("cell", "sparksql")), ), + ( + "managed_spark_cell_monitoring.spark_connect", + (("line", "cellmonitor"),), + ), ) @@ -76,7 +80,7 @@ class ManagedSparkConnect(Configurable): enable_extras = Bool( help=( "Whether to automatically load the installed interactive extras " - "(explore_dataframe, %dpip, %%sparksql)." + "(explore_dataframe, %dpip, %%sparksql, %cellmonitor)." ), ).tag(config=True) @@ -448,6 +452,28 @@ def _unload_extras_for_shell(ip: Any) -> None: state.loaded_extensions.discard(ext_name) +def _is_extension_disabled_for_current_shell(ext_name: str) -> bool: + """Whether interactive extras were explicitly turned off for this shell.""" + ip_mod = sys.modules.get("IPython") + get_ipython = getattr(ip_mod, "get_ipython", None) + if not callable(get_ipython): + return False + ip = get_ipython() + if ip is None: + return False + state = _SHELL_STATES.get(id(ip)) + if state is None or state.shell is not ip: + return False + cfg = state.config_instance + if cfg is None or cfg.enable_extras: + return False + ext_mgr = getattr(ip, "extension_manager", None) + loaded = getattr(ext_mgr, "loaded", None) + if isinstance(loaded, (set, dict, list, tuple)) and ext_name in loaded: + return False + return True + + def _init_extras() -> None: """Initialize interactive extras on package import unless opted out.""" ip = None diff --git a/google/cloud/managed_spark_connect/client/core.py b/google/cloud/managed_spark_connect/client/core.py index ebc8c705..a0d96105 100644 --- a/google/cloud/managed_spark_connect/client/core.py +++ b/google/cloud/managed_spark_connect/client/core.py @@ -29,7 +29,13 @@ logger = logging.getLogger(__name__) -_UNGUARDED_METHOD_SUFFIXES = ("/ReleaseExecute", "/ReleaseSession") +_UNGUARDED_METHOD_SUFFIXES = ( + "/ReleaseExecute", + "/ReleaseSession", + # Background cell-monitoring polls must run alongside active ExecutePlan + # streams without triggering control-plane liveness checks. + "/GetStatus", +) _GUARD_MODE: contextvars.ContextVar[str] = contextvars.ContextVar( "msc_guard_mode", default="direct" ) diff --git a/google/cloud/managed_spark_connect/session.py b/google/cloud/managed_spark_connect/session.py index 61f5256d..9d572ba5 100644 --- a/google/cloud/managed_spark_connect/session.py +++ b/google/cloud/managed_spark_connect/session.py @@ -29,6 +29,7 @@ import threading import time import uuid +import weakref import tqdm from packaging import version from types import MethodType @@ -101,6 +102,7 @@ TerminateSessionRequest, ) from google.cloud.dataproc_v1.types import sessions +from google.cloud.managed_spark_connect import _cell_monitoring from google.cloud.managed_spark_connect import _logging from google.cloud.managed_spark_connect import _runtimes from google.cloud.managed_spark_connect import environment @@ -2046,6 +2048,20 @@ def __init__( self._show_operation_links: Optional[bool] = show_operation_links self._show_progress_bar: Optional[bool] = show_progress_bar self._progress_bar_leave: Optional[bool] = progress_bar_leave + weak_self = weakref.ref(self) + self._cell_monitor_bridge = _cell_monitoring.SessionCellMonitorBridge( + self.client, + spark_ui_url_getter=lambda: ( + s._get_session_spark_ui_url() + if (s := weak_self()) is not None + else "" + ), + on_fallback=lambda op_ids: ( + s._on_cell_monitor_fallback(op_ids) + if (s := weak_self()) is not None + else None + ), + ) # The _execute_and_fetch hooks stack in install order, innermost # first: the position-lost replay (so the hooks around it see one # call, with the caller's request, however many attempts it takes), @@ -2073,17 +2089,41 @@ def _execute_plan_request_with_metadata(*args, **kwargs): def execute_hook(inner): def _execute(req, *args, **kwargs): - if not self._sql_lazy_transformation(req): - self._display_operation_link(req.operation_id) - return inner(req, *args, **kwargs) + operation_id = req.operation_id + is_lazy_sql = self._sql_lazy_transformation(req) + bridge = self.__dict__.get("_cell_monitor_bridge") + monitored = ( + not is_lazy_sql + and bridge is not None + and bridge.begin_operation(operation_id) + ) + if not monitored and not is_lazy_sql: + self._display_operation_link(operation_id) + outcome = "SUCCEEDED" + try: + return inner(req, *args, **kwargs) + except BaseException as exc: + if monitored: + outcome = _cell_monitoring.classify_exception_outcome( + exc + ) + raise + finally: + if monitored and bridge is not None: + bridge.finish_operation(operation_id, outcome=outcome) return _execute def execute_and_fetch_as_iterator_hook(inner): def _execute_and_fetch_as_iterator(req, *args, **kwargs): - if not self._sql_lazy_transformation(req): - self._display_operation_link(req.operation_id) - return inner(req, *args, **kwargs) + operation_id = req.operation_id + is_lazy_sql = self._sql_lazy_transformation(req) + bridge = self.__dict__.get("_cell_monitor_bridge") + if bridge is None or is_lazy_sql: + if not is_lazy_sql: + self._display_operation_link(operation_id) + return inner(req, *args, **kwargs) + return self._monitored_stream(bridge, inner, req, args, kwargs) return _execute_and_fetch_as_iterator @@ -2165,11 +2205,6 @@ def handler( if operation_id is None: return - # Don't build / render progress bar for non-interactive (despite - # Ipython or non-IPython) or when disabled, unless tests forced the bar on. - if not self._should_show_progress_bar(): - return - total_tasks = 0 completed_tasks = 0 @@ -2177,6 +2212,21 @@ def handler( total_tasks += stage.num_tasks completed_tasks += stage.num_completed_tasks + bridge = self.__dict__.get("_cell_monitor_bridge") + if bridge is not None: + if total_tasks > 0 and not done: + bridge.note_spark_tasks_seen(operation_id) + if bridge.should_suppress_progress_bar(operation_id): + self._close_progress_bar( + operation_id, reason="cell_monitor" + ) + return + + # Don't build / render progress bar for non-interactive (despite + # Ipython or non-IPython) or when disabled, unless tests forced the bar on. + if not self._should_show_progress_bar(): + return + # Don't show progress bar till we receive some tasks if total_tasks == 0: return @@ -2322,6 +2372,54 @@ def _sql_lazy_transformation(req): except AttributeError: return False + def _monitored_stream( + self, + bridge: _cell_monitoring.SessionCellMonitorBridge, + inner: Any, + req: Any, + args: Any, + kwargs: Any, + ): + """Starts monitoring lazily on first iteration so unconsumed generators never leak.""" + operation_id = req.operation_id + is_lazy_sql = self._sql_lazy_transformation(req) + if is_lazy_sql or not bridge.begin_operation(operation_id): + if not is_lazy_sql: + self._display_operation_link(operation_id) + yield from inner(req, *args, **kwargs) + return + outcome = "CANCELLED" + try: + yield from inner(req, *args, **kwargs) + outcome = "SUCCEEDED" + except BaseException as exc: + outcome = _cell_monitoring.classify_exception_outcome(exc) + raise + finally: + bridge.finish_operation(operation_id, outcome=outcome) + + def _get_session_spark_ui_url(self) -> str: + if ( + self._region is not None + and self._active_s8s_session_id is not None + and self._project_id is not None + ): + return ( + f"{_MANAGED_SPARK_SESSIONS_BASE_URL}/{self._region}/" + f"{self._active_s8s_session_id}/sparkApplications/applications" + f"?project={self._project_id}" + ) + return "" + + def _on_cell_monitor_fallback(self, operation_ids: List[str]) -> None: + """Displays suppressed operation links when cell monitoring falls back. + + `managed_spark_cell_monitoring` invokes this under the originating cell's + `display_context` so HTML links route to the right notebook cell output. + """ + for op_id in operation_ids: + self._display_operation_link(op_id) + def _repr_html_(self) -> str: if not self._active_s8s_session_id: return """ @@ -2331,16 +2429,13 @@ def _repr_html_(self) -> str: links = _session_links( self._region, self._project_id, self._active_s8s_session_id ) - ssui_url = ( - f"{_MANAGED_SPARK_SESSIONS_BASE_URL}/{self._region}/" - f"{self._active_s8s_session_id}/sparkApplications/applications" - f"?project={self._project_id}" - ) + ssui_url = self._get_session_spark_ui_url() + extra_links = [("Spark UI ↗", ssui_url)] if ssui_url else None return _status_line_html( "Spark Connect", self._active_s8s_session_id, links, - extra_links=[("Spark UI ↗", ssui_url)], + extra_links=extra_links, ) def _display_operation_link(self, operation_id: str): @@ -2549,6 +2644,9 @@ def _close_client(self) -> None: logger.debug( "Failed to close the StreamingQueryManager", exc_info=True ) + bridge = self.__dict__.get("_cell_monitor_bridge") + if bridge is not None: + bridge.close() try: client.close() except Exception: diff --git a/tests/unit/test_cell_monitoring.py b/tests/unit/test_cell_monitoring.py new file mode 100644 index 00000000..e8054b77 --- /dev/null +++ b/tests/unit/test_cell_monitoring.py @@ -0,0 +1,939 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Unit tests for thin Spark Connect cell-monitoring lifecycle integration.""" + +import gc +import io +import sys +import types +from typing import Any, List +import unittest +from unittest import mock +import warnings +import weakref + +import grpc +from pyspark.errors.exceptions.connect import SparkConnectGrpcException +from pyspark.sql.connect.shell.progress import StageInfo + +from google.cloud.managed_spark_connect import _cell_monitoring +from google.cloud.managed_spark_connect.client import core +from google.cloud.managed_spark_connect.exceptions import SessionNotActiveError +from google.cloud.managed_spark_connect.session import ManagedSparkSession + + +class _FakeRpcError(grpc.RpcError): + + def __init__(self, status_code: grpc.StatusCode, details: str = ""): + super().__init__(details) + self._code = status_code + self._details = details + + def code(self) -> grpc.StatusCode: + return self._code + + def details(self) -> str: + return self._details + + +class _FakeMultiCallable: + + def __init__(self): + self.calls: List[Any] = [] + + def __call__(self, request, **_kwargs): + self.calls.append(request) + return f"response:{request}" + + +class _FakeGrpcChannel(grpc.Channel): + + def __init__(self): + self.multicallables: dict[str, _FakeMultiCallable] = {} + + def _get(self, method: str) -> _FakeMultiCallable: + return self.multicallables.setdefault(method, _FakeMultiCallable()) + + def unary_unary(self, method, *args, **kwargs): + return self._get(method) + + def unary_stream(self, method, *args, **kwargs): + return self._get(method) + + def stream_unary(self, method, *args, **kwargs): + return self._get(method) + + def stream_stream(self, method, *args, **kwargs): + return self._get(method) + + def subscribe(self, callback, try_to_connect=False): + return None + + def unsubscribe(self, callback): + return None + + def close(self): + return None + + +class _FakePoller: + + def __init__( + self, + client: Any, + spark_ui_url_getter=None, + on_fallback=None, + **_kwargs, + ): + self.client = client + self.spark_ui_url_getter = spark_ui_url_getter + self.on_fallback = on_fallback + self.active_ops: set[str] = set() + self.begun: List[str] = [] + self.finished: List[tuple[str, str]] = [] + self.spark_tasks_seen: List[str] = [] + self.closed = False + self.is_supported = True + + def begin_operation(self, operation_id: str) -> bool: + if not self.is_supported or self.closed: + return False + self.begun.append(operation_id) + self.active_ops.add(operation_id) + return True + + def finish_operation( + self, operation_id: str, outcome: str = "SUCCEEDED" + ) -> None: + self.active_ops.discard(operation_id) + self.finished.append((operation_id, outcome)) + + def note_spark_tasks_seen(self, operation_id: str) -> None: + self.spark_tasks_seen.append(operation_id) + + def should_suppress_progress_bar(self, operation_id: str) -> bool: + return operation_id in self.active_ops and self.is_supported + + def close(self) -> None: + self.closed = True + self.active_ops.clear() + self.spark_ui_url_getter = None + self.on_fallback = None + + +class TestCellMonitoringBridgeUnit(unittest.TestCase): + + def test_proxied_channel_get_status_bypasses_liveness_guard(self): + fake_inner = _FakeGrpcChannel() + guard = mock.Mock(return_value=False) + with ( + mock.patch.object( + core.proxy, "ManagedSparkSessionProxy" + ) as proxy_cls, + mock.patch.object(core.proxy, "get_refreshed_credentials"), + mock.patch.object(core, "DefaultChannelBuilder") as builder_cls, + ): + proxy_cls.return_value.port = 12345 + builder_cls.return_value.toChannel.return_value = fake_inner + channel = core.ProxiedChannel("example.com", guard) + + get_status = channel.unary_unary( + "/spark.connect.SparkConnectService/GetStatus" + ) + self.assertIs( + get_status, + fake_inner.multicallables[ + "/spark.connect.SparkConnectService/GetStatus" + ], + ) + self.assertEqual(get_status("status-req"), "response:status-req") + guard.assert_not_called() + + analyze_plan = channel.unary_unary( + "/spark.connect.SparkConnectService/AnalyzePlan" + ) + with self.assertRaises(SessionNotActiveError): + analyze_plan("analyze-req") + guard.assert_called_once() + + def test_classify_exception_outcome(self): + self.assertEqual( + _cell_monitoring.classify_exception_outcome(KeyboardInterrupt()), + "CANCELLED", + ) + self.assertEqual( + _cell_monitoring.classify_exception_outcome(GeneratorExit()), + "CANCELLED", + ) + self.assertEqual( + _cell_monitoring.classify_exception_outcome( + _FakeRpcError(grpc.StatusCode.CANCELLED, "aborted") + ), + "CANCELLED", + ) + + class _GrpcStatusExc(Exception): + grpc_status_code = grpc.StatusCode.CANCELLED + + self.assertEqual( + _cell_monitoring.classify_exception_outcome(_GrpcStatusExc()), + "CANCELLED", + ) + + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + pyspark_cancel = SparkConnectGrpcException( + "Operation aborted", errorClass="OPERATION_CANCELED" + ) + self.assertEqual( + _cell_monitoring.classify_exception_outcome(pyspark_cancel), + "CANCELLED", + ) + self.assertEqual( + [w for w in caught if issubclass(w.category, FutureWarning)], + [], + ) + + class _LowerCondExc(Exception): + + def getCondition(self): + return "operation_canceled" + + class _LowerErrorClassExc(Exception): + + def getErrorClass(self): + return "spark_job_cancelled" + + self.assertEqual( + _cell_monitoring.classify_exception_outcome(_LowerCondExc()), + "CANCELLED", + ) + self.assertEqual( + _cell_monitoring.classify_exception_outcome(_LowerErrorClassExc()), + "CANCELLED", + ) + + self.assertEqual( + _cell_monitoring.classify_exception_outcome( + RuntimeError("SparkConnectGrpcException(OPERATION_CANCELED)") + ), + "CANCELLED", + ) + self.assertEqual( + _cell_monitoring.classify_exception_outcome( + RuntimeError("UnknownException(operation_canceled)") + ), + "CANCELLED", + ) + self.assertEqual( + _cell_monitoring.classify_exception_outcome( + RuntimeError("[JOB_CANCELLED] stopped") + ), + "CANCELLED", + ) + self.assertEqual( + _cell_monitoring.classify_exception_outcome( + RuntimeError("[spark_job_cancelled] Job 0 cancelled") + ), + "CANCELLED", + ) + self.assertEqual( + _cell_monitoring.classify_exception_outcome( + RuntimeError("ABORTED: job_cancelled") + ), + "CANCELLED", + ) + # Echoed user SQL literals must not false-positive as cancellation. + for literal in ( + "OPERATION_CANCELED", + "operation_canceled", + "JOB_CANCELLED", + "job_cancelled", + "spark_job_cancelled", + ): + self.assertEqual( + _cell_monitoring.classify_exception_outcome( + ValueError(f"ParseException: SELECT '{literal}'") + ), + "FAILED", + ) + self.assertEqual( + _cell_monitoring.classify_exception_outcome( + ValueError("Division by zero") + ), + "FAILED", + ) + + class _BrokenGrpcStatusExc(Exception): + + @property + def grpc_status_code(self): + raise RuntimeError("broken grpc_status_code") + + class _BrokenStrExc(Exception): + + def __str__(self) -> str: + raise RuntimeError("broken str") + + class _BrokenCauseExc(Exception): + + @property + def __cause__(self): + raise RuntimeError("broken cause") + + self.assertEqual( + _cell_monitoring.classify_exception_outcome( + _BrokenGrpcStatusExc("boom") + ), + "FAILED", + ) + self.assertEqual( + _cell_monitoring.classify_exception_outcome(_BrokenStrExc()), + "FAILED", + ) + self.assertEqual( + _cell_monitoring.classify_exception_outcome(_BrokenCauseExc()), + "FAILED", + ) + + # Broken outer wrapper still inspects cause/context chain. + try: + try: + raise _FakeRpcError(grpc.StatusCode.CANCELLED, "root cancel") + except BaseException as root: + raise _BrokenGrpcStatusExc("outer wrapper") from root + except BaseException as wrapped: + self.assertEqual( + _cell_monitoring.classify_exception_outcome(wrapped), + "CANCELLED", + ) + + class _NonExceptionGetCondition(Exception): + + def getCondition(self): + raise KeyboardInterrupt("interrupt") + + with self.assertRaises(KeyboardInterrupt): + _cell_monitoring.classify_exception_outcome( + _NonExceptionGetCondition() + ) + + def test_noop_when_cell_monitoring_extension_not_loaded(self): + with mock.patch.dict( + sys.modules, {_cell_monitoring._CELL_MONITOR_EXTENSION: None} + ): + bridge = _cell_monitoring.SessionCellMonitorBridge(mock.MagicMock()) + self.assertFalse(bridge.begin_operation("op-1")) + self.assertFalse(bridge.should_suppress_progress_bar("op-1")) + bridge.note_spark_tasks_seen("op-1") + bridge.finish_operation("op-1", outcome="SUCCEEDED") + bridge.close() + + def test_bridge_error_handling_factory_latch_and_close_hygiene(self): + calls = 0 + + def _raising_factory(*_args, **_kwargs): + nonlocal calls + calls += 1 + raise RuntimeError("boom") + + fake_mod = types.ModuleType(_cell_monitoring._CELL_MONITOR_EXTENSION) + fake_mod.create_session_poller = _raising_factory # type: ignore[attr-defined] + with mock.patch.dict( + sys.modules, {_cell_monitoring._CELL_MONITOR_EXTENSION: fake_mod} + ): + b1 = _cell_monitoring.SessionCellMonitorBridge(mock.MagicMock()) + self.assertFalse(b1.begin_operation("op-1")) + self.assertFalse(b1.begin_operation("op-2")) + self.assertEqual(calls, 1) + + finish_calls = 0 + + class _BrokenFinishPoller(_FakePoller): + + def finish_operation( + self, operation_id: str, outcome: str = "SUCCEEDED" + ) -> None: + nonlocal finish_calls + finish_calls += 1 + raise TypeError("internal type mismatch") + + created: List[_BrokenFinishPoller] = [] + fake_mod2 = types.ModuleType(_cell_monitoring._CELL_MONITOR_EXTENSION) + fake_mod2.create_session_poller = lambda client, **kw: ( # type: ignore[attr-defined] + created.append(_BrokenFinishPoller(client, **kw)) or created[-1] + ) + client = mock.MagicMock() + with mock.patch.dict( + sys.modules, {_cell_monitoring._CELL_MONITOR_EXTENSION: fake_mod2} + ): + b2 = _cell_monitoring.SessionCellMonitorBridge(client) + self.assertTrue(b2.begin_operation("op-3")) + b2.finish_operation("op-3", outcome="SUCCEEDED") + self.assertEqual(finish_calls, 1) + b2.close() + self.assertIsNone(b2._client) + self.assertTrue(created[0].closed) + self.assertFalse(b2.begin_operation("op-4")) + + +class TestSessionAndExtrasIntegration(unittest.TestCase): + + def _create_local_session(self) -> ManagedSparkSession: + with mock.patch( + "pyspark.sql.connect.session.SparkSession._start_connect_server" + ): + session = ManagedSparkSession("sc://localhost:15002") + session._register_progress_execution_handler() + return session + + def _patch_session_metadata(self): + p_proj = mock.patch.object(ManagedSparkSession, "_project_id", "proj-1") + p_reg = mock.patch.object(ManagedSparkSession, "_region", "us-central1") + p_sid = mock.patch.object( + ManagedSparkSession, "_active_s8s_session_id", "sc-sess-1" + ) + p_file = mock.patch.object( + ManagedSparkSession, + "_get_active_session_file_path", + return_value=None, + ) + for p in (p_proj, p_reg, p_sid, p_file): + p.start() + self.addCleanup(p.stop) + + def test_session_hooks_outcomes_progress_suppression_fallback_and_gc(self): + self._patch_session_metadata() + created_pollers: List[_FakePoller] = [] + fake_mod = types.ModuleType(_cell_monitoring._CELL_MONITOR_EXTENSION) + + def _factory(client, **kwargs): + p = _FakePoller(client, **kwargs) + created_pollers.append(p) + return p + + fake_mod.create_session_poller = _factory # type: ignore[attr-defined] + + with mock.patch.dict( + sys.modules, + {_cell_monitoring._CELL_MONITOR_EXTENSION: fake_mod}, + ): + bars_opened: List[Any] = [] + ManagedSparkSession._set_tqdm_factory( + lambda **kw: bars_opened.append(kw) + or mock.MagicMock(n=0, total=4) + ) + self.addCleanup(ManagedSparkSession._set_tqdm_factory, None) + + active_sess: List[ManagedSparkSession] = [] + yielded_during_active: List[bool] = [] + stream_mode = "ok" + + def _fake_stream(r, *a, **kw): + s = active_sess[0] + for h in s.client._progress_handlers: + h([StageInfo(1, 4, 2, 0, False)], 2, r.operation_id, False) + yielded_during_active.append( + s._cell_monitor_bridge.should_suppress_progress_bar( + r.operation_id + ) + ) + yield "batch-1" + if stream_mode == "fail": + raise RuntimeError("task failed") + if stream_mode == "cancel": + raise KeyboardInterrupt() + yield "batch-2" + + with ( + mock.patch.dict( + "os.environ", + {"MANAGED_SPARK_CONNECT_FORCE_PROGRESS_BAR": "1"}, + ), + mock.patch( + "pyspark.sql.connect.client.core.SparkConnectClient._execute_and_fetch_as_iterator", + side_effect=_fake_stream, + ), + ): + s2 = self._create_local_session() + active_sess.append(s2) + req1 = s2.client._execute_plan_request_with_metadata() + + with mock.patch.object( + s2, "_display_operation_link" + ) as mock_link: + # 1. Normal exhaustion -> outcome="SUCCEEDED" + it = s2.client._execute_and_fetch_as_iterator(req1, {}) + self.assertEqual(next(it), "batch-1") + self.assertEqual(yielded_during_active, [True]) + self.assertEqual(len(created_pollers), 1) + poller = created_pollers[0] + self.assertEqual(poller.finished, []) + expected_url = ( + "https://console.cloud.google.com/dataproc/interactive/" + "us-central1/sc-sess-1/sparkApplications/applications" + "?project=proj-1" + ) + self.assertEqual(poller.spark_ui_url_getter(), expected_url) + self.assertIn(expected_url, s2._repr_html_()) + self.assertEqual(next(it), "batch-2") + with self.assertRaises(StopIteration): + next(it) + mock_link.assert_not_called() + self.assertEqual( + poller.finished, [(req1.operation_id, "SUCCEEDED")] + ) + self.assertEqual( + poller.spark_tasks_seen, [req1.operation_id] + ) + + # 2. Mid-stream exception -> outcome="FAILED" + stream_mode = "fail" + req2 = s2.client._execute_plan_request_with_metadata() + it2 = s2.client._execute_and_fetch_as_iterator(req2, {}) + self.assertEqual(next(it2), "batch-1") + with self.assertRaises(RuntimeError): + next(it2) + self.assertEqual( + poller.finished[-1], (req2.operation_id, "FAILED") + ) + + # 3. KeyboardInterrupt -> outcome="CANCELLED" + stream_mode = "cancel" + req3 = s2.client._execute_plan_request_with_metadata() + it3 = s2.client._execute_and_fetch_as_iterator(req3, {}) + self.assertEqual(next(it3), "batch-1") + with self.assertRaises(KeyboardInterrupt): + next(it3) + self.assertEqual( + poller.finished[-1], + (req3.operation_id, "CANCELLED"), + ) + + # 4. Fallback callback displays suppressed operation link + poller.on_fallback(["op-fallback"]) + mock_link.assert_called_once_with("op-fallback") + + self.assertEqual(bars_opened, []) + + # Verify _close_client stops poller and leaves zero refcycles pinning session + active_sess.clear() + del it, it2, it3 + ManagedSparkSession._forget_server_session(s2) + weak_s2 = weakref.ref(s2) + s2._close_client() + self.assertTrue(poller.closed) + del s2 + gc.collect() + self.assertIsNone(weak_s2()) + + def test_monitored_and_unmonitored_execute_and_lazy_sql_skip(self): + self._patch_session_metadata() + created_pollers: List[_FakePoller] = [] + fake_mod = types.ModuleType(_cell_monitoring._CELL_MONITOR_EXTENSION) + fake_mod.create_session_poller = lambda client, **kw: ( # type: ignore[attr-defined] + created_pollers.append(_FakePoller(client, **kw)) + or created_pollers[-1] + ) + + modes_by_op: dict[str, str] = {} + + def _exec_behavior(req, *a, **kw): + mode = modes_by_op.get(req.operation_id, "ok") + if mode == "fail": + raise RuntimeError("execute failed") + if mode == "cancel": + raise _FakeRpcError(grpc.StatusCode.CANCELLED, "user aborted") + if mode == "mutate": + req.operation_id = "mutated-in-inner" + return "exec-ok" + + with ( + mock.patch.dict( + sys.modules, + {_cell_monitoring._CELL_MONITOR_EXTENSION: fake_mod}, + ), + mock.patch( + "pyspark.sql.connect.client.core.SparkConnectClient._execute", + side_effect=_exec_behavior, + ), + mock.patch.object( + _cell_monitoring, + "classify_exception_outcome", + wraps=_cell_monitoring.classify_exception_outcome, + ) as mock_classify, + ): + s = self._create_local_session() + self.addCleanup(s._close_client) + + with mock.patch.object(s, "_display_operation_link") as mock_link: + # 1. Monitored _execute(): SUCCEEDED, FAILED, CANCELLED + req_ok = s.client._execute_plan_request_with_metadata() + modes_by_op[req_ok.operation_id] = "ok" + self.assertEqual(s.client._execute(req_ok, {}), "exec-ok") + + req_fail = s.client._execute_plan_request_with_metadata() + modes_by_op[req_fail.operation_id] = "fail" + with self.assertRaises(RuntimeError): + s.client._execute(req_fail, {}) + + req_cancel = s.client._execute_plan_request_with_metadata() + modes_by_op[req_cancel.operation_id] = "cancel" + with self.assertRaises(grpc.RpcError): + s.client._execute(req_cancel, {}) + + poller = created_pollers[0] + self.assertEqual( + poller.finished, + [ + (req_ok.operation_id, "SUCCEEDED"), + (req_fail.operation_id, "FAILED"), + (req_cancel.operation_id, "CANCELLED"), + ], + ) + mock_link.assert_not_called() + + # 2. Lazy SQL SELECT skips monitoring; eager DML + mutated op_id pair cleanly + lazy_req = s.client._execute_plan_request_with_metadata() + lazy_req.plan.command.sql_command.input.sql.query = ( + "SELECT * FROM tbl" + ) + self.assertEqual(s.client._execute(lazy_req, {}), "exec-ok") + self.assertNotIn(lazy_req.operation_id, poller.begun) + + dml_req = s.client._execute_plan_request_with_metadata() + dml_req.plan.command.sql_command.input.sql.query = ( + "INSERT INTO test_table_2 VALUES (1)" + ) + self.assertEqual(s.client._execute(dml_req, {}), "exec-ok") + self.assertIn(dml_req.operation_id, poller.begun) + self.assertEqual( + poller.finished[-1], + (dml_req.operation_id, "SUCCEEDED"), + ) + + req_mutate = s.client._execute_plan_request_with_metadata() + orig_mutate_id = req_mutate.operation_id + modes_by_op[orig_mutate_id] = "mutate" + self.assertEqual(s.client._execute(req_mutate, {}), "exec-ok") + self.assertIn(orig_mutate_id, poller.begun) + self.assertEqual( + poller.finished[-1], (orig_mutate_id, "SUCCEEDED") + ) + self.assertEqual(poller.active_ops, set()) + mock_link.assert_not_called() + + # 3. Unmonitored _execute(): skips classification; gates link + mock_classify.reset_mock() + poller.is_supported = False + req_unmon = s.client._execute_plan_request_with_metadata() + modes_by_op[req_unmon.operation_id] = "fail" + with self.assertRaises(RuntimeError): + s.client._execute(req_unmon, {}) + mock_classify.assert_not_called() + mock_link.assert_called_once_with(req_unmon.operation_id) + + mock_link.reset_mock() + eager_unmon = s.client._execute_plan_request_with_metadata() + eager_unmon.plan.command.sql_command.input.sql.query = ( + "INSERT INTO test_table_2 VALUES (1)" + ) + self.assertEqual(s.client._execute(eager_unmon, {}), "exec-ok") + mock_link.assert_called_once_with(eager_unmon.operation_id) + + mock_link.reset_mock() + lazy_unmon = s.client._execute_plan_request_with_metadata() + lazy_unmon.plan.command.sql_command.input.sql.query = ( + "SELECT * FROM tbl" + ) + self.assertEqual(s.client._execute(lazy_unmon, {}), "exec-ok") + mock_link.assert_not_called() + + def test_iterator_closed_before_next_and_closed_mid_stream(self): + self._patch_session_metadata() + created_pollers: List[_FakePoller] = [] + fake_mod = types.ModuleType(_cell_monitoring._CELL_MONITOR_EXTENSION) + fake_mod.create_session_poller = lambda client, **kw: ( # type: ignore[attr-defined] + created_pollers.append(_FakePoller(client, **kw)) + or created_pollers[-1] + ) + inner_closed: List[str] = [] + + mutate_ops: set[str] = set() + + def _fake_stream(req, *a, **kw): + op_id = req.operation_id + if op_id in mutate_ops: + req.operation_id = "mutated-stream-id" + try: + yield "row-1" + yield "row-2" + finally: + inner_closed.append(op_id) + + with ( + mock.patch.dict( + sys.modules, + {_cell_monitoring._CELL_MONITOR_EXTENSION: fake_mod}, + ), + mock.patch( + "pyspark.sql.connect.client.core.SparkConnectClient._execute_and_fetch_as_iterator", + side_effect=_fake_stream, + ), + ): + s = self._create_local_session() + self.addCleanup(s._close_client) + + # 1. Closed / dropped before first next() -> never began or leaked + req_drop = s.client._execute_plan_request_with_metadata() + it_drop = s.client._execute_and_fetch_as_iterator(req_drop, {}) + it_drop.close() + self.assertEqual(created_pollers, []) + self.assertEqual(inner_closed, []) + + # 2. Lazy SQL iterator skips monitoring; eager DML monitors and unmonitored gates link + req_lazy = s.client._execute_plan_request_with_metadata() + req_lazy.plan.command.sql_command.input.sql.query = "SELECT 1" + with mock.patch.object(s, "_display_operation_link") as mock_link: + self.assertEqual( + list(s.client._execute_and_fetch_as_iterator(req_lazy, {})), + ["row-1", "row-2"], + ) + mock_link.assert_not_called() + self.assertEqual(created_pollers, []) + + req_dml = s.client._execute_plan_request_with_metadata() + req_dml.plan.command.sql_command.input.sql.query = ( + "INSERT INTO test_table_2 VALUES (1)" + ) + orig_dml_id = req_dml.operation_id + mutate_ops.add(orig_dml_id) + self.assertEqual( + list(s.client._execute_and_fetch_as_iterator(req_dml, {})), + ["row-1", "row-2"], + ) + poller = created_pollers[0] + self.assertEqual(poller.begun, [orig_dml_id]) + self.assertEqual(poller.finished, [(orig_dml_id, "SUCCEEDED")]) + self.assertEqual(poller.active_ops, set()) + + with mock.patch.object(s, "_display_operation_link") as mock_link: + poller.is_supported = False + req_unmon_lazy = s.client._execute_plan_request_with_metadata() + req_unmon_lazy.plan.command.sql_command.input.sql.query = ( + "SELECT 1" + ) + self.assertEqual( + list( + s.client._execute_and_fetch_as_iterator( + req_unmon_lazy, {} + ) + ), + ["row-1", "row-2"], + ) + mock_link.assert_not_called() + + req_unmon_dml = s.client._execute_plan_request_with_metadata() + req_unmon_dml.plan.command.sql_command.input.sql.query = ( + "INSERT INTO test_table_2 VALUES (1)" + ) + self.assertEqual( + list( + s.client._execute_and_fetch_as_iterator( + req_unmon_dml, {} + ) + ), + ["row-1", "row-2"], + ) + mock_link.assert_called_once_with(req_unmon_dml.operation_id) + + poller.is_supported = True + + # 3. Closed mid-stream -> closes inner generator and reports CANCELLED + req_mid = s.client._execute_plan_request_with_metadata() + it_mid = s.client._execute_and_fetch_as_iterator(req_mid, {}) + self.assertEqual(next(it_mid), "row-1") + self.assertIn(req_mid.operation_id, poller.active_ops) + it_mid.close() + self.assertIn(req_mid.operation_id, inner_closed) + self.assertEqual( + poller.finished[-1], (req_mid.operation_id, "CANCELLED") + ) + self.assertEqual(poller.active_ops, set()) + + # 4. Missing bridge still gates operation link on lazy SQL + s._cell_monitor_bridge = None + with mock.patch.object(s, "_display_operation_link") as mock_link: + req_no_bridge_lazy = ( + s.client._execute_plan_request_with_metadata() + ) + req_no_bridge_lazy.plan.command.sql_command.input.sql.query = ( + "SELECT 1" + ) + self.assertEqual( + list( + s.client._execute_and_fetch_as_iterator( + req_no_bridge_lazy, {} + ) + ), + ["row-1", "row-2"], + ) + mock_link.assert_not_called() + + req_no_bridge_dml = ( + s.client._execute_plan_request_with_metadata() + ) + req_no_bridge_dml.plan.command.sql_command.input.sql.query = ( + "INSERT INTO test_table_2 VALUES (1)" + ) + self.assertEqual( + list( + s.client._execute_and_fetch_as_iterator( + req_no_bridge_dml, {} + ) + ), + ["row-1", "row-2"], + ) + mock_link.assert_called_once_with( + req_no_bridge_dml.operation_id + ) + + def test_progress_handler_suppression_done_guard_and_resumption(self): + self._patch_session_metadata() + created_pollers: List[_FakePoller] = [] + fake_mod = types.ModuleType(_cell_monitoring._CELL_MONITOR_EXTENSION) + fake_mod.create_session_poller = lambda client, **kw: ( # type: ignore[attr-defined] + created_pollers.append(_FakePoller(client, **kw)) + or created_pollers[-1] + ) + + bars: List[Any] = [] + + def _make_bar(**kw): + bar = mock.MagicMock(n=0, total=kw["total"]) + bars.append(bar) + return bar + + ManagedSparkSession._set_tqdm_factory(_make_bar) + self.addCleanup(ManagedSparkSession._set_tqdm_factory, None) + + with ( + mock.patch.dict( + sys.modules, + {_cell_monitoring._CELL_MONITOR_EXTENSION: fake_mod}, + ), + mock.patch.dict( + "os.environ", {"MANAGED_SPARK_CONNECT_FORCE_PROGRESS_BAR": "1"} + ), + ): + s = self._create_local_session() + self.addCleanup(s._close_client) + self.addCleanup(s._close_progress_bar, "op-p") + self.assertTrue(s._cell_monitor_bridge.begin_operation("op-p")) + poller = created_pollers[0] + handler = s.client._progress_handlers[-1] + + # 1. Start unmonitored/unsuppressed so tqdm bar opens + poller.is_supported = False + handler([StageInfo(1, 4, 1, 0, False)], 1, "op-p", False) + self.assertEqual(len(bars), 1) + self.assertFalse(bars[0].close.called) + self.assertEqual(poller.spark_tasks_seen, ["op-p"]) + + # 2. Suppression turns True -> open tqdm bar closes immediately + poller.is_supported = True + handler([StageInfo(1, 4, 2, 0, False)], 1, "op-p", False) + bars[0].close.assert_called_once() + self.assertEqual(len(poller.spark_tasks_seen), 2) + + # 3. done=True does NOT record note_spark_tasks_seen after finish + handler([StageInfo(1, 4, 4, 0, True)], 0, "op-p", True) + self.assertEqual(len(poller.spark_tasks_seen), 2) + + # 4. When fallback flips suppression to False, tqdm resumes cleanly + poller.is_supported = False + handler([StageInfo(1, 4, 3, 0, False)], 1, "op-p", False) + self.assertEqual(len(bars), 2) + handler([StageInfo(1, 4, 4, 0, True)], 0, "op-p", True) + bars[1].close.assert_called_once() + + def test_ipython_extras_loads_and_unloads_cellmonitor_extension(self): + from IPython.core.interactiveshell import InteractiveShell + from google.cloud.managed_spark_connect import _ipython + + fake_ext = types.ModuleType(_cell_monitoring._CELL_MONITOR_EXTENSION) + unloaded: List[Any] = [] + poller_created: List[Any] = [] + + def _load_ext(ip): + def cellmonitor(line=""): + return line + + cellmonitor.__module__ = _cell_monitoring._CELL_MONITOR_EXTENSION + ip.register_magic_function( + cellmonitor, magic_kind="line", magic_name="cellmonitor" + ) + + def _unload_ext(ip): + unloaded.append(ip) + + fake_ext.load_ipython_extension = _load_ext # type: ignore[attr-defined] + fake_ext.unload_ipython_extension = _unload_ext # type: ignore[attr-defined] + fake_ext.create_session_poller = lambda client, **kw: ( # type: ignore[attr-defined] + poller_created.append(client) or _FakePoller(client, **kw) + ) + + ip = InteractiveShell.instance() + self.addCleanup(InteractiveShell.clear_instance) + self.addCleanup(_ipython._SHELL_STATES.clear) + _ipython._SHELL_STATES.clear() + ip.magics_manager.magics.get("line", {}).pop("cellmonitor", None) + + spec = types.SimpleNamespace( + name=fake_ext.__name__, _initializing=False + ) + fake_ext.__spec__ = spec # type: ignore[attr-defined] + + stdout_buf = io.StringIO() + with ( + mock.patch.dict( + sys.modules, + { + "managed_spark_cell_monitoring": types.ModuleType( + "managed_spark_cell_monitoring" + ), + _cell_monitoring._CELL_MONITOR_EXTENSION: fake_ext, + "google.colabsqlviz": None, + "google.cloud.managed_spark_magics": None, + }, + ), + mock.patch("IPython.get_ipython", return_value=ip), + mock.patch("sys.stdout", stdout_buf), + ): + _ipython._init_extras() + self.assertIn("%cellmonitor", stdout_buf.getvalue()) + self.assertIn("cellmonitor", ip.magics_manager.magics["line"]) + + _ipython._get_or_create_config(ip).enable_extras = False + self.assertEqual(unloaded, [ip]) + self.assertNotIn("cellmonitor", ip.magics_manager.magics["line"]) + + # Even though the module stays in sys.modules, a new bridge stays idle. + bridge = _cell_monitoring.SessionCellMonitorBridge(mock.MagicMock()) + self.assertFalse(bridge.begin_operation("op-after-disable")) + self.assertEqual(poller_created, []) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/test_init.py b/tests/unit/test_init.py index 78be3cba..edaa5de9 100644 --- a/tests/unit/test_init.py +++ b/tests/unit/test_init.py @@ -305,6 +305,15 @@ def setUp(self): env_patcher = mock.patch.dict(os.environ) env_patcher.start() self.addCleanup(env_patcher.stop) + # Isolate optional cell-monitoring extension so unit assertions on + # managed_spark_magics remain deterministic whether or not + # managed-spark-cell-monitoring is also installed in the venv. + mod_patcher = mock.patch.dict( + sys.modules, + {"managed_spark_cell_monitoring.spark_connect": None}, + ) + mod_patcher.start() + self.addCleanup(mod_patcher.stop) os.environ.pop(_ipython.ENV_ENABLE_EXTRAS, None) _ipython._SHELL_STATES.clear() self.addCleanup(_ipython._SHELL_STATES.clear)