Repository navigation
feat: integrate ManagedSparkSession with Spark Connect cell monitoring #237
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
e6a9f7c
feat: integrate ManagedSparkSession with Spark Connect cell monitoring
ptch314 5f078ee
fix: harden cell monitoring exception classification and session GC c…
ptch314 36597f2
test: mock atexit.register and client.close in GC poller test
ptch314 24bbde5
fix: address cell monitoring lifecycle, exception classification, doc…
ptch314 30adde1
fix: begin cell monitor on DML/CTAS SQL and match cancellation case-i…
ptch314 097f08e
test: close resumed progress bar in cell monitoring test
ptch314 786cf6b
fix: skip cell monitoring on lazy SQL and preserve operation_id pairing
ptch314 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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" | ||
|
|
||
|
|
||
| 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 | ||
|
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, | ||
| ) | ||
|
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, | ||
| ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.