Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
194 changes: 194 additions & 0 deletions google/cloud/managed_spark_connect/_cell_monitoring.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,194 @@
# 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`."""
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
Comment on lines +26 to +58

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"


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


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))
Comment on lines +84 to +89

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.


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

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.

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

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


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,
)
6 changes: 5 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 on lines +41 to +44

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.

)


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
6 changes: 5 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,11 @@

logger = logging.getLogger(__name__)

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

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.

_GUARD_MODE: contextvars.ContextVar[str] = contextvars.ContextVar(
"msc_guard_mode", default="direct"
)
Expand Down
Loading
Loading