Repository navigation
Conversation
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.
There was a problem hiding this comment.
Code Review
This pull request introduces a thin lifecycle bridge (SessionCellMonitorBridge) to integrate with managed_spark_cell_monitoring.spark_connect for cell monitoring in Managed Spark Connect sessions. Key changes include tracking operation outcomes, suppressing progress bars, and handling fallbacks. The review feedback highlights three main improvement opportunities: wrapping the exception classification logic in classify_exception_outcome to prevent secondary exceptions from masking the original error, avoiding exception classification in _execute when the operation is not monitored, and ensuring the poller is closed during garbage collection while using getattr instead of direct __dict__ access.
dborowitz
left a comment
There was a problem hiding this comment.
This PR just sets it up when installed; we're going to need to add it as a dep with [client] too. That is blocked on an upstream version release, but it should be safe to submit this in the meantime.
dborowitz
left a comment
There was a problem hiding this comment.
Please address remaining gemini comments.
dborowitz
left a comment
There was a problem hiding this comment.
[Dave's review agent] Review of e6a9f7c / 5f078ee / 36597f2 (verified locally on 36597f2: 789 unit tests pass, pyink --check passes).
Summary of main items (details in inline comments):
- Blocking / high priority: unguarded
TypeErrorfallback inSessionCellMonitorBridge.finish_operationcan escape intofinally:and mask user exceptions or fail succeeded queries. - Should-fix:
getErrorClass()emitsFutureWarningon PySpark 4.x;classify_exception_outcomeouterexcept BaseExceptionswallows interrupts and aborts cause-chain traversal on a broken property;note_spark_tasks_seenfires onProgress.finish()(done=True) afterfinish_operation; lazy iterators can leak active ops if never iterated;__del__poller cleanup reachability/weak-client contract and teardown safety; test global-state cleanup and missing coverage;README.mddocs for auto-loaded%cellmonitor. - History / non-blocking notes:
- Consider squashing
36597f2into5f078eeso the history doesn't carry a PySpark-4.0-only GC test commit. - Worth double-checking whether
begin_operationshould respectshowOperationLinks(False)/showProgressBar(False)/ non-interactive mode, whetherstr(exc)substring matching forOPERATION_CANCELED/JOB_CANCELLEDcould false-positive on echoed error text, and how the monitor handles position-lost replay (seeingop1FAILEDfollowed byop2begin_operationfor one user query).
- Consider squashing
| 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, | ||
| ) |
There was a problem hiding this comment.
[Dave's review agent] Blocking / should-fix: The except TypeError: fallback poller.finish_operation(operation_id) is unguarded. Any TypeError raised inside a poller triggers a second finish_operation call, and if that retry raises, it escapes into finally: in _execute (session.py:2107) or _wrap_monitored_iterator (session.py:2395), failing a succeeded query or masking the user's real Spark exception. Every other bridge method swallows Exception.
Either drop the legacy 1-arg path (since both packages are developed together), or nest the fallback inside the outer try/except Exception:
try:
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,
)| try: | ||
| 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__ | ||
| except BaseException: | ||
| pass |
There was a problem hiding this comment.
[Dave's review agent] Should-fix: Two issues in classify_exception_outcome:
getErrorClass()emits aFutureWarningon PySpark 4.x (Deprecated in 4.0.0, use getCondition instead.), so every failed monitored query will emit a deprecation warning into the user's cell. PrefergetConditionbeforegetErrorClass, matchingclient/reattach_patch.py:61-65.- Single outer
except BaseException: pass:- Swallows
KeyboardInterrupt/SystemExitarriving mid-classification. - A raising property on an outer exception (e.g.
grpc_status_code) aborts the wholewhileloop, skippinggetCondition/__str__and skipping__cause__/__context__traversal (so a broken outer wrapper around aCANCELLEDcause is misclassified as"FAILED"). Intest_cell_monitoring.py,_BrokenExc.__str__is never even reached becausegrpc_status_coderaises first. isinstance(cur, (KeyboardInterrupt, GeneratorExit))is only checked on the outermostexc, not inside the cause chain.
- Swallows
Suggested refactor isolating each probe with except Exception::
def classify_exception_outcome(exc: BaseException) -> str:
"""Classifies an `ExecutePlan` exception into `CANCELLED` or `FAILED`."""
seen: set[int] = set()
cur: Optional[BaseException] = exc
while cur is not None and id(cur) not in seen:
seen.add(id(cur))
if isinstance(cur, (KeyboardInterrupt, GeneratorExit)):
return "CANCELLED"
try:
code_fn = getattr(cur, "code", None)
if callable(code_fn) and getattr(code_fn(), "name", None) == "CANCELLED":
return "CANCELLED"
except Exception:
pass
try:
grpc_code = getattr(cur, "grpc_status_code", None)
if getattr(grpc_code, "name", None) == "CANCELLED":
return "CANCELLED"
except Exception:
pass
try:
cond_fn = getattr(cur, "getCondition", None) or getattr(
cur, "getErrorClass", None
)
if callable(cond_fn):
cond = cond_fn() or ""
if "CANCELED" in cond or "CANCELLED" in cond:
return "CANCELLED"
except Exception:
pass
try:
msg = str(cur)
if "OPERATION_CANCELED" in msg or "JOB_CANCELLED" in msg:
return "CANCELLED"
except Exception:
pass
cur = getattr(cur, "__cause__", None) or getattr(cur, "__context__", None)
return "FAILED"| 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 |
There was a problem hiding this comment.
[Dave's review agent] Nit: If create_session_poller raises, _resolve_poller() logs at debug and returns None without latching the failure, so every subsequent begin_operation() retries the factory (potentially half-starting background threads repeatedly). Consider setting self._closed = True or a dedicated _factory_failed = True flag in the except Exception: block.
| @property | ||
| def is_supported(self) -> bool: | ||
| poller = self._poller | ||
| if poller is None: | ||
| return True | ||
| return bool(getattr(poller, "is_supported", True)) |
There was a problem hiding this comment.
[Dave's review agent] Nit: is_supported is unused and returns True even when no poller is loaded or after close(). Consider removing it. Also in close() (lines 178-186), clearing self._client = None alongside _poller, _spark_ui_url_getter, and _on_fallback is cleaner hygiene.
| 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) |
There was a problem hiding this comment.
[Dave's review agent] Should-fix: begin_operation runs eagerly here, while finish_operation lives inside _wrap_monitored_iterator's finally: block. Because PySpark's SparkConnectClient._execute_and_fetch_as_iterator is a generator function, the try/except around inner(...) doesn't catch RPC errors, and if a caller drops or .close()s the returned generator before calling next(), _wrap_monitored_iterator's finally: never runs—leaving the operation active (and progress bars suppressed) until session close.
Either put begin_operation, _display_operation_link, and finish_operation inside a single generator:
def _monitored_stream(self, inner, req, args, kwargs):
if not self._cell_monitor_poller.begin_operation(req.operation_id):
self._display_operation_link(req.operation_id)
yield from inner(req, *args, **kwargs)
return
outcome = "CANCELLED"
try:
yield from inner(req, *args, **kwargs)
outcome = "SUCCEEDED"
except BaseException as exc:
outcome = _cell_monitoring.classify_exception_outcome(exc)
raise
finally:
self._cell_monitor_poller.finish_operation(
req.operation_id, outcome=outcome
)Or wrap the iterator in a small _MonitoredIterator class whose close() and __del__ call finish_operation once if eager begin_operation is needed.
| poller = self.__dict__.get("_cell_monitor_poller") | ||
| if poller is not None: | ||
| poller.close() |
There was a problem hiding this comment.
[Dave's review agent] Should-fix: A couple of concerns with closing the poller in __del__:
- Reachability & client reference contract: PySpark pins every
SparkConnectClientvia anatexithook until_close_client()unregisters it (and_close_client()already closes the bridge). Moreover,SessionCellMonitorBridgepassesself.clientstrongly tocreate_session_poller(...), andclientholds hooks closing overself—so any real poller holdingclientfrom a live thread pinsselffrom GC anyway (which is why the unit test had to passNoneto_FakePollerand patchatexit.register). Either drop this__del__hunk + test, or document/enforce a weak-client (weakref.proxy(self.client)) and non-blockingclose()contract (since__del__runs on an arbitrary GC thread). - Teardown safety & comment placement: If kept, move this above the existing
_client_closedcomment (it currently splits that comment fromif self.__dict__.get("_client_closed"):), and guardpoller.close()so interpreter-teardown errors (e.g.loggerbeingNonein_cell_monitoring.py) cannot abort__del__beforesuper().__del__()runs:
def __del__(self) -> None:
bridge = self.__dict__.get("_cell_monitor_poller")
if bridge is not None:
try:
bridge.close()
except Exception:
pass
# pyspark's SparkSession.__del__ closes the client again. ...
if self.__dict__.get("_client_closed"):
return
super().__del__()| 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) |
There was a problem hiding this comment.
[Dave's review agent] Nit:
_on_cell_monitor_fallbackcalls_display_operation_link->IPython.display.display(HTML(...))directly. Ifon_fallbackis invoked from a background poller thread,display()may render into whichever cell happens to be active (or miss the originating cell'sContextVar). Worth documenting or marshaling through the cell's output context._get_session_spark_ui_url()duplicates the Spark UI URL constructed in_repr_html_()right below it—_repr_html_()can call_get_session_spark_ui_url().- Naming/consistency:
self._cell_monitor_pollerholds aSessionCellMonitorBridge(not a poller) and could be named_cell_monitor_bridge; the twoWeakMethodlambdas in__init__could share oneweakref.ref(self); and hooks accessself._cell_monitor_pollerdirectly while the handler/iterator useself.__dict__.get(...).
| ( | ||
| "managed_spark_cell_monitoring.spark_connect", | ||
| (("line", "cellmonitor"),), | ||
| ), |
There was a problem hiding this comment.
[Dave's review agent] Should-fix (docs) / nit:
- Auto-loading
%cellmonitorwhenmanaged-spark-cell-monitoringis installed (and suppressing operation links / tqdm bars) is user-visible behavior not yet documented inREADME.md("Install" / "Interactive Extras" still list onlyexplore_dataframe(),%dpip, and%%sparksql). Please document%cellmonitor, its opt-out, and thatmanaged-spark-cell-monitoringis not pulled in by[interactive]. - Note also that setting
%config ManagedSparkConnect.enable_extras = Falseunloads the extension/magic but leavesmanaged_spark_cell_monitoring.spark_connectinsys.modules, soSessionCellMonitorBridge._resolve_poller()will still resolvecreate_session_pollerunlessunload_ipython_extensiondisables monitoring internally.
| _UNGUARDED_METHOD_SUFFIXES = ( | ||
| "/ReleaseExecute", | ||
| "/ReleaseSession", | ||
| "/GetStatus", | ||
| ) |
There was a problem hiding this comment.
[Dave's review agent] Nit: Worth a short comment explaining why /GetStatus skips the liveness guard (so background cell-monitoring polls run concurrently without triggering liveness checks while ExecutePlan is active), plus a behavioral test asserting ProxiedChannel returns the /GetStatus callable unguarded rather than only checking _UNGUARDED_METHOD_SUFFIXES membership.
| ManagedSparkSession._project_id = "proj-1" | ||
| ManagedSparkSession._region = "us-central1" | ||
| ManagedSparkSession._active_s8s_session_id = "sc-sess-1" |
There was a problem hiding this comment.
[Dave's review agent] Should-fix (test hygiene & coverage):
- Mutating class-level
ManagedSparkSession._project_id,_region, and_active_s8s_session_iddirectly withoutmock.patch.object/addCleanupleaks global state to subsequent tests if any assertion fails before line 284 (same for_forget_server_session(s)at line 343). Also note_forget_server_session()calls_remove_stopped_session_from_file(), which truncates$MANAGED_SPARK_CONNECT_ACTIVE_SESSION_FILE_PATHif a developer has that env var set. - Useful missing test cases to add:
- Monitored
client._execute()(SUCCEEDED, FAILED, CANCELLED, and link suppression — currently only the unmonitored path is tested). classify_exception_outcomewith a realPySparkException/getCondition()(asserting noFutureWarning),grpc_status_code, chained__cause__/__context__(including a broken outer exception wrapping aCANCELLEDcause), and separate broken-property vs broken-__str__tests._sql_lazy_transformation(req)skippingbegin_operation/finish_operation.- Iterator closed mid-stream (
it.close()->CANCELLED) and an iterator dropped/closed before its firstnext(). SessionCellMonitorBridgeerror-handling paths (finish_operationTypeError/exception, raising factory, post-close()begin_operation).- Progress handler closing an open tqdm bar on suppression, ignoring
done=Truefornote_spark_tasks_seen, and resuming bars once suppression flips toFalse. - Behavioral
ProxiedChanneltest verifying/GetStatusbypassesis_active_callback.
- Monitored
Summary
Integrates
ManagedSparkSessionand interactive IPython extras withmanaged-spark-cell-monitoring's Spark ConnectGetStatuspoller via a thin lifecycle bridge:_ipython.py): Auto-loadsmanaged_spark_cell_monitoring.spark_connect(%cellmonitor) when installed in IPython notebooks, respectingMANAGED_SPARK_CONNECT_ENABLE_EXTRASand%config ManagedSparkConnect.enable_extras.client/core.py): Adds"/GetStatus"to_UNGUARDED_METHOD_SUFFIXESso backgroundGetStatusRPCs can poll concurrently while anExecutePlanstream is active on the channel._cell_monitoring.py,session.py):managed_spark_cell_monitoring.spark_connect.create_session_poller(...)with zero overhead or extra imports whenmanaged-spark-cell-monitoringis not installed or inactive._executeand_execute_and_fetch_as_iteratoracross full stream lifetimes, classifying completion outcomes (SUCCEEDED,FAILED,CANCELLED) forfinish_operation(...).tqdmprogress bars while cell monitoring is active for an operation, restoring them automatically via session fallback if the server does not serveCellMonitorTelemetry.Companion PRs in
GoogleCloudDataproc/managed-spark-cell-monitoring:GetStatus+cell_monitor.protostubs)GetStatuspoller & AnyWidget snapshot mode, stacked on fix: unit test expected error message #54)Testing
pyink . --checkvermin --no-tips --violations --eval-annotations --target=3.10- google tests setup.pypytest tests/unit/test_cell_monitoring.py tests/unit/test_init.pyand full unit test suitepython -m build --no-isolation&twine check --strict dist/*