Skip to content
12 changes: 10 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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]'
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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`

Expand Down
227 changes: 227 additions & 0 deletions google/cloud/managed_spark_connect/_cell_monitoring.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,227 @@
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Thin lifecycle bridge to `managed_spark_cell_monitoring.spark_connect`."""

import logging
import re
import sys
import threading
from typing import Any, Callable, List, Optional

logger = logging.getLogger(__name__)

_CELL_MONITOR_EXTENSION = "managed_spark_cell_monitoring.spark_connect"
# Match structured cancellation tokens (brackets, parens, or error prefixes),
# avoiding false positives on user SQL echoed inside quotes (e.g. "'OPERATION_CANCELED'").
_CANCELLED_MSG_RE = re.compile(
r"(?:\[|\(|:\s+|^)(?:OPERATION_CANCELED|SPARK_JOB_CANCELLED|JOB_CANCELLED)\b",
re.IGNORECASE,
)


def classify_exception_outcome(exc: BaseException) -> str:
"""Classifies an `ExecutePlan` exception into `CANCELLED` or `FAILED`."""
seen: set[int] = set()
cur: Optional[BaseException] = exc
while cur is not None and id(cur) not in seen:
seen.add(id(cur))
if isinstance(cur, (KeyboardInterrupt, GeneratorExit)):
return "CANCELLED"
try:
code_fn = getattr(cur, "code", None)
if callable(code_fn):
code = code_fn()
if getattr(code, "name", None) == "CANCELLED":
return "CANCELLED"
except Exception:
pass
try:
grpc_code = getattr(cur, "grpc_status_code", None)
if getattr(grpc_code, "name", None) == "CANCELLED":
return "CANCELLED"
except Exception:
pass
try:
cond_fn = getattr(cur, "getCondition", None) or getattr(
cur, "getErrorClass", None
)
if callable(cond_fn):
cond = cond_fn()
if isinstance(cond, str):
cond_upper = cond.upper()
if "CANCELED" in cond_upper or "CANCELLED" in cond_upper:
return "CANCELLED"
except Exception:
pass
try:
if _CANCELLED_MSG_RE.search(str(cur)):
return "CANCELLED"
except Exception:
pass
try:
cur = getattr(cur, "__cause__", None) or getattr(
cur, "__context__", None
)
except Exception:
break

return "FAILED"
Comment thread
ptch314 marked this conversation as resolved.
Resolved


def _disabled_by_ipython_extras() -> bool:
ipython_mod = sys.modules.get("google.cloud.managed_spark_connect._ipython")
checker = getattr(
ipython_mod, "_is_extension_disabled_for_current_shell", None
)
if callable(checker):
try:
return bool(checker(_CELL_MONITOR_EXTENSION))
except Exception:
return False
return False


class SessionCellMonitorBridge:
"""Lazily delegates operation hooks to `managed-spark-cell-monitoring`.

When `managed_spark_cell_monitoring.spark_connect` is not loaded in the
current Python process, all methods are fast no-ops with zero imports or
background threads.
"""

def __init__(
self,
client: Any,
spark_ui_url_getter: Optional[Callable[[], str]] = None,
on_fallback: Optional[Callable[[List[str]], None]] = None,
) -> None:
self._client = client
self._spark_ui_url_getter = spark_ui_url_getter
self._on_fallback = on_fallback
self._lock = threading.Lock()
self._poller: Any = None
self._closed = False
self._factory_failed = False

def _resolve_poller(self) -> Any:
poller = self._poller
if poller is not None or self._closed or self._factory_failed:
return poller
if _disabled_by_ipython_extras():
return None
mod = sys.modules.get(_CELL_MONITOR_EXTENSION)
if mod is None:
return None
factory = getattr(mod, "create_session_poller", None)
if not callable(factory):
return None
with self._lock:
if self._closed or self._factory_failed or self._client is None:
return None
if self._poller is None:
try:
self._poller = factory(
self._client,
spark_ui_url_getter=self._spark_ui_url_getter,
on_fallback=self._on_fallback,
)
except Exception:
self._factory_failed = True
logger.debug(
"Failed creating Spark Connect cell monitor poller",
exc_info=True,
)
return None
Comment thread
ptch314 marked this conversation as resolved.
Resolved
return self._poller

def begin_operation(self, operation_id: Optional[str]) -> bool:
if not operation_id or self._closed or _disabled_by_ipython_extras():
return False
poller = self._resolve_poller()
if poller is None:
return False
try:
return bool(poller.begin_operation(operation_id))
except Exception:
logger.debug(
"Error in cell monitor begin_operation(%s)",
operation_id,
exc_info=True,
)
return False

def finish_operation(
self,
operation_id: Optional[str],
outcome: str = "SUCCEEDED",
) -> None:
if not operation_id:
return
poller = self._poller
if poller is None:
return
try:
poller.finish_operation(operation_id, outcome=outcome)
except Exception:
logger.debug(
"Error in cell monitor finish_operation(%s)",
operation_id,
exc_info=True,
)
Comment thread
ptch314 marked this conversation as resolved.
Resolved

def note_spark_tasks_seen(self, operation_id: Optional[str]) -> None:
poller = self._poller
if poller is None or not operation_id:
return
try:
poller.note_spark_tasks_seen(operation_id)
except Exception:
logger.debug(
"Error recording Spark tasks for %s",
operation_id,
exc_info=True,
)

def should_suppress_progress_bar(self, operation_id: Optional[str]) -> bool:
poller = self._poller
if (
poller is None
or not operation_id
or self._closed
or _disabled_by_ipython_extras()
):
return False
try:
return bool(poller.should_suppress_progress_bar(operation_id))
except Exception:
return False

def close(self) -> None:
with self._lock:
if self._closed:
return
self._closed = True
poller = self._poller
self._poller = None
self._client = None
self._spark_ui_url_getter = None
self._on_fallback = None
if poller is not None:
try:
poller.close()
except Exception:
logger.debug(
"Error closing Spark Connect cell monitor poller",
exc_info=True,
)
28 changes: 27 additions & 1 deletion google/cloud/managed_spark_connect/_ipython.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@
"google.cloud.managed_spark_magics",
(("line", "dpip"), ("line", "sparksql"), ("cell", "sparksql")),
),
(
"managed_spark_cell_monitoring.spark_connect",
(("line", "cellmonitor"),),
),
Comment thread
ptch314 marked this conversation as resolved.
Resolved
)


Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -448,6 +452,28 @@ def _unload_extras_for_shell(ip: Any) -> None:
state.loaded_extensions.discard(ext_name)


def _is_extension_disabled_for_current_shell(ext_name: str) -> bool:
"""Whether interactive extras were explicitly turned off for this shell."""
ip_mod = sys.modules.get("IPython")
get_ipython = getattr(ip_mod, "get_ipython", None)
if not callable(get_ipython):
return False
ip = get_ipython()
if ip is None:
return False
state = _SHELL_STATES.get(id(ip))
if state is None or state.shell is not ip:
return False
cfg = state.config_instance
if cfg is None or cfg.enable_extras:
return False
ext_mgr = getattr(ip, "extension_manager", None)
loaded = getattr(ext_mgr, "loaded", None)
if isinstance(loaded, (set, dict, list, tuple)) and ext_name in loaded:
return False
return True


def _init_extras() -> None:
"""Initialize interactive extras on package import unless opted out."""
ip = None
Expand Down
8 changes: 7 additions & 1 deletion google/cloud/managed_spark_connect/client/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,13 @@

logger = logging.getLogger(__name__)

_UNGUARDED_METHOD_SUFFIXES = ("/ReleaseExecute", "/ReleaseSession")
_UNGUARDED_METHOD_SUFFIXES = (
"/ReleaseExecute",
"/ReleaseSession",
# Background cell-monitoring polls must run alongside active ExecutePlan
# streams without triggering control-plane liveness checks.
"/GetStatus",
)
Comment thread
ptch314 marked this conversation as resolved.
Resolved
_GUARD_MODE: contextvars.ContextVar[str] = contextvars.ContextVar(
"msc_guard_mode", default="direct"
)
Expand Down
Loading
Loading