Skip to content

feat: integrate ManagedSparkSession with Spark Connect cell monitoring - #237

Open
ptch314 wants to merge 3 commits into
mainfrom
feat/spark-connect-cell-monitoring
Open

ptch314 wants to merge 3 commits into
mainfrom
feat/spark-connect-cell-monitoring

Conversation

@ptch314

@ptch314 ptch314 commented Nov 16, 2026

Copy link
Copy Markdown
Collaborator

Summary

Integrates ManagedSparkSession and interactive IPython extras with managed-spark-cell-monitoring's Spark Connect GetStatus poller via a thin lifecycle bridge:

  • Interactive Extras (_ipython.py): Auto-loads managed_spark_cell_monitoring.spark_connect (%cellmonitor) when installed in IPython notebooks, respecting MANAGED_SPARK_CONNECT_ENABLE_EXTRAS and %config ManagedSparkConnect.enable_extras.
  • Client Concurrency (client/core.py): Adds "/GetStatus" to _UNGUARDED_METHOD_SUFFIXES so background GetStatus RPCs can poll concurrently while an ExecutePlan stream is active on the channel.
  • Thin Session Lifecycle Bridge (_cell_monitoring.py, session.py):
    • Lazily resolves managed_spark_cell_monitoring.spark_connect.create_session_poller(...) with zero overhead or extra imports when managed-spark-cell-monitoring is not installed or inactive.
    • Wraps _execute and _execute_and_fetch_as_iterator across full stream lifetimes, classifying completion outcomes (SUCCEEDED, FAILED, CANCELLED) for finish_operation(...).
    • Suppresses duplicate per-operation links and tqdm progress bars while cell monitoring is active for an operation, restoring them automatically via session fallback if the server does not serve CellMonitorTelemetry.

Companion PRs in GoogleCloudDataproc/managed-spark-cell-monitoring:

Testing

  • pyink . --check
  • vermin --no-tips --violations --eval-annotations --target=3.10- google tests setup.py
  • pytest tests/unit/test_cell_monitoring.py tests/unit/test_init.py and full unit test suite
  • python -m build --no-isolation & twine check --strict dist/*

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.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 dborowitz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 dborowitz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please address remaining gemini comments.

@dborowitz dborowitz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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 TypeError fallback in SessionCellMonitorBridge.finish_operation can escape into finally: and mask user exceptions or fail succeeded queries.
  • Should-fix: getErrorClass() emits FutureWarning on PySpark 4.x; classify_exception_outcome outer except BaseException swallows interrupts and aborts cause-chain traversal on a broken property; note_spark_tasks_seen fires on Progress.finish() (done=True) after finish_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.md docs for auto-loaded %cellmonitor.
  • History / non-blocking notes:
    • Consider squashing 36597f2 into 5f078ee so the history doesn't carry a PySpark-4.0-only GC test commit.
    • Worth double-checking whether begin_operation should respect showOperationLinks(False) / showProgressBar(False) / non-interactive mode, whether str(exc) substring matching for OPERATION_CANCELED/JOB_CANCELLED could false-positive on echoed error text, and how the monitor handles position-lost replay (seeing op1 FAILED followed by op2 begin_operation for one user query).

Comment on lines +145 to +154
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,
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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,
            )

Comment on lines +26 to +58
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Dave's review agent] Should-fix: Two issues in classify_exception_outcome:

  1. getErrorClass() emits a FutureWarning on 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. Prefer getCondition before getErrorClass, matching client/reattach_patch.py:61-65.
  2. Single outer except BaseException: pass:
    • Swallows KeyboardInterrupt/SystemExit arriving mid-classification.
    • A raising property on an outer exception (e.g. grpc_status_code) aborts the whole while loop, skipping getCondition/__str__ and skipping __cause__/__context__ traversal (so a broken outer wrapper around a CANCELLED cause is misclassified as "FAILED"). In test_cell_monitoring.py, _BrokenExc.__str__ is never even reached because grpc_status_code raises first.
    • isinstance(cur, (KeyboardInterrupt, GeneratorExit)) is only checked on the outermost exc, not inside the cause chain.

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"

Comment on lines +105 to +116
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment on lines +84 to +89
@property
def is_supported(self) -> bool:
poller = self._poller
if poller is None:
return True
return bool(getattr(poller, "is_supported", True))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment on lines +2115 to +2135
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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment on lines +2618 to +2620
poller = self.__dict__.get("_cell_monitor_poller")
if poller is not None:
poller.close()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Dave's review agent] Should-fix: A couple of concerns with closing the poller in __del__:

  1. Reachability & client reference contract: PySpark pins every SparkConnectClient via an atexit hook until _close_client() unregisters it (and _close_client() already closes the bridge). Moreover, SessionCellMonitorBridge passes self.client strongly to create_session_poller(...), and client holds hooks closing over self—so any real poller holding client from a live thread pins self from GC anyway (which is why the unit test had to pass None to _FakePoller and patch atexit.register). Either drop this __del__ hunk + test, or document/enforce a weak-client (weakref.proxy(self.client)) and non-blocking close() contract (since __del__ runs on an arbitrary GC thread).
  2. Teardown safety & comment placement: If kept, move this above the existing _client_closed comment (it currently splits that comment from if self.__dict__.get("_client_closed"):), and guard poller.close() so interpreter-teardown errors (e.g. logger being None in _cell_monitoring.py) cannot abort __del__ before super().__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__()

Comment on lines +2397 to +2412
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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Dave's review agent] Nit:

  • _on_cell_monitor_fallback calls _display_operation_link -> IPython.display.display(HTML(...)) directly. If on_fallback is invoked from a background poller thread, display() may render into whichever cell happens to be active (or miss the originating cell's ContextVar). 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_poller holds a SessionCellMonitorBridge (not a poller) and could be named _cell_monitor_bridge; the two WeakMethod lambdas in __init__ could share one weakref.ref(self); and hooks access self._cell_monitor_poller directly while the handler/iterator use self.__dict__.get(...).

Comment on lines +41 to +44
(
"managed_spark_cell_monitoring.spark_connect",
(("line", "cellmonitor"),),
),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Dave's review agent] Should-fix (docs) / nit:

  • Auto-loading %cellmonitor when managed-spark-cell-monitoring is installed (and suppressing operation links / tqdm bars) is user-visible behavior not yet documented in README.md ("Install" / "Interactive Extras" still list only explore_dataframe(), %dpip, and %%sparksql). Please document %cellmonitor, its opt-out, and that managed-spark-cell-monitoring is not pulled in by [interactive].
  • Note also that setting %config ManagedSparkConnect.enable_extras = False unloads the extension/magic but leaves managed_spark_cell_monitoring.spark_connect in sys.modules, so SessionCellMonitorBridge._resolve_poller() will still resolve create_session_poller unless unload_ipython_extension disables monitoring internally.

Comment on lines +32 to +36
_UNGUARDED_METHOD_SUFFIXES = (
"/ReleaseExecute",
"/ReleaseSession",
"/GetStatus",
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment on lines +184 to +186
ManagedSparkSession._project_id = "proj-1"
ManagedSparkSession._region = "us-central1"
ManagedSparkSession._active_s8s_session_id = "sc-sess-1"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Dave's review agent] Should-fix (test hygiene & coverage):

  1. Mutating class-level ManagedSparkSession._project_id, _region, and _active_s8s_session_id directly without mock.patch.object / addCleanup leaks 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_PATH if a developer has that env var set.
  2. Useful missing test cases to add:
    • Monitored client._execute() (SUCCEEDED, FAILED, CANCELLED, and link suppression — currently only the unmonitored path is tested).
    • classify_exception_outcome with a real PySparkException / getCondition() (asserting no FutureWarning), grpc_status_code, chained __cause__/__context__ (including a broken outer exception wrapping a CANCELLED cause), and separate broken-property vs broken-__str__ tests.
    • _sql_lazy_transformation(req) skipping begin_operation/finish_operation.
    • Iterator closed mid-stream (it.close() -> CANCELLED) and an iterator dropped/closed before its first next().
    • SessionCellMonitorBridge error-handling paths (finish_operation TypeError/exception, raising factory, post-close() begin_operation).
    • Progress handler closing an open tqdm bar on suppression, ignoring done=True for note_spark_tasks_seen, and resuming bars once suppression flips to False.
    • Behavioral ProxiedChannel test verifying /GetStatus bypasses is_active_callback.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants