From e6a9f7c0982724d12b4adcb4d5e64fc0d9266cbf Mon Sep 17 00:00:00 2001 From: Patrick Chen Date: Mon, 16 Nov 2026 21:45:08 +0000 Subject: [PATCH 1/7] feat: integrate ManagedSparkSession with Spark Connect cell monitoring Wires optional notebook cell monitoring into `ManagedSparkSession` and IPython interactive extras via a lightweight lifecycle bridge: - `google.cloud.managed_spark_connect._ipython`: auto-loads `managed_spark_cell_monitoring.spark_connect` (`%cellmonitor`) alongside installed interactive extras when available. - `google.cloud.managed_spark_connect.client.core`: adds `/GetStatus` to `_UNGUARDED_METHOD_SUFFIXES` so background `GetStatus` polling runs concurrently with in-flight `ExecutePlan` streams. - `google.cloud.managed_spark_connect._cell_monitoring` & `session`: - Lazily delegates `begin_operation`, `finish_operation(..., outcome=...)` (`SUCCEEDED`, `FAILED`, `CANCELLED`), and task progress suppression to `managed_spark_cell_monitoring.spark_connect.create_session_poller(...)` with zero imports or overhead when the extension is inactive. - Restores per-operation Console links and legacy `tqdm` progress bars automatically if the session falls back. --- .../managed_spark_connect/_cell_monitoring.py | 191 ++++++++++ .../cloud/managed_spark_connect/_ipython.py | 6 +- .../managed_spark_connect/client/core.py | 6 +- google/cloud/managed_spark_connect/session.py | 107 +++++- tests/unit/test_cell_monitoring.py | 341 ++++++++++++++++++ tests/unit/test_init.py | 9 + 6 files changed, 649 insertions(+), 11 deletions(-) create mode 100644 google/cloud/managed_spark_connect/_cell_monitoring.py create mode 100644 tests/unit/test_cell_monitoring.py 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..9b061e9c --- /dev/null +++ b/google/cloud/managed_spark_connect/_cell_monitoring.py @@ -0,0 +1,191 @@ +# 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 sys +import threading +from typing import Any, Callable, List, Optional + +logger = logging.getLogger(__name__) + + +def classify_exception_outcome(exc: BaseException) -> str: + """Classifies an `ExecutePlan` exception into `CANCELLED` or `FAILED`.""" + if isinstance(exc, (KeyboardInterrupt, GeneratorExit)): + return "CANCELLED" + + seen: set[int] = set() + cur: Optional[BaseException] = exc + while cur is not None and id(cur) not in seen: + seen.add(id(cur)) + code_fn = getattr(cur, "code", None) + if callable(code_fn): + try: + code = code_fn() + if getattr(code, "name", None) == "CANCELLED": + return "CANCELLED" + except Exception: + pass + grpc_code = getattr(cur, "grpc_status_code", None) + if getattr(grpc_code, "name", None) == "CANCELLED": + return "CANCELLED" + err_cls_fn = getattr(cur, "getErrorClass", None) + if callable(err_cls_fn): + try: + err_cls = err_cls_fn() or "" + if "CANCELED" in err_cls or "CANCELLED" in err_cls: + return "CANCELLED" + except Exception: + pass + msg = str(cur) + if "OPERATION_CANCELED" in msg or "JOB_CANCELLED" in msg: + return "CANCELLED" + cur = cur.__cause__ or cur.__context__ + + return "FAILED" + + +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 + + @property + def is_supported(self) -> bool: + poller = self._poller + if poller is None: + return True + return bool(getattr(poller, "is_supported", True)) + + def _resolve_poller(self) -> Any: + poller = self._poller + if poller is not None or self._closed: + return poller + mod = sys.modules.get("managed_spark_cell_monitoring.spark_connect") + 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: + 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: + 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: + 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 TypeError: + poller.finish_operation(operation_id) + 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: + 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._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..e42fff75 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) diff --git a/google/cloud/managed_spark_connect/client/core.py b/google/cloud/managed_spark_connect/client/core.py index ebc8c705..f3762bb9 100644 --- a/google/cloud/managed_spark_connect/client/core.py +++ b/google/cloud/managed_spark_connect/client/core.py @@ -29,7 +29,11 @@ logger = logging.getLogger(__name__) -_UNGUARDED_METHOD_SUFFIXES = ("/ReleaseExecute", "/ReleaseSession") +_UNGUARDED_METHOD_SUFFIXES = ( + "/ReleaseExecute", + "/ReleaseSession", + "/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..82ee0838 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,17 @@ 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_ui_url = weakref.WeakMethod(self._get_session_spark_ui_url) + weak_fallback = weakref.WeakMethod(self._on_cell_monitor_fallback) + self._cell_monitor_poller = _cell_monitoring.SessionCellMonitorBridge( + self.client, + spark_ui_url_getter=lambda: ( + fn() if (fn := weak_ui_url()) is not None else "" + ), + on_fallback=lambda op_ids: ( + fn(op_ids) if (fn := weak_fallback()) 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 +2086,50 @@ def _execute_plan_request_with_metadata(*args, **kwargs): def execute_hook(inner): def _execute(req, *args, **kwargs): + monitored = False if not self._sql_lazy_transformation(req): - self._display_operation_link(req.operation_id) - return inner(req, *args, **kwargs) + monitored = self._cell_monitor_poller.begin_operation( + req.operation_id + ) + if not monitored: + self._display_operation_link(req.operation_id) + outcome = "SUCCEEDED" + try: + return inner(req, *args, **kwargs) + except BaseException as exc: + outcome = _cell_monitoring.classify_exception_outcome(exc) + raise + finally: + if monitored: + self._cell_monitor_poller.finish_operation( + req.operation_id, outcome=outcome + ) return _execute def execute_and_fetch_as_iterator_hook(inner): def _execute_and_fetch_as_iterator(req, *args, **kwargs): + monitored = False if not self._sql_lazy_transformation(req): - self._display_operation_link(req.operation_id) - return inner(req, *args, **kwargs) + monitored = self._cell_monitor_poller.begin_operation( + req.operation_id + ) + if not monitored: + self._display_operation_link(req.operation_id) + try: + iterator = inner(req, *args, **kwargs) + except BaseException as exc: + if monitored: + self._cell_monitor_poller.finish_operation( + req.operation_id, + outcome=_cell_monitoring.classify_exception_outcome( + exc + ), + ) + raise + if not monitored: + return iterator + return self._wrap_monitored_iterator(iterator, req.operation_id) return _execute_and_fetch_as_iterator @@ -2165,11 +2211,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 +2218,21 @@ def handler( total_tasks += stage.num_tasks completed_tasks += stage.num_completed_tasks + poller = self.__dict__.get("_cell_monitor_poller") + if poller is not None: + if total_tasks > 0: + poller.note_spark_tasks_seen(operation_id) + if poller.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 +2378,36 @@ def _sql_lazy_transformation(req): except AttributeError: return False + def _wrap_monitored_iterator(self, iterator, operation_id: str): + outcome = "CANCELLED" + try: + yield from iterator + outcome = "SUCCEEDED" + except BaseException as exc: + outcome = _cell_monitoring.classify_exception_outcome(exc) + raise + finally: + poller = self.__dict__.get("_cell_monitor_poller") + if poller is not None: + poller.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: + 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 """ @@ -2549,6 +2635,9 @@ def _close_client(self) -> None: logger.debug( "Failed to close the StreamingQueryManager", exc_info=True ) + poller = self.__dict__.get("_cell_monitor_poller") + if poller is not None: + poller.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..3c7df532 --- /dev/null +++ b/tests/unit/test_cell_monitoring.py @@ -0,0 +1,341 @@ +# 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 weakref + +import grpc +from pyspark.sql.connect.shell.progress import StageInfo + +from google.cloud.managed_spark_connect import _cell_monitoring +from google.cloud.managed_spark_connect.client.core import ( + _UNGUARDED_METHOD_SUFFIXES, +) +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 _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_get_status_is_unguarded_method_suffix(self): + self.assertTrue( + "/spark.connect.SparkConnectService/GetStatus".endswith( + _UNGUARDED_METHOD_SUFFIXES + ) + ) + + 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", + ) + + wrapped = RuntimeError("SparkConnectGrpcException(OPERATION_CANCELED)") + self.assertEqual( + _cell_monitoring.classify_exception_outcome(wrapped), + "CANCELLED", + ) + self.assertEqual( + _cell_monitoring.classify_exception_outcome( + ValueError("Division by zero") + ), + "FAILED", + ) + + def test_noop_when_cell_monitoring_extension_not_loaded(self): + with mock.patch.dict( + sys.modules, {"managed_spark_cell_monitoring.spark_connect": 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() + + +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 test_session_hooks_outcomes_progress_suppression_fallback_and_gc(self): + created_pollers: List[_FakePoller] = [] + fake_mod = types.ModuleType( + "managed_spark_cell_monitoring.spark_connect" + ) + + 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, + {"managed_spark_cell_monitoring.spark_connect": fake_mod}, + ): + ManagedSparkSession._project_id = "proj-1" + ManagedSparkSession._region = "us-central1" + ManagedSparkSession._active_s8s_session_id = "sc-sess-1" + + 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_poller.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"}, + ): + with 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, []) + self.assertEqual( + poller.spark_ui_url_getter(), + "https://console.cloud.google.com/dataproc/interactive/us-central1/sc-sess-1/sparkApplications/applications?project=proj-1", + ) + 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_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( + "managed_spark_cell_monitoring.spark_connect" + ) + unloaded: List[Any] = [] + + def _load_ext(ip): + def cellmonitor(line=""): + return line + + cellmonitor.__module__ = ( + "managed_spark_cell_monitoring.spark_connect" + ) + 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] + + 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" + ), + "managed_spark_cell_monitoring.spark_connect": 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"]) + + +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) From 5f078ee314395f7fb75ec36048994bf1f5663d7b Mon Sep 17 00:00:00 2001 From: Patrick Chen Date: Thu, 19 Nov 2026 22:09:42 +0000 Subject: [PATCH 2/7] fix: harden cell monitoring exception classification and session GC cleanup --- .../managed_spark_connect/_cell_monitoring.py | 61 +++++++------- google/cloud/managed_spark_connect/session.py | 8 +- tests/unit/test_cell_monitoring.py | 80 +++++++++++++++++++ 3 files changed, 119 insertions(+), 30 deletions(-) diff --git a/google/cloud/managed_spark_connect/_cell_monitoring.py b/google/cloud/managed_spark_connect/_cell_monitoring.py index 9b061e9c..28e8454a 100644 --- a/google/cloud/managed_spark_connect/_cell_monitoring.py +++ b/google/cloud/managed_spark_connect/_cell_monitoring.py @@ -23,36 +23,39 @@ def classify_exception_outcome(exc: BaseException) -> str: """Classifies an `ExecutePlan` exception into `CANCELLED` or `FAILED`.""" - if isinstance(exc, (KeyboardInterrupt, GeneratorExit)): - return "CANCELLED" - - seen: set[int] = set() - cur: Optional[BaseException] = exc - while cur is not None and id(cur) not in seen: - seen.add(id(cur)) - code_fn = getattr(cur, "code", None) - if callable(code_fn): - try: - code = code_fn() - if getattr(code, "name", None) == "CANCELLED": - return "CANCELLED" - except Exception: - pass - grpc_code = getattr(cur, "grpc_status_code", None) - if getattr(grpc_code, "name", None) == "CANCELLED": - return "CANCELLED" - err_cls_fn = getattr(cur, "getErrorClass", None) - if callable(err_cls_fn): - try: - err_cls = err_cls_fn() or "" - if "CANCELED" in err_cls or "CANCELLED" in err_cls: - return "CANCELLED" - except Exception: - pass - msg = str(cur) - if "OPERATION_CANCELED" in msg or "JOB_CANCELLED" in msg: + try: + if isinstance(exc, (KeyboardInterrupt, GeneratorExit)): return "CANCELLED" - cur = cur.__cause__ or cur.__context__ + + seen: set[int] = set() + cur: Optional[BaseException] = exc + while cur is not None and id(cur) not in seen: + seen.add(id(cur)) + code_fn = getattr(cur, "code", None) + if callable(code_fn): + try: + code = code_fn() + if getattr(code, "name", None) == "CANCELLED": + return "CANCELLED" + except Exception: + pass + grpc_code = getattr(cur, "grpc_status_code", None) + if getattr(grpc_code, "name", None) == "CANCELLED": + return "CANCELLED" + err_cls_fn = getattr(cur, "getErrorClass", None) + if callable(err_cls_fn): + try: + err_cls = err_cls_fn() or "" + if "CANCELED" in err_cls or "CANCELLED" in err_cls: + return "CANCELLED" + except Exception: + pass + msg = str(cur) + if "OPERATION_CANCELED" in msg or "JOB_CANCELLED" in msg: + return "CANCELLED" + cur = cur.__cause__ or cur.__context__ + except BaseException: + pass return "FAILED" diff --git a/google/cloud/managed_spark_connect/session.py b/google/cloud/managed_spark_connect/session.py index 82ee0838..ac43d13f 100644 --- a/google/cloud/managed_spark_connect/session.py +++ b/google/cloud/managed_spark_connect/session.py @@ -2097,7 +2097,10 @@ def _execute(req, *args, **kwargs): try: return inner(req, *args, **kwargs) except BaseException as exc: - outcome = _cell_monitoring.classify_exception_outcome(exc) + if monitored: + outcome = _cell_monitoring.classify_exception_outcome( + exc + ) raise finally: if monitored: @@ -2612,6 +2615,9 @@ def __del__(self) -> None: # stop() the GC may run that on any thread, including a # ReleaseExecute pool worker, where shutting the shared release pool # down fails half-way and leaves it unusable for the whole process. + poller = self.__dict__.get("_cell_monitor_poller") + if poller is not None: + poller.close() if self.__dict__.get("_client_closed"): return super().__del__() diff --git a/tests/unit/test_cell_monitoring.py b/tests/unit/test_cell_monitoring.py index 3c7df532..19cc82e1 100644 --- a/tests/unit/test_cell_monitoring.py +++ b/tests/unit/test_cell_monitoring.py @@ -13,6 +13,7 @@ # limitations under the License. """Unit tests for thin Spark Connect cell-monitoring lifecycle integration.""" +import atexit import gc import io import sys @@ -128,6 +129,20 @@ def test_classify_exception_outcome(self): "FAILED", ) + class _BrokenExc(Exception): + + @property + def grpc_status_code(self): + raise RuntimeError("broken descriptor") + + def __str__(self) -> str: + raise RuntimeError("broken str") + + self.assertEqual( + _cell_monitoring.classify_exception_outcome(_BrokenExc()), + "FAILED", + ) + def test_noop_when_cell_monitoring_extension_not_loaded(self): with mock.patch.dict( sys.modules, {"managed_spark_cell_monitoring.spark_connect": None} @@ -275,6 +290,71 @@ def _fake_stream(r, *a, **kw): gc.collect() self.assertIsNone(weak_s2()) + def test_execute_unmonitored_skips_classification_and_del_closes_poller( + self, + ): + created_pollers: List[_FakePoller] = [] + fake_mod = types.ModuleType( + "managed_spark_cell_monitoring.spark_connect" + ) + + def _factory(client, **kwargs): + # Do not retain a strong reference from the test's list back to + # `client` -> hooks -> `session`, so GC can collect `session` + # without _close_client() clearing the hooks first. + p = _FakePoller(None, **kwargs) + p.is_supported = False + created_pollers.append(p) + return p + + fake_mod.create_session_poller = _factory # type: ignore[attr-defined] + + def _boom(r, *a, **kw): + raise RuntimeError("execute failed") + + def _exercise_and_drop(): + with ( + mock.patch.dict( + sys.modules, + {"managed_spark_cell_monitoring.spark_connect": fake_mod}, + ), + mock.patch( + "pyspark.sql.connect.client.core.SparkConnectClient._execute", + side_effect=_boom, + ), + mock.patch.object( + _cell_monitoring, + "classify_exception_outcome", + wraps=_cell_monitoring.classify_exception_outcome, + ) as mock_classify, + ): + s = self._create_local_session() + req = s.client._execute_plan_request_with_metadata() + with ( + mock.patch.object(s, "_display_operation_link"), + self.assertRaises(RuntimeError), + ): + s.client._execute(req, {}) + mock_classify.assert_not_called() + self.assertEqual(len(created_pollers), 1) + poller = created_pollers[0] + self.assertEqual(poller.finished, []) + + ManagedSparkSession._forget_server_session(s) + # PySpark registers client._cleanup_ml via atexit, which pins + # the client/session until _close_client() or shutdown. + cleanup_ml = getattr(s.client, "_cleanup_ml", None) + if cleanup_ml is not None: + atexit.unregister(cleanup_ml) + weak_s = weakref.ref(s) + self.assertFalse(poller.closed) + return poller, weak_s + + poller, weak_s = _exercise_and_drop() + gc.collect() + self.assertTrue(poller.closed) + self.assertIsNone(weak_s()) + def test_ipython_extras_loads_and_unloads_cellmonitor_extension(self): from IPython.core.interactiveshell import InteractiveShell from google.cloud.managed_spark_connect import _ipython From 36597f2db3ba6e275e0c4f9d01a0e4cedeb72ea4 Mon Sep 17 00:00:00 2001 From: Patrick Chen Date: Fri, 20 Nov 2026 18:51:00 +0000 Subject: [PATCH 3/7] test: mock atexit.register and client.close in GC poller test --- tests/unit/test_cell_monitoring.py | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/tests/unit/test_cell_monitoring.py b/tests/unit/test_cell_monitoring.py index 19cc82e1..6ca5939f 100644 --- a/tests/unit/test_cell_monitoring.py +++ b/tests/unit/test_cell_monitoring.py @@ -13,7 +13,6 @@ # limitations under the License. """Unit tests for thin Spark Connect cell-monitoring lifecycle integration.""" -import atexit import gc import io import sys @@ -318,6 +317,7 @@ def _exercise_and_drop(): sys.modules, {"managed_spark_cell_monitoring.spark_connect": fake_mod}, ), + mock.patch("atexit.register"), mock.patch( "pyspark.sql.connect.client.core.SparkConnectClient._execute", side_effect=_boom, @@ -341,17 +341,15 @@ def _exercise_and_drop(): self.assertEqual(poller.finished, []) ManagedSparkSession._forget_server_session(s) - # PySpark registers client._cleanup_ml via atexit, which pins - # the client/session until _close_client() or shutdown. - cleanup_ml = getattr(s.client, "_cleanup_ml", None) - if cleanup_ml is not None: - atexit.unregister(cleanup_ml) weak_s = weakref.ref(s) self.assertFalse(poller.closed) return poller, weak_s - poller, weak_s = _exercise_and_drop() - gc.collect() + with mock.patch( + "pyspark.sql.connect.client.core.SparkConnectClient.close" + ): + poller, weak_s = _exercise_and_drop() + gc.collect() self.assertTrue(poller.closed) self.assertIsNone(weak_s()) From 24bbde5506b359c3599363c201f285eb43cf3c4e Mon Sep 17 00:00:00 2001 From: Patrick Chen Date: Mon, 30 Nov 2026 18:10:49 +0000 Subject: [PATCH 4/7] fix: address cell monitoring lifecycle, exception classification, docs, and test review --- README.md | 12 +- .../managed_spark_connect/_cell_monitoring.py | 110 +-- .../cloud/managed_spark_connect/_ipython.py | 22 + .../managed_spark_connect/client/core.py | 2 + google/cloud/managed_spark_connect/session.py | 98 ++- tests/unit/test_cell_monitoring.py | 659 +++++++++++++----- 6 files changed, 652 insertions(+), 251 deletions(-) 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 index 28e8454a..95a7f5c9 100644 --- a/google/cloud/managed_spark_connect/_cell_monitoring.py +++ b/google/cloud/managed_spark_connect/_cell_monitoring.py @@ -14,52 +14,81 @@ """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|JOB_CANCELLED)\b" +) + def classify_exception_outcome(exc: BaseException) -> str: """Classifies an `ExecutePlan` exception into `CANCELLED` or `FAILED`.""" - try: - if isinstance(exc, (KeyboardInterrupt, GeneratorExit)): + 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" - - seen: set[int] = set() - cur: Optional[BaseException] = exc - while cur is not None and id(cur) not in seen: - seen.add(id(cur)) + try: code_fn = getattr(cur, "code", None) if callable(code_fn): - try: - code = code_fn() - if getattr(code, "name", None) == "CANCELLED": - return "CANCELLED" - except Exception: - pass + 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" - err_cls_fn = getattr(cur, "getErrorClass", None) - if callable(err_cls_fn): - try: - err_cls = err_cls_fn() or "" - if "CANCELED" in err_cls or "CANCELLED" in err_cls: - return "CANCELLED" - except Exception: - pass - msg = str(cur) - if "OPERATION_CANCELED" in msg or "JOB_CANCELLED" in msg: + except Exception: + pass + try: + cond_fn = getattr(cur, "getCondition", None) or getattr( + cur, "getErrorClass", None + ) + if callable(cond_fn): + cond = cond_fn() or "" + if "CANCELED" in cond or "CANCELLED" in cond: + return "CANCELLED" + except Exception: + pass + try: + if _CANCELLED_MSG_RE.search(str(cur)): return "CANCELLED" - cur = cur.__cause__ or cur.__context__ - except BaseException: - pass + 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`. @@ -80,26 +109,22 @@ def __init__( self._lock = threading.Lock() self._poller: Any = None self._closed = False - - @property - def is_supported(self) -> bool: - poller = self._poller - if poller is None: - return True - return bool(getattr(poller, "is_supported", True)) + self._factory_failed = False def _resolve_poller(self) -> Any: poller = self._poller - if poller is not None or self._closed: + if poller is not None or self._closed or self._factory_failed: return poller - mod = sys.modules.get("managed_spark_cell_monitoring.spark_connect") + 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: + if self._closed or self._factory_failed or self._client is None: return None if self._poller is None: try: @@ -109,6 +134,7 @@ def _resolve_poller(self) -> Any: on_fallback=self._on_fallback, ) except Exception: + self._factory_failed = True logger.debug( "Failed creating Spark Connect cell monitor poller", exc_info=True, @@ -117,7 +143,7 @@ def _resolve_poller(self) -> Any: return self._poller def begin_operation(self, operation_id: Optional[str]) -> bool: - if not operation_id or self._closed: + if not operation_id or self._closed or _disabled_by_ipython_extras(): return False poller = self._resolve_poller() if poller is None: @@ -144,8 +170,6 @@ def finish_operation( return try: poller.finish_operation(operation_id, outcome=outcome) - except TypeError: - poller.finish_operation(operation_id) except Exception: logger.debug( "Error in cell monitor finish_operation(%s)", @@ -168,7 +192,12 @@ def note_spark_tasks_seen(self, operation_id: Optional[str]) -> None: 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: + 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)) @@ -182,6 +211,7 @@ def close(self) -> None: 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: diff --git a/google/cloud/managed_spark_connect/_ipython.py b/google/cloud/managed_spark_connect/_ipython.py index e42fff75..752b94dd 100644 --- a/google/cloud/managed_spark_connect/_ipython.py +++ b/google/cloud/managed_spark_connect/_ipython.py @@ -452,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 f3762bb9..a0d96105 100644 --- a/google/cloud/managed_spark_connect/client/core.py +++ b/google/cloud/managed_spark_connect/client/core.py @@ -32,6 +32,8 @@ _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( diff --git a/google/cloud/managed_spark_connect/session.py b/google/cloud/managed_spark_connect/session.py index ac43d13f..94e9a1b5 100644 --- a/google/cloud/managed_spark_connect/session.py +++ b/google/cloud/managed_spark_connect/session.py @@ -2048,15 +2048,18 @@ 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_ui_url = weakref.WeakMethod(self._get_session_spark_ui_url) - weak_fallback = weakref.WeakMethod(self._on_cell_monitor_fallback) - self._cell_monitor_poller = _cell_monitoring.SessionCellMonitorBridge( + weak_self = weakref.ref(self) + self._cell_monitor_bridge = _cell_monitoring.SessionCellMonitorBridge( self.client, spark_ui_url_getter=lambda: ( - fn() if (fn := weak_ui_url()) is not None else "" + s._get_session_spark_ui_url() + if (s := weak_self()) is not None + else "" ), on_fallback=lambda op_ids: ( - fn(op_ids) if (fn := weak_fallback()) is not None else None + 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 @@ -2086,9 +2089,10 @@ def _execute_plan_request_with_metadata(*args, **kwargs): def execute_hook(inner): def _execute(req, *args, **kwargs): + bridge = self.__dict__.get("_cell_monitor_bridge") monitored = False if not self._sql_lazy_transformation(req): - monitored = self._cell_monitor_poller.begin_operation( + monitored = bridge is not None and bridge.begin_operation( req.operation_id ) if not monitored: @@ -2103,8 +2107,8 @@ def _execute(req, *args, **kwargs): ) raise finally: - if monitored: - self._cell_monitor_poller.finish_operation( + if monitored and bridge is not None: + bridge.finish_operation( req.operation_id, outcome=outcome ) @@ -2112,27 +2116,10 @@ def _execute(req, *args, **kwargs): def execute_and_fetch_as_iterator_hook(inner): def _execute_and_fetch_as_iterator(req, *args, **kwargs): - monitored = False - if not self._sql_lazy_transformation(req): - monitored = self._cell_monitor_poller.begin_operation( - req.operation_id - ) - if not monitored: - self._display_operation_link(req.operation_id) - try: - iterator = inner(req, *args, **kwargs) - except BaseException as exc: - if monitored: - self._cell_monitor_poller.finish_operation( - req.operation_id, - outcome=_cell_monitoring.classify_exception_outcome( - exc - ), - ) - raise - if not monitored: - return iterator - return self._wrap_monitored_iterator(iterator, req.operation_id) + bridge = self.__dict__.get("_cell_monitor_bridge") + if bridge is None or self._sql_lazy_transformation(req): + return inner(req, *args, **kwargs) + return self._monitored_stream(bridge, inner, req, args, kwargs) return _execute_and_fetch_as_iterator @@ -2221,11 +2208,11 @@ def handler( total_tasks += stage.num_tasks completed_tasks += stage.num_completed_tasks - poller = self.__dict__.get("_cell_monitor_poller") - if poller is not None: - if total_tasks > 0: - poller.note_spark_tasks_seen(operation_id) - if poller.should_suppress_progress_bar(operation_id): + 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" ) @@ -2381,18 +2368,28 @@ def _sql_lazy_transformation(req): except AttributeError: return False - def _wrap_monitored_iterator(self, iterator, operation_id: str): + 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.""" + if not bridge.begin_operation(req.operation_id): + self._display_operation_link(req.operation_id) + yield from inner(req, *args, **kwargs) + return outcome = "CANCELLED" try: - yield from iterator + yield from inner(req, *args, **kwargs) outcome = "SUCCEEDED" except BaseException as exc: outcome = _cell_monitoring.classify_exception_outcome(exc) raise finally: - poller = self.__dict__.get("_cell_monitor_poller") - if poller is not None: - poller.finish_operation(operation_id, outcome=outcome) + bridge.finish_operation(req.operation_id, outcome=outcome) def _get_session_spark_ui_url(self) -> str: if ( @@ -2408,6 +2405,11 @@ def _get_session_spark_ui_url(self) -> str: 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) @@ -2420,16 +2422,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): @@ -2615,9 +2614,6 @@ def __del__(self) -> None: # stop() the GC may run that on any thread, including a # ReleaseExecute pool worker, where shutting the shared release pool # down fails half-way and leaves it unusable for the whole process. - poller = self.__dict__.get("_cell_monitor_poller") - if poller is not None: - poller.close() if self.__dict__.get("_client_closed"): return super().__del__() @@ -2641,9 +2637,9 @@ def _close_client(self) -> None: logger.debug( "Failed to close the StreamingQueryManager", exc_info=True ) - poller = self.__dict__.get("_cell_monitor_poller") - if poller is not None: - poller.close() + 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 index 6ca5939f..ec789c06 100644 --- a/tests/unit/test_cell_monitoring.py +++ b/tests/unit/test_cell_monitoring.py @@ -20,15 +20,16 @@ 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.core import ( - _UNGUARDED_METHOD_SUFFIXES, -) +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 @@ -46,6 +47,46 @@ 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__( @@ -93,12 +134,38 @@ def close(self) -> None: class TestCellMonitoringBridgeUnit(unittest.TestCase): - def test_get_status_is_unguarded_method_suffix(self): - self.assertTrue( - "/spark.connect.SparkConnectService/GetStatus".endswith( - _UNGUARDED_METHOD_SUFFIXES - ) + 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( @@ -116,11 +183,47 @@ def test_classify_exception_outcome(self): "CANCELLED", ) - wrapped = RuntimeError("SparkConnectGrpcException(OPERATION_CANCELED)") + 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( - _cell_monitoring.classify_exception_outcome(wrapped), + [w for w in caught if issubclass(w.category, FutureWarning)], + [], + ) + + self.assertEqual( + _cell_monitoring.classify_exception_outcome( + RuntimeError("SparkConnectGrpcException(OPERATION_CANCELED)") + ), + "CANCELLED", + ) + self.assertEqual( + _cell_monitoring.classify_exception_outcome( + RuntimeError("[JOB_CANCELLED] stopped") + ), "CANCELLED", ) + # Echoed user SQL literals must not false-positive as cancellation. + self.assertEqual( + _cell_monitoring.classify_exception_outcome( + ValueError("ParseException: SELECT 'OPERATION_CANCELED'") + ), + "FAILED", + ) self.assertEqual( _cell_monitoring.classify_exception_outcome( ValueError("Division by zero") @@ -128,23 +231,63 @@ def test_classify_exception_outcome(self): "FAILED", ) - class _BrokenExc(Exception): + class _BrokenGrpcStatusExc(Exception): @property def grpc_status_code(self): - raise RuntimeError("broken descriptor") + 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(_BrokenExc()), + _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, {"managed_spark_cell_monitoring.spark_connect": None} + sys.modules, {_cell_monitoring._CELL_MONITOR_EXTENSION: None} ): bridge = _cell_monitoring.SessionCellMonitorBridge(mock.MagicMock()) self.assertFalse(bridge.begin_operation("op-1")) @@ -153,6 +296,53 @@ def test_noop_when_cell_monitoring_extension_not_loaded(self): 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): @@ -164,11 +354,25 @@ def _create_local_session(self) -> ManagedSparkSession: 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( - "managed_spark_cell_monitoring.spark_connect" - ) + fake_mod = types.ModuleType(_cell_monitoring._CELL_MONITOR_EXTENSION) def _factory(client, **kwargs): p = _FakePoller(client, **kwargs) @@ -179,12 +383,8 @@ def _factory(client, **kwargs): with mock.patch.dict( sys.modules, - {"managed_spark_cell_monitoring.spark_connect": fake_mod}, + {_cell_monitoring._CELL_MONITOR_EXTENSION: fake_mod}, ): - ManagedSparkSession._project_id = "proj-1" - ManagedSparkSession._region = "us-central1" - ManagedSparkSession._active_s8s_session_id = "sc-sess-1" - bars_opened: List[Any] = [] ManagedSparkSession._set_tqdm_factory( lambda **kw: bars_opened.append(kw) @@ -201,7 +401,7 @@ def _fake_stream(r, *a, **kw): 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_poller.should_suppress_progress_bar( + s._cell_monitor_bridge.should_suppress_progress_bar( r.operation_id ) ) @@ -212,163 +412,298 @@ def _fake_stream(r, *a, **kw): raise KeyboardInterrupt() yield "batch-2" - with mock.patch.dict( - "os.environ", - {"MANAGED_SPARK_CONNECT_FORCE_PROGRESS_BAR": "1"}, - ): - with mock.patch( + 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, []) - self.assertEqual( - poller.spark_ui_url_getter(), - "https://console.cloud.google.com/dataproc/interactive/us-central1/sc-sess-1/sparkApplications/applications?project=proj-1", - ) - 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_execute_unmonitored_skips_classification_and_del_closes_poller( - self, - ): + ), + ): + 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( - "managed_spark_cell_monitoring.spark_connect" + 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] ) - def _factory(client, **kwargs): - # Do not retain a strong reference from the test's list back to - # `client` -> hooks -> `session`, so GC can collect `session` - # without _close_client() clearing the hooks first. - p = _FakePoller(None, **kwargs) - p.is_supported = False - created_pollers.append(p) - return p + modes_by_op: dict[str, str] = {} - fake_mod.create_session_poller = _factory # type: ignore[attr-defined] + 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") + return "exec-ok" - def _boom(r, *a, **kw): - raise RuntimeError("execute failed") + 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, {}) - def _exercise_and_drop(): - with ( - mock.patch.dict( - sys.modules, - {"managed_spark_cell_monitoring.spark_connect": fake_mod}, - ), - mock.patch("atexit.register"), - mock.patch( - "pyspark.sql.connect.client.core.SparkConnectClient._execute", - side_effect=_boom, - ), - mock.patch.object( - _cell_monitoring, - "classify_exception_outcome", - wraps=_cell_monitoring.classify_exception_outcome, - ) as mock_classify, - ): - s = self._create_local_session() - req = s.client._execute_plan_request_with_metadata() - with ( - mock.patch.object(s, "_display_operation_link"), - self.assertRaises(RuntimeError), - ): - s.client._execute(req, {}) - mock_classify.assert_not_called() - self.assertEqual(len(created_pollers), 1) poller = created_pollers[0] - self.assertEqual(poller.finished, []) + 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 SELECT SQL skips begin_operation/finish_operation + 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) + + # 3. Unmonitored _execute(): skips classification and displays 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) - ManagedSparkSession._forget_server_session(s) - weak_s = weakref.ref(s) - self.assertFalse(poller.closed) - return poller, weak_s + 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] = [] - with mock.patch( - "pyspark.sql.connect.client.core.SparkConnectClient.close" + def _fake_stream(req, *a, **kw): + try: + yield "row-1" + yield "row-2" + finally: + inner_closed.append(req.operation_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, + ), ): - poller, weak_s = _exercise_and_drop() - gc.collect() - self.assertTrue(poller.closed) - self.assertIsNone(weak_s()) + 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 SELECT SQL iterator skips monitoring too + req_lazy = s.client._execute_plan_request_with_metadata() + req_lazy.plan.command.sql_command.input.sql.query = "SELECT 1" + self.assertEqual( + list(s.client._execute_and_fetch_as_iterator(req_lazy, {})), + ["row-1", "row-2"], + ) + self.assertEqual(created_pollers, []) + + # 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") + poller = created_pollers[0] + self.assertIn(req_mid.operation_id, poller.active_ops) + it_mid.close() + self.assertIn(req_mid.operation_id, inner_closed) + self.assertEqual( + poller.finished, [(req_mid.operation_id, "CANCELLED")] + ) + self.assertEqual(poller.active_ops, set()) + + 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.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) 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( - "managed_spark_cell_monitoring.spark_connect" - ) + 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__ = ( - "managed_spark_cell_monitoring.spark_connect" - ) + cellmonitor.__module__ = _cell_monitoring._CELL_MONITOR_EXTENSION ip.register_magic_function( cellmonitor, magic_kind="line", magic_name="cellmonitor" ) @@ -378,6 +713,9 @@ def _unload_ext(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) @@ -398,7 +736,7 @@ def _unload_ext(ip): "managed_spark_cell_monitoring": types.ModuleType( "managed_spark_cell_monitoring" ), - "managed_spark_cell_monitoring.spark_connect": fake_ext, + _cell_monitoring._CELL_MONITOR_EXTENSION: fake_ext, "google.colabsqlviz": None, "google.cloud.managed_spark_magics": None, }, @@ -414,6 +752,11 @@ def _unload_ext(ip): 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() From 30adde10d4f6457b1f1d994f193bfaf43f6a991a Mon Sep 17 00:00:00 2001 From: Patrick Chen Date: Mon, 30 Nov 2026 21:57:17 +0000 Subject: [PATCH 5/7] fix: begin cell monitor on DML/CTAS SQL and match cancellation case-insensitively --- .../managed_spark_connect/_cell_monitoring.py | 11 +- google/cloud/managed_spark_connect/session.py | 19 +- tests/unit/test_cell_monitoring.py | 164 ++++++++++++++++-- 3 files changed, 170 insertions(+), 24 deletions(-) diff --git a/google/cloud/managed_spark_connect/_cell_monitoring.py b/google/cloud/managed_spark_connect/_cell_monitoring.py index 95a7f5c9..ad5ebe7d 100644 --- a/google/cloud/managed_spark_connect/_cell_monitoring.py +++ b/google/cloud/managed_spark_connect/_cell_monitoring.py @@ -25,7 +25,8 @@ # 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|JOB_CANCELLED)\b" + r"(?:\[|\(|:\s+|^)(?:OPERATION_CANCELED|SPARK_JOB_CANCELLED|JOB_CANCELLED)\b", + re.IGNORECASE, ) @@ -56,9 +57,11 @@ def classify_exception_outcome(exc: BaseException) -> str: cur, "getErrorClass", None ) if callable(cond_fn): - cond = cond_fn() or "" - if "CANCELED" in cond or "CANCELLED" in cond: - return "CANCELLED" + 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: diff --git a/google/cloud/managed_spark_connect/session.py b/google/cloud/managed_spark_connect/session.py index 94e9a1b5..589ddb1c 100644 --- a/google/cloud/managed_spark_connect/session.py +++ b/google/cloud/managed_spark_connect/session.py @@ -2090,13 +2090,11 @@ def _execute_plan_request_with_metadata(*args, **kwargs): def execute_hook(inner): def _execute(req, *args, **kwargs): bridge = self.__dict__.get("_cell_monitor_bridge") - monitored = False - if not self._sql_lazy_transformation(req): - monitored = bridge is not None and bridge.begin_operation( - req.operation_id - ) - if not monitored: - self._display_operation_link(req.operation_id) + monitored = bridge is not None and bridge.begin_operation( + req.operation_id + ) + if not monitored and not self._sql_lazy_transformation(req): + self._display_operation_link(req.operation_id) outcome = "SUCCEEDED" try: return inner(req, *args, **kwargs) @@ -2117,7 +2115,9 @@ def _execute(req, *args, **kwargs): def execute_and_fetch_as_iterator_hook(inner): def _execute_and_fetch_as_iterator(req, *args, **kwargs): bridge = self.__dict__.get("_cell_monitor_bridge") - if bridge is None or self._sql_lazy_transformation(req): + if bridge is None: + if not self._sql_lazy_transformation(req): + self._display_operation_link(req.operation_id) return inner(req, *args, **kwargs) return self._monitored_stream(bridge, inner, req, args, kwargs) @@ -2378,7 +2378,8 @@ def _monitored_stream( ): """Starts monitoring lazily on first iteration so unconsumed generators never leak.""" if not bridge.begin_operation(req.operation_id): - self._display_operation_link(req.operation_id) + if not self._sql_lazy_transformation(req): + self._display_operation_link(req.operation_id) yield from inner(req, *args, **kwargs) return outcome = "CANCELLED" diff --git a/tests/unit/test_cell_monitoring.py b/tests/unit/test_cell_monitoring.py index ec789c06..5b94c845 100644 --- a/tests/unit/test_cell_monitoring.py +++ b/tests/unit/test_cell_monitoring.py @@ -205,25 +205,69 @@ class _GrpcStatusExc(Exception): [], ) + 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", ) - # Echoed user SQL literals must not false-positive as cancellation. self.assertEqual( _cell_monitoring.classify_exception_outcome( - ValueError("ParseException: SELECT 'OPERATION_CANCELED'") + RuntimeError("[spark_job_cancelled] Job 0 cancelled") ), - "FAILED", + "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") @@ -558,15 +602,25 @@ def _exec_behavior(req, *a, **kw): ) mock_link.assert_not_called() - # 2. Lazy SELECT SQL skips begin_operation/finish_operation + # 2. Monitored SQL SELECT and DML both report begin/finish 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 dst SELECT * FROM src" + ) + for sql_req in (lazy_req, dml_req): + self.assertEqual(s.client._execute(sql_req, {}), "exec-ok") + self.assertIn(sql_req.operation_id, poller.begun) + self.assertEqual( + poller.finished[-1], + (sql_req.operation_id, "SUCCEEDED"), + ) + mock_link.assert_not_called() - # 3. Unmonitored _execute(): skips classification and displays link + # 3. Unmonitored _execute(): skips classification; gates link mock_classify.reset_mock() poller.is_supported = False req_unmon = s.client._execute_plan_request_with_metadata() @@ -576,6 +630,22 @@ def _exec_behavior(req, *a, **kw): 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] = [] @@ -613,28 +683,100 @@ def _fake_stream(req, *a, **kw): self.assertEqual(created_pollers, []) self.assertEqual(inner_closed, []) - # 2. Lazy SELECT SQL iterator skips monitoring too + # 2. Monitored SQL iterator runs monitoring; unmonitored gates link req_lazy = s.client._execute_plan_request_with_metadata() req_lazy.plan.command.sql_command.input.sql.query = "SELECT 1" self.assertEqual( list(s.client._execute_and_fetch_as_iterator(req_lazy, {})), ["row-1", "row-2"], ) - self.assertEqual(created_pollers, []) + poller = created_pollers[0] + self.assertEqual(poller.begun, [req_lazy.operation_id]) + self.assertEqual( + poller.finished, [(req_lazy.operation_id, "SUCCEEDED")] + ) + + 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") - poller = created_pollers[0] self.assertIn(req_mid.operation_id, poller.active_ops) it_mid.close() self.assertIn(req_mid.operation_id, inner_closed) self.assertEqual( - poller.finished, [(req_mid.operation_id, "CANCELLED")] + 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] = [] From 097f08ef3a5ac93e85886819eea655cfabaee455 Mon Sep 17 00:00:00 2001 From: Patrick Chen Date: Mon, 30 Nov 2026 22:14:19 +0000 Subject: [PATCH 6/7] test: close resumed progress bar in cell monitoring test --- tests/unit/test_cell_monitoring.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/unit/test_cell_monitoring.py b/tests/unit/test_cell_monitoring.py index 5b94c845..827e0a59 100644 --- a/tests/unit/test_cell_monitoring.py +++ b/tests/unit/test_cell_monitoring.py @@ -807,6 +807,7 @@ def _make_bar(**kw): ): 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] @@ -832,6 +833,8 @@ def _make_bar(**kw): 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 786cf6b2dd070eedf4c1c486b20f3dc1feb675d6 Mon Sep 17 00:00:00 2001 From: Patrick Chen Date: Tue, 1 Dec 2026 01:04:19 +0000 Subject: [PATCH 7/7] fix: skip cell monitoring on lazy SQL and preserve operation_id pairing --- google/cloud/managed_spark_connect/session.py | 34 ++++++---- tests/unit/test_cell_monitoring.py | 64 ++++++++++++++----- 2 files changed, 68 insertions(+), 30 deletions(-) diff --git a/google/cloud/managed_spark_connect/session.py b/google/cloud/managed_spark_connect/session.py index 589ddb1c..9d572ba5 100644 --- a/google/cloud/managed_spark_connect/session.py +++ b/google/cloud/managed_spark_connect/session.py @@ -2089,12 +2089,16 @@ def _execute_plan_request_with_metadata(*args, **kwargs): def execute_hook(inner): def _execute(req, *args, **kwargs): + operation_id = req.operation_id + is_lazy_sql = self._sql_lazy_transformation(req) bridge = self.__dict__.get("_cell_monitor_bridge") - monitored = bridge is not None and bridge.begin_operation( - req.operation_id + monitored = ( + not is_lazy_sql + and bridge is not None + and bridge.begin_operation(operation_id) ) - if not monitored and not self._sql_lazy_transformation(req): - self._display_operation_link(req.operation_id) + if not monitored and not is_lazy_sql: + self._display_operation_link(operation_id) outcome = "SUCCEEDED" try: return inner(req, *args, **kwargs) @@ -2106,18 +2110,18 @@ def _execute(req, *args, **kwargs): raise finally: if monitored and bridge is not None: - bridge.finish_operation( - req.operation_id, outcome=outcome - ) + 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): + operation_id = req.operation_id + is_lazy_sql = self._sql_lazy_transformation(req) bridge = self.__dict__.get("_cell_monitor_bridge") - if bridge is None: - if not self._sql_lazy_transformation(req): - self._display_operation_link(req.operation_id) + 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) @@ -2377,9 +2381,11 @@ def _monitored_stream( kwargs: Any, ): """Starts monitoring lazily on first iteration so unconsumed generators never leak.""" - if not bridge.begin_operation(req.operation_id): - if not self._sql_lazy_transformation(req): - self._display_operation_link(req.operation_id) + 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" @@ -2390,7 +2396,7 @@ def _monitored_stream( outcome = _cell_monitoring.classify_exception_outcome(exc) raise finally: - bridge.finish_operation(req.operation_id, outcome=outcome) + bridge.finish_operation(operation_id, outcome=outcome) def _get_session_spark_ui_url(self) -> str: if ( diff --git a/tests/unit/test_cell_monitoring.py b/tests/unit/test_cell_monitoring.py index 827e0a59..e8054b77 100644 --- a/tests/unit/test_cell_monitoring.py +++ b/tests/unit/test_cell_monitoring.py @@ -555,6 +555,8 @@ def _exec_behavior(req, *a, **kw): 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 ( @@ -602,22 +604,34 @@ def _exec_behavior(req, *a, **kw): ) mock_link.assert_not_called() - # 2. Monitored SQL SELECT and DML both report begin/finish + # 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 dst SELECT * FROM src" + "INSERT INTO test_table_2 VALUES (1)" ) - for sql_req in (lazy_req, dml_req): - self.assertEqual(s.client._execute(sql_req, {}), "exec-ok") - self.assertIn(sql_req.operation_id, poller.begun) - self.assertEqual( - poller.finished[-1], - (sql_req.operation_id, "SUCCEEDED"), - ) + 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 @@ -656,12 +670,17 @@ def test_iterator_closed_before_next_and_closed_mid_stream(self): ) 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(req.operation_id) + inner_closed.append(op_id) with ( mock.patch.dict( @@ -683,18 +702,31 @@ def _fake_stream(req, *a, **kw): self.assertEqual(created_pollers, []) self.assertEqual(inner_closed, []) - # 2. Monitored SQL iterator runs monitoring; unmonitored gates link + # 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_lazy, {})), + list(s.client._execute_and_fetch_as_iterator(req_dml, {})), ["row-1", "row-2"], ) poller = created_pollers[0] - self.assertEqual(poller.begun, [req_lazy.operation_id]) - self.assertEqual( - poller.finished, [(req_lazy.operation_id, "SUCCEEDED")] - ) + 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