From 5f89934cbb1e5f3d2350551e5241f404cde036bd Mon Sep 17 00:00:00 2001 From: Patrick Chen Date: Fri, 4 Dec 2026 15:50:29 +0000 Subject: [PATCH 1/2] feat(cell_monitoring): extract query and DataFrame plan summary for JobTable Extract a concise SQL query or DataFrame pipeline summary from Spark Connect `ExecutePlanRequest.plan` on the client and forward it to `managed-spark-cell-monitoring` via `SessionCellMonitorBridge.begin_operation`. - Support `SqlCommand` (PySpark 4.x `input.sql.query` and 3.5 `.sql`), SQL-rooted relations (unwrapping display/materialization wrappers including `%%sparksql` formatting), SQL + chained PySpark transforms formatted as `sql(...).()`, and pure DataFrame/command plans (`table`, `read.`, `range`, `createDataFrame`, `count`/`agg`/`groupBy`, `join`, set ops, `saveAsTable`, `write.`, `writeTo`, views, `MERGE INTO`, streaming, ML). - Dedent/trim and cap extracted text at 2,000 characters; fully exception-safe and depth-bounded. - Pass `query=` to `poller.begin_operation` with `TypeError` fallback to 1-arg `begin_operation(operation_id)` for backward compatibility with older `managed-spark-cell-monitoring` releases. --- .../managed_spark_connect/_cell_monitoring.py | 468 ++++++++++++- google/cloud/managed_spark_connect/session.py | 17 +- tests/unit/test_cell_monitoring.py | 654 ++++++++++++++++++ 3 files changed, 1132 insertions(+), 7 deletions(-) diff --git a/google/cloud/managed_spark_connect/_cell_monitoring.py b/google/cloud/managed_spark_connect/_cell_monitoring.py index ad5ebe7d..eb5a02a0 100644 --- a/google/cloud/managed_spark_connect/_cell_monitoring.py +++ b/google/cloud/managed_spark_connect/_cell_monitoring.py @@ -13,9 +13,11 @@ # limitations under the License. """Thin lifecycle bridge to `managed_spark_cell_monitoring.spark_connect`.""" +from collections.abc import Sequence import logging import re import sys +import textwrap import threading from typing import Any, Callable, List, Optional @@ -28,6 +30,457 @@ r"(?:\[|\(|:\s+|^)(?:OPERATION_CANCELED|SPARK_JOB_CANCELLED|JOB_CANCELLED)\b", re.IGNORECASE, ) +_MAX_QUERY_CHARS = 2000 +_MAX_PLAN_DEPTH = 64 +_SQL_UNWRAP_RELATIONS = frozenset( + { + "show_string", + "html_string", + "limit", + "tail", + "offset", + "subquery_alias", + "to_df", + "hint", + "collect_metrics", + } +) +_SPARKSQL_POS_COL_RE = re.compile(r"^_c\d+$") +_UNARY_RELATION_OPS = { + "filter": "filter", + "project": "select", + "aggregate": "groupBy", + "sort": "orderBy", + "limit": "limit", + "offset": "offset", + "tail": "tail", + "show_string": "show", + "html_string": "show", + "with_columns": "withColumn", + "with_columns_renamed": "withColumnRenamed", + "drop": "drop", + "deduplicate": "dropDuplicates", + "sample": "sample", + "sample_by": "sampleBy", + "repartition": "repartition", + "repartition_by_expression": "repartition", + "subquery_alias": "alias", + "to_df": "toDF", + "hint": "hint", + "unpivot": "unpivot", + "to_schema": "to", + "map_partitions": "mapInPandas", + "group_map": "applyInPandas", + "apply_in_pandas_with_state": "applyInPandasWithState", + "with_watermark": "withWatermark", + "collect_metrics": "observe", + "parse": "parse", + "transpose": "transpose", + "fill_na": "fillna", + "drop_na": "dropna", + "replace": "replace", + "summary": "summary", + "describe": "describe", + "crosstab": "crosstab", + "cov": "cov", + "corr": "corr", + "approx_quantile": "approxQuantile", + "freq_items": "freqItems", +} +_SET_OP_NAMES = { + 1: "intersect", + 2: "union", + 3: "except", +} + + +def _which_oneof(msg: Any, oneof_name: str) -> Optional[str]: + if msg is None: + return None + fn = getattr(msg, "WhichOneof", None) + if not callable(fn): + return None + val = fn(oneof_name) + return val if isinstance(val, str) and val else None + + +def _non_empty_str(val: Any) -> Optional[str]: + if isinstance(val, str): + stripped = val.strip() + if stripped: + return stripped + return None + + +def _finalize_query(raw: Optional[str]) -> Optional[str]: + if not isinstance(raw, str): + return None + cleaned = textwrap.dedent(raw).strip() + if not cleaned: + return None + if len(cleaned) > _MAX_QUERY_CHARS: + return cleaned[: _MAX_QUERY_CHARS - 3].rstrip() + "..." + return cleaned + + +def _is_sparksql_display_project(project_msg: Any) -> bool: + """Matches %%sparksql's internal `df.toDF('_c0', ...).selectExpr(...)` wrapper.""" + child = getattr(project_msg, "input", None) + if _which_oneof(child, "rel_type") != "to_df": + return False + col_names = getattr(getattr(child, "to_df", None), "column_names", None) + if not isinstance(col_names, Sequence) or isinstance( + col_names, (str, bytes) + ): + return False + if not col_names: + return False + return all( + isinstance(c, str) and bool(_SPARKSQL_POS_COL_RE.match(c)) + for c in col_names + ) + + +def _format_aggregate_op(agg_msg: Any) -> str: + """Distinguishes `.count()`, `.agg()`, and `.groupBy()` on an Aggregate proto.""" + if agg_msg is None: + return "groupBy" + group_type = getattr(agg_msg, "group_type", 0) + # ROLLUP=2, CUBE=3, PIVOT=4, GROUPING_SETS=5 always represent grouped ops. + if isinstance(group_type, int) and group_type in (2, 3, 4, 5): + return "groupBy" + grouping = getattr(agg_msg, "grouping_expressions", None) + has_grouping = ( + isinstance(grouping, Sequence) + and not isinstance(grouping, (str, bytes)) + and len(grouping) > 0 + ) + if has_grouping: + return "groupBy" + aggs = getattr(agg_msg, "aggregate_expressions", None) + if ( + isinstance(aggs, Sequence) + and not isinstance(aggs, (str, bytes)) + and len(aggs) > 0 + ): + if len(aggs) == 1: + expr = aggs[0] + if _which_oneof(expr, "expr_type") == "unresolved_function": + fn_name = _non_empty_str( + getattr( + getattr(expr, "unresolved_function", None), + "function_name", + None, + ) + ) + if fn_name and fn_name.lower() == "count": + return "count" + return "agg" + return "groupBy" + + +def _extract_sql_from_relation(rel: Any, depth: int = 0) -> Optional[str]: + if rel is None or depth >= _MAX_PLAN_DEPTH: + return None + rel_type = _which_oneof(rel, "rel_type") + if rel_type is None: + return None + if rel_type == "sql": + raw = getattr(getattr(rel, "sql", None), "query", None) + if isinstance(raw, str) and raw.strip(): + return raw + return None + if rel_type == "with_relations": + root = getattr(getattr(rel, "with_relations", None), "root", None) + return _extract_sql_from_relation(root, depth + 1) + if rel_type == "project": + proj = getattr(rel, "project", None) + if _is_sparksql_display_project(proj): + return _extract_sql_from_relation( + getattr(proj, "input", None), depth + 1 + ) + return None + if rel_type in _SQL_UNWRAP_RELATIONS: + child = getattr(getattr(rel, rel_type, None), "input", None) + return _extract_sql_from_relation(child, depth + 1) + return None + + +def _format_read_relation(read_msg: Any) -> str: + read_type = _which_oneof(read_msg, "read_type") + if read_type == "named_table": + name = _non_empty_str( + getattr( + getattr(read_msg, "named_table", None), + "unparsed_identifier", + None, + ) + ) + return f"table({name})" if name else "table()" + if read_type == "data_source": + ds = getattr(read_msg, "data_source", None) + fmt = _non_empty_str(getattr(ds, "format", None)) + raw_paths = getattr(ds, "paths", None) + paths: List[str] = [] + if isinstance(raw_paths, Sequence) and not isinstance( + raw_paths, (str, bytes) + ): + for p in raw_paths: + ps = _non_empty_str(p) + if ps: + paths.append(ps) + if paths: + path_arg = paths[0] if len(paths) == 1 else f"{paths[0]}, ..." + if fmt: + return f"read.{fmt}({path_arg})" + return f"read({path_arg})" + if fmt: + return f"read.{fmt}()" + return "read()" + + +def _format_range_relation(range_msg: Any) -> str: + start = getattr(range_msg, "start", 0) + end = getattr(range_msg, "end", None) + step = getattr(range_msg, "step", 1) + if ( + isinstance(start, int) + and not isinstance(start, bool) + and isinstance(end, int) + and not isinstance(end, bool) + ): + if ( + isinstance(step, int) + and not isinstance(step, bool) + and step not in (0, 1) + ): + return f"range({start}, {end}, {step})" + return f"range({start}, {end})" + return "range()" + + +def _format_relation_df(rel: Any, depth: int = 0) -> Optional[str]: + if rel is None or depth >= _MAX_PLAN_DEPTH: + return None + steps: List[str] = [] + cur = rel + cur_depth = depth + base_str: Optional[str] = None + + while cur is not None and cur_depth < _MAX_PLAN_DEPTH: + rel_type = _which_oneof(cur, "rel_type") + if rel_type is None: + break + if rel_type == "with_relations": + cur = getattr(getattr(cur, "with_relations", None), "root", None) + cur_depth += 1 + continue + op_name = _UNARY_RELATION_OPS.get(rel_type) + if op_name is not None: + if rel_type == "aggregate": + op_name = _format_aggregate_op(getattr(cur, "aggregate", None)) + steps.append(op_name) + cur = getattr(getattr(cur, rel_type, None), "input", None) + cur_depth += 1 + continue + if rel_type == "read": + base_str = _format_read_relation(getattr(cur, "read", None)) + elif rel_type == "range": + base_str = _format_range_relation(getattr(cur, "range", None)) + elif rel_type in ("local_relation", "cached_local_relation"): + base_str = "createDataFrame()" + elif rel_type == "cached_remote_relation": + base_str = "cachedRelation()" + elif rel_type == "catalog": + cat_type = _which_oneof(getattr(cur, "catalog", None), "cat_type") + base_str = f"catalog.{cat_type}()" if cat_type else "catalog()" + elif rel_type == "sql": + raw_sql = getattr(getattr(cur, "sql", None), "query", None) + if isinstance(raw_sql, str) and raw_sql.strip(): + inline = " ".join(raw_sql.split()) + base_str = f"sql({inline})" + elif rel_type in ("join", "as_of_join", "lateral_join"): + sub = getattr(cur, rel_type, None) + left_s = _format_relation_df( + getattr(sub, "left", None), cur_depth + 1 + ) + right_s = _format_relation_df( + getattr(sub, "right", None), cur_depth + 1 + ) + if left_s and right_s: + base_str = f"{left_s}.join({right_s})" + elif left_s: + base_str = f"{left_s}.join()" + elif right_s: + base_str = f"join({right_s})" + else: + base_str = "join()" + elif rel_type == "set_op": + sub = getattr(cur, "set_op", None) + left_s = _format_relation_df( + getattr(sub, "left_input", None), cur_depth + 1 + ) + right_s = _format_relation_df( + getattr(sub, "right_input", None), cur_depth + 1 + ) + set_op_name = _SET_OP_NAMES.get( + getattr(sub, "set_op_type", 0), "setOp" + ) + if left_s and right_s: + base_str = f"{left_s}.{set_op_name}({right_s})" + elif left_s: + base_str = f"{left_s}.{set_op_name}()" + else: + base_str = f"{set_op_name}()" + elif rel_type == "co_group_map": + sub = getattr(cur, "co_group_map", None) + left_s = _format_relation_df( + getattr(sub, "input", None), cur_depth + 1 + ) + right_s = _format_relation_df( + getattr(sub, "other", None), cur_depth + 1 + ) + if left_s and right_s: + base_str = f"{left_s}.cogroup({right_s})" + elif left_s: + base_str = f"{left_s}.cogroup()" + else: + base_str = "cogroup()" + elif rel_type == "common_inline_user_defined_data_source": + sub = getattr(cur, rel_type, None) + name = _non_empty_str(getattr(sub, "name", None)) + base_str = f"read.{name}()" if name else "read()" + elif rel_type in ( + "common_inline_user_defined_table_function", + "unresolved_table_valued_function", + ): + sub = getattr(cur, rel_type, None) + name = _non_empty_str(getattr(sub, "function_name", None)) + base_str = f"{name}()" if name else "tvf()" + elif rel_type == "ml_relation": + base_str = "ml()" + break + + collapsed: List[str] = [] + for step in reversed(steps): + if not collapsed or collapsed[-1] != step: + collapsed.append(step) + + if base_str and collapsed: + return f"{base_str}." + ".".join(f"{s}()" for s in collapsed) + if base_str: + return base_str + if collapsed: + return ".".join(f"{s}()" for s in collapsed) + return None + + +def _compose_write_with_input(target: str, input_rel: Any) -> str: + sql_q = _extract_sql_from_relation(input_rel) + if sql_q: + return f"{target}: {textwrap.dedent(sql_q).strip()}" + df_s = _format_relation_df(input_rel) + if df_s: + return f"{df_s}.{target}" + return target + + +def _extract_command_query(cmd: Any) -> Optional[str]: + cmd_type = _which_oneof(cmd, "command_type") + if cmd_type is None: + return None + if cmd_type == "sql_command": + sql_cmd = getattr(cmd, "sql_command", None) + query = getattr( + getattr(getattr(sql_cmd, "input", None), "sql", None), + "query", + None, + ) + if isinstance(query, str) and query.strip(): + return query + legacy_query = getattr(sql_cmd, "sql", None) + if isinstance(legacy_query, str) and legacy_query.strip(): + return legacy_query + return None + if cmd_type == "write_operation": + wo = getattr(cmd, "write_operation", None) + save_type = _which_oneof(wo, "save_type") + source = _non_empty_str(getattr(wo, "source", None)) + if save_type == "table": + table_name = _non_empty_str( + getattr(getattr(wo, "table", None), "table_name", None) + ) + target = ( + f"saveAsTable({table_name})" if table_name else "saveAsTable()" + ) + elif save_type == "path": + path = _non_empty_str(getattr(wo, "path", None)) + if source and path: + target = f"write.{source}({path})" + elif path: + target = f"write({path})" + elif source: + target = f"write.{source}" + else: + target = "write" + else: + target = f"write.{source}" if source else "write" + return _compose_write_with_input(target, getattr(wo, "input", None)) + if cmd_type == "write_operation_v2": + wo2 = getattr(cmd, "write_operation_v2", None) + table_name = _non_empty_str(getattr(wo2, "table_name", None)) + target = f"writeTo({table_name})" if table_name else "writeTo()" + return _compose_write_with_input(target, getattr(wo2, "input", None)) + if cmd_type == "create_dataframe_view": + view = getattr(cmd, "create_dataframe_view", None) + name = _non_empty_str(getattr(view, "name", None)) or "" + is_global = bool(getattr(view, "is_global", False)) + fn = "createGlobalTempView" if is_global else "createTempView" + return f"{fn}({name})" + if cmd_type == "write_stream_operation_start": + ws = getattr(cmd, "write_stream_operation_start", None) + dest = ( + _non_empty_str(getattr(ws, "table_name", None)) + or _non_empty_str(getattr(ws, "path", None)) + or _non_empty_str(getattr(ws, "format", None)) + ) + return f"writeStream({dest})" if dest else "writeStream()" + if cmd_type == "merge_into_table_command": + merge = getattr(cmd, "merge_into_table_command", None) + target_table = _non_empty_str(getattr(merge, "target_table_name", None)) + return f"MERGE INTO {target_table}" if target_table else "MERGE INTO" + if cmd_type == "checkpoint_command": + cp = getattr(cmd, "checkpoint_command", None) + return ( + "localCheckpoint" + if bool(getattr(cp, "local", False)) + else "checkpoint" + ) + if cmd_type == "ml_command": + ml = getattr(cmd, "ml_command", None) + sub = _which_oneof(ml, "command") + return f"ml.{sub}" if sub else "ml" + return None + + +def extract_operation_query(req: Any) -> Optional[str]: + """Extracts a concise query or operation description from an ExecutePlanRequest.""" + try: + plan = getattr(req, "plan", None) + op_type = _which_oneof(plan, "op_type") + if op_type == "command": + return _finalize_query( + _extract_command_query(getattr(plan, "command", None)) + ) + if op_type == "root": + root = getattr(plan, "root", None) + sql_q = _extract_sql_from_relation(root) + if sql_q is not None: + return _finalize_query(sql_q) + return _finalize_query(_format_relation_df(root)) + return None + except Exception: + return None def classify_exception_outcome(exc: BaseException) -> str: @@ -145,13 +598,26 @@ def _resolve_poller(self) -> Any: return None return self._poller - def begin_operation(self, operation_id: Optional[str]) -> bool: + def begin_operation( + self, + operation_id: Optional[str], + *, + query: Optional[str] = None, + ) -> 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: + if query is not None: + try: + return bool( + poller.begin_operation(operation_id, query=query) + ) + except TypeError as exc: + if "query" not in str(exc): + raise return bool(poller.begin_operation(operation_id)) except Exception: logger.debug( diff --git a/google/cloud/managed_spark_connect/session.py b/google/cloud/managed_spark_connect/session.py index 7e537633..cc35ce35 100644 --- a/google/cloud/managed_spark_connect/session.py +++ b/google/cloud/managed_spark_connect/session.py @@ -2461,11 +2461,12 @@ def _execute(req, *args, **kwargs): operation_id = req.operation_id is_lazy_sql = self._sql_lazy_transformation(req) bridge = self.__dict__.get("_cell_monitor_bridge") - monitored = ( - not is_lazy_sql - and bridge is not None - and bridge.begin_operation(operation_id) - ) + monitored = False + if not is_lazy_sql and bridge is not None: + query = _cell_monitoring.extract_operation_query(req) + monitored = bridge.begin_operation( + operation_id, query=query + ) if not monitored and not is_lazy_sql: self._display_operation_link(operation_id) outcome = "SUCCEEDED" @@ -2754,7 +2755,11 @@ def _monitored_stream( """Starts monitoring lazily on first iteration so unconsumed generators never leak.""" operation_id = req.operation_id is_lazy_sql = self._sql_lazy_transformation(req) - if is_lazy_sql or not bridge.begin_operation(operation_id): + monitored = False + if not is_lazy_sql and bridge is not None: + query = _cell_monitoring.extract_operation_query(req) + monitored = bridge.begin_operation(operation_id, query=query) + if not monitored: if not is_lazy_sql: self._display_operation_link(operation_id) yield from inner(req, *args, **kwargs) diff --git a/tests/unit/test_cell_monitoring.py b/tests/unit/test_cell_monitoring.py index fb7c2536..dc34702d 100644 --- a/tests/unit/test_cell_monitoring.py +++ b/tests/unit/test_cell_monitoring.py @@ -25,6 +25,12 @@ import grpc from pyspark.errors.exceptions.connect import SparkConnectGrpcException +from pyspark.sql.connect.proto import ( + base_pb2, + commands_pb2, + expressions_pb2, + relations_pb2, +) from pyspark.sql.connect.shell.progress import StageInfo from google.cloud.managed_spark_connect import _cell_monitoring @@ -1078,5 +1084,653 @@ def test_ipython_extras_preserves_preloaded_cellmonitor_extension(self): self.assertEqual(poller_created, [client]) +class _QueryAwarePoller(_FakePoller): + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.begun_queries: List[tuple[str, Any]] = [] + + def begin_operation(self, operation_id: str, *, query: Any = None) -> bool: + if not super().begin_operation(operation_id): + return False + self.begun_queries.append((operation_id, query)) + return True + + +class TestExtractOperationQueryAndForwarding(unittest.TestCase): + + def _req_with_root( + self, rel: relations_pb2.Relation + ) -> base_pb2.ExecutePlanRequest: + return base_pb2.ExecutePlanRequest(plan=base_pb2.Plan(root=rel)) + + def _req_with_cmd( + self, cmd: commands_pb2.Command + ) -> base_pb2.ExecutePlanRequest: + return base_pb2.ExecutePlanRequest(plan=base_pb2.Plan(command=cmd)) + + def test_sql_command_pyspark4_and_legacy(self): + req_v4 = self._req_with_cmd( + commands_pb2.Command( + sql_command=commands_pb2.SqlCommand( + input=relations_pb2.Relation( + sql=relations_pb2.SQL(query="INSERT INTO t VALUES (1)") + ), + sql="LEGACY IGNORED", + ) + ) + ) + self.assertEqual( + _cell_monitoring.extract_operation_query(req_v4), + "INSERT INTO t VALUES (1)", + ) + + req_v35 = self._req_with_cmd( + commands_pb2.Command( + sql_command=commands_pb2.SqlCommand( + sql="CREATE TABLE t AS SELECT 1" + ) + ) + ) + self.assertEqual( + _cell_monitoring.extract_operation_query(req_v35), + "CREATE TABLE t AS SELECT 1", + ) + + def test_relation_sql_direct_and_wrapped(self): + sql_rel = relations_pb2.Relation( + sql=relations_pb2.SQL(query="SELECT * FROM orders") + ) + self.assertEqual( + _cell_monitoring.extract_operation_query( + self._req_with_root(sql_rel) + ), + "SELECT * FROM orders", + ) + + show_rel = relations_pb2.Relation( + show_string=relations_pb2.ShowString(input=sql_rel) + ) + self.assertEqual( + _cell_monitoring.extract_operation_query( + self._req_with_root(show_rel) + ), + "SELECT * FROM orders", + ) + + limit_rel = relations_pb2.Relation( + limit=relations_pb2.Limit(input=sql_rel, limit=10) + ) + self.assertEqual( + _cell_monitoring.extract_operation_query( + self._req_with_root(limit_rel) + ), + "SELECT * FROM orders", + ) + + # %%sparksql HTML display pattern (`df.toDF('_c0', '_c1').selectExpr(...).limit(21)`) + # still unwraps cleanly to the underlying SQL query. + sparksql_html_rel = relations_pb2.Relation( + limit=relations_pb2.Limit( + limit=21, + input=relations_pb2.Relation( + project=relations_pb2.Project( + input=relations_pb2.Relation( + to_df=relations_pb2.ToDF( + input=sql_rel, column_names=["_c0", "_c1"] + ) + ) + ) + ), + ) + ) + self.assertEqual( + _cell_monitoring.extract_operation_query( + self._req_with_root(sparksql_html_rel) + ), + "SELECT * FROM orders", + ) + + # Genuine PySpark transforms chained onto spark.sql(...) stay visibly + # distinguished as `sql(...).()` rather than masquerading as raw SQL. + count_expr = expressions_pb2.Expression( + unresolved_function=expressions_pb2.Expression.UnresolvedFunction( + function_name="count" + ) + ) + sum_expr = expressions_pb2.Expression( + unresolved_function=expressions_pb2.Expression.UnresolvedFunction( + function_name="sum" + ) + ) + sql_count_rel = relations_pb2.Relation( + aggregate=relations_pb2.Aggregate( + input=relations_pb2.Relation( + filter=relations_pb2.Filter(input=sql_rel) + ), + aggregate_expressions=[count_expr], + ) + ) + self.assertEqual( + _cell_monitoring.extract_operation_query( + self._req_with_root(sql_count_rel) + ), + "sql(SELECT * FROM orders).filter().count()", + ) + + sql_select_rel = relations_pb2.Relation( + show_string=relations_pb2.ShowString( + input=relations_pb2.Relation( + project=relations_pb2.Project(input=sql_rel) + ) + ) + ) + self.assertEqual( + _cell_monitoring.extract_operation_query( + self._req_with_root(sql_select_rel) + ), + "sql(SELECT * FROM orders).select().show()", + ) + + sql_agg_rel = relations_pb2.Relation( + aggregate=relations_pb2.Aggregate( + input=sql_rel, + aggregate_expressions=[sum_expr], + ) + ) + self.assertEqual( + _cell_monitoring.extract_operation_query( + self._req_with_root(sql_agg_rel) + ), + "sql(SELECT * FROM orders).agg()", + ) + + def test_multiline_dedent_strip_and_length_cap(self): + raw = """ + SELECT id, name + FROM users + WHERE active = true + """ + req = self._req_with_root( + relations_pb2.Relation(sql=relations_pb2.SQL(query=raw)) + ) + self.assertEqual( + _cell_monitoring.extract_operation_query(req), + "SELECT id, name\nFROM users\nWHERE active = true", + ) + + long_sql = "SELECT " + "a" * 2500 + req_long = self._req_with_root( + relations_pb2.Relation(sql=relations_pb2.SQL(query=long_sql)) + ) + extracted = _cell_monitoring.extract_operation_query(req_long) + assert extracted is not None + self.assertLessEqual(len(extracted), 2000) + self.assertTrue(extracted.endswith("...")) + self.assertTrue(extracted.startswith("SELECT aaa")) + + def test_pure_dataframe_plans_and_duplicate_collapsing(self): + orders = relations_pb2.Relation( + read=relations_pb2.Read( + named_table=relations_pb2.Read.NamedTable( + unparsed_identifier="db.orders" + ) + ) + ) + chain = relations_pb2.Relation( + show_string=relations_pb2.ShowString( + input=relations_pb2.Relation( + aggregate=relations_pb2.Aggregate( + input=relations_pb2.Relation( + filter=relations_pb2.Filter(input=orders) + ) + ) + ) + ) + ) + self.assertEqual( + _cell_monitoring.extract_operation_query( + self._req_with_root(chain) + ), + "table(db.orders).filter().groupBy().show()", + ) + + ds = relations_pb2.Relation( + read=relations_pb2.Read( + data_source=relations_pb2.Read.DataSource( + format="parquet", paths=["gs://bucket/data"] + ) + ) + ) + users = relations_pb2.Relation( + read=relations_pb2.Read( + named_table=relations_pb2.Read.NamedTable( + unparsed_identifier="users" + ) + ) + ) + joined = relations_pb2.Relation( + show_string=relations_pb2.ShowString( + input=relations_pb2.Relation( + aggregate=relations_pb2.Aggregate( + input=relations_pb2.Relation( + join=relations_pb2.Join(left=ds, right=users) + ) + ) + ) + ) + ) + self.assertEqual( + _cell_monitoring.extract_operation_query( + self._req_with_root(joined) + ), + "read.parquet(gs://bucket/data).join(table(users)).groupBy().show()", + ) + + rng = relations_pb2.Relation( + show_string=relations_pb2.ShowString( + input=relations_pb2.Relation( + aggregate=relations_pb2.Aggregate( + input=relations_pb2.Relation( + range=relations_pb2.Range(start=0, end=1000, step=1) + ) + ) + ) + ) + ) + self.assertEqual( + _cell_monitoring.extract_operation_query(self._req_with_root(rng)), + "range(0, 1000).groupBy().show()", + ) + + local_df = relations_pb2.Relation( + show_string=relations_pb2.ShowString( + input=relations_pb2.Relation( + sort=relations_pb2.Sort( + input=relations_pb2.Relation( + project=relations_pb2.Project( + input=relations_pb2.Relation( + filter=relations_pb2.Filter( + input=relations_pb2.Relation( + local_relation=relations_pb2.LocalRelation() + ) + ) + ) + ) + ) + ) + ) + ) + ) + self.assertEqual( + _cell_monitoring.extract_operation_query( + self._req_with_root(local_df) + ), + "createDataFrame().filter().select().orderBy().show()", + ) + + # Consecutive duplicate transformations collapse into one. + dup_cols = relations_pb2.Relation( + show_string=relations_pb2.ShowString( + input=relations_pb2.Relation( + with_columns=relations_pb2.WithColumns( + input=relations_pb2.Relation( + with_columns=relations_pb2.WithColumns(input=orders) + ) + ) + ) + ) + ) + self.assertEqual( + _cell_monitoring.extract_operation_query( + self._req_with_root(dup_cols) + ), + "table(db.orders).withColumn().show()", + ) + + # SetOp (union / intersect / except) and Catalog and CoGroupMap. + union_rel = relations_pb2.Relation( + set_op=relations_pb2.SetOperation( + left_input=orders, + right_input=users, + set_op_type=relations_pb2.SetOperation.SET_OP_TYPE_UNION, + ) + ) + self.assertEqual( + _cell_monitoring.extract_operation_query( + self._req_with_root(union_rel) + ), + "table(db.orders).union(table(users))", + ) + + cogroup_rel = relations_pb2.Relation( + co_group_map=relations_pb2.CoGroupMap(input=orders, other=users) + ) + self.assertEqual( + _cell_monitoring.extract_operation_query( + self._req_with_root(cogroup_rel) + ), + "table(db.orders).cogroup(table(users))", + ) + + cat_req = base_pb2.ExecutePlanRequest() + cat_req.plan.root.catalog.list_tables.SetInParent() + self.assertEqual( + _cell_monitoring.extract_operation_query(cat_req), + "catalog.list_tables()", + ) + + def test_write_and_other_commands(self): + sql_input = relations_pb2.Relation( + sql=relations_pb2.SQL(query="SELECT * FROM src") + ) + df_input = relations_pb2.Relation( + filter=relations_pb2.Filter( + input=relations_pb2.Relation( + read=relations_pb2.Read( + named_table=relations_pb2.Read.NamedTable( + unparsed_identifier="src" + ) + ) + ) + ) + ) + + # WriteOperation: table + SQL input + wo_table_sql = self._req_with_cmd( + commands_pb2.Command( + write_operation=commands_pb2.WriteOperation( + input=sql_input, + table=commands_pb2.WriteOperation.SaveTable( + table_name="db.dst" + ), + ) + ) + ) + self.assertEqual( + _cell_monitoring.extract_operation_query(wo_table_sql), + "saveAsTable(db.dst): SELECT * FROM src", + ) + + # WriteOperation: path + format + DataFrame input + wo_path_df = self._req_with_cmd( + commands_pb2.Command( + write_operation=commands_pb2.WriteOperation( + input=df_input, + source="parquet", + path="gs://bucket/out", + ) + ) + ) + self.assertEqual( + _cell_monitoring.extract_operation_query(wo_path_df), + "table(src).filter().write.parquet(gs://bucket/out)", + ) + + # WriteOperationV2: DataFrame input & SQL input + wo2_df = self._req_with_cmd( + commands_pb2.Command( + write_operation_v2=commands_pb2.WriteOperationV2( + input=df_input, table_name="cat.db.tbl" + ) + ) + ) + self.assertEqual( + _cell_monitoring.extract_operation_query(wo2_df), + "table(src).filter().writeTo(cat.db.tbl)", + ) + + wo2_sql = self._req_with_cmd( + commands_pb2.Command( + write_operation_v2=commands_pb2.WriteOperationV2( + input=sql_input, table_name="cat.db.tbl" + ) + ) + ) + self.assertEqual( + _cell_monitoring.extract_operation_query(wo2_sql), + "writeTo(cat.db.tbl): SELECT * FROM src", + ) + + # CreateDataFrameView (temp and global) + view_temp = self._req_with_cmd( + commands_pb2.Command( + create_dataframe_view=commands_pb2.CreateDataFrameViewCommand( + name="v_local", is_global=False + ) + ) + ) + self.assertEqual( + _cell_monitoring.extract_operation_query(view_temp), + "createTempView(v_local)", + ) + + view_global = self._req_with_cmd( + commands_pb2.Command( + create_dataframe_view=commands_pb2.CreateDataFrameViewCommand( + name="v_global", is_global=True + ) + ) + ) + self.assertEqual( + _cell_monitoring.extract_operation_query(view_global), + "createGlobalTempView(v_global)", + ) + + # WriteStreamOperationStart + ws_req = self._req_with_cmd( + commands_pb2.Command( + write_stream_operation_start=commands_pb2.WriteStreamOperationStart( + table_name="events_sink" + ) + ) + ) + self.assertEqual( + _cell_monitoring.extract_operation_query(ws_req), + "writeStream(events_sink)", + ) + + # MergeIntoTableCommand + merge_req = self._req_with_cmd( + commands_pb2.Command( + merge_into_table_command=commands_pb2.MergeIntoTableCommand( + target_table_name="db.target" + ) + ) + ) + self.assertEqual( + _cell_monitoring.extract_operation_query(merge_req), + "MERGE INTO db.target", + ) + + # CheckpointCommand (local & regular) + cp_local = self._req_with_cmd( + commands_pb2.Command( + checkpoint_command=commands_pb2.CheckpointCommand(local=True) + ) + ) + self.assertEqual( + _cell_monitoring.extract_operation_query(cp_local), + "localCheckpoint", + ) + cp_reg = self._req_with_cmd( + commands_pb2.Command( + checkpoint_command=commands_pb2.CheckpointCommand(local=False) + ) + ) + self.assertEqual( + _cell_monitoring.extract_operation_query(cp_reg), + "checkpoint", + ) + + # MlCommand + ml_req = base_pb2.ExecutePlanRequest() + ml_req.plan.command.ml_command.fit.SetInParent() + self.assertEqual( + _cell_monitoring.extract_operation_query(ml_req), + "ml.fit", + ) + + def test_empty_none_mock_malformed_and_deep_plan(self): + self.assertIsNone(_cell_monitoring.extract_operation_query(None)) + self.assertIsNone( + _cell_monitoring.extract_operation_query( + base_pb2.ExecutePlanRequest() + ) + ) + self.assertIsNone( + _cell_monitoring.extract_operation_query(mock.MagicMock()) + ) + self.assertIsNone( + _cell_monitoring.extract_operation_query( + types.SimpleNamespace(plan=types.SimpleNamespace()) + ) + ) + + class _ExplodingReq: + + @property + def plan(self): + raise RuntimeError("boom") + + self.assertIsNone( + _cell_monitoring.extract_operation_query(_ExplodingReq()) + ) + + # Cyclic/deeply nested relation (>64) terminates cleanly without infinite loop. + cyclic_rel = types.SimpleNamespace( + WhichOneof=lambda name: "filter" if name == "rel_type" else None + ) + cyclic_rel.filter = types.SimpleNamespace(input=cyclic_rel) + cyclic_plan = types.SimpleNamespace( + WhichOneof=lambda name: "root" if name == "op_type" else None, + root=cyclic_rel, + ) + res = _cell_monitoring.extract_operation_query( + types.SimpleNamespace(plan=cyclic_plan) + ) + self.assertEqual(res, "filter()") + + def test_bridge_begin_operation_query_and_legacy_fallback(self): + # 1. Query-aware poller receives query kwarg. + aware_pollers: List[_QueryAwarePoller] = [] + fake_mod = types.ModuleType(_cell_monitoring._CELL_MONITOR_EXTENSION) + fake_mod.create_session_poller = lambda client, **kw: ( # type: ignore[attr-defined] + aware_pollers.append(_QueryAwarePoller(client, **kw)) + or aware_pollers[-1] + ) + with mock.patch.dict( + sys.modules, {_cell_monitoring._CELL_MONITOR_EXTENSION: fake_mod} + ): + bridge = _cell_monitoring.SessionCellMonitorBridge(mock.MagicMock()) + self.assertTrue(bridge.begin_operation("op-1", query="SELECT 1")) + self.assertEqual( + aware_pollers[0].begun_queries, [("op-1", "SELECT 1")] + ) + + # 2. Legacy 1-arg poller (_FakePoller) falls back gracefully on TypeError. + legacy_pollers: List[_FakePoller] = [] + fake_mod_legacy = types.ModuleType( + _cell_monitoring._CELL_MONITOR_EXTENSION + ) + fake_mod_legacy.create_session_poller = lambda client, **kw: ( # type: ignore[attr-defined] + legacy_pollers.append(_FakePoller(client, **kw)) + or legacy_pollers[-1] + ) + with mock.patch.dict( + sys.modules, + {_cell_monitoring._CELL_MONITOR_EXTENSION: fake_mod_legacy}, + ): + bridge_legacy = _cell_monitoring.SessionCellMonitorBridge( + mock.MagicMock() + ) + self.assertTrue( + bridge_legacy.begin_operation("op-2", query="SELECT 2") + ) + self.assertEqual(legacy_pollers[0].begun, ["op-2"]) + + # 3. Unrelated TypeError is NOT silently retried as 1-arg. + class _BrokenTypeErrorPoller(_FakePoller): + + def begin_operation(self, operation_id: str, *, query=None) -> bool: + raise TypeError("unrelated internal error") + + fake_mod_err = types.ModuleType( + _cell_monitoring._CELL_MONITOR_EXTENSION + ) + fake_mod_err.create_session_poller = ( # type: ignore[attr-defined] + lambda client, **kw: _BrokenTypeErrorPoller(client, **kw) + ) + with mock.patch.dict( + sys.modules, + {_cell_monitoring._CELL_MONITOR_EXTENSION: fake_mod_err}, + ): + bridge_err = _cell_monitoring.SessionCellMonitorBridge( + mock.MagicMock() + ) + self.assertFalse( + bridge_err.begin_operation("op-3", query="SELECT 3") + ) + + def test_execute_and_monitored_stream_forward_extracted_query(self): + created_pollers: List[_QueryAwarePoller] = [] + fake_mod = types.ModuleType(_cell_monitoring._CELL_MONITOR_EXTENSION) + fake_mod.create_session_poller = lambda client, **kw: ( # type: ignore[attr-defined] + created_pollers.append(_QueryAwarePoller(client, **kw)) + or created_pollers[-1] + ) + + with ( + mock.patch.dict( + sys.modules, + {_cell_monitoring._CELL_MONITOR_EXTENSION: fake_mod}, + ), + mock.patch( + "pyspark.sql.connect.session.SparkSession._start_connect_server" + ), + mock.patch( + "pyspark.sql.connect.client.core.SparkConnectClient._execute", + return_value="ok", + ), + mock.patch( + "pyspark.sql.connect.client.core.SparkConnectClient._execute_and_fetch_as_iterator", + side_effect=lambda req, *a, **kw: iter(["row-1"]), + ), + ): + session = ManagedSparkSession("sc://localhost:15002") + session._register_progress_execution_handler() + self.addCleanup(session._close_client) + + # _execute forwards extracted query + req_exec = session.client._execute_plan_request_with_metadata() + req_exec.plan.command.sql_command.input.sql.query = ( + "INSERT INTO dst VALUES (1)" + ) + self.assertEqual(session.client._execute(req_exec, {}), "ok") + + # _execute_and_fetch_as_iterator forwards extracted query + req_stream = session.client._execute_plan_request_with_metadata() + req_stream.plan.root.show_string.input.sql.query = ( + "SELECT * FROM events" + ) + self.assertEqual( + list( + session.client._execute_and_fetch_as_iterator( + req_stream, {} + ) + ), + ["row-1"], + ) + + self.assertEqual(len(created_pollers), 1) + self.assertEqual( + created_pollers[0].begun_queries, + [ + (req_exec.operation_id, "INSERT INTO dst VALUES (1)"), + (req_stream.operation_id, "SELECT * FROM events"), + ], + ) + + if __name__ == "__main__": unittest.main() From 15d408fe8705c50ebc3633a3948abfd671f15bac Mon Sep 17 00:00:00 2001 From: Patrick Chen Date: Fri, 4 Dec 2026 16:33:59 +0000 Subject: [PATCH 2/2] fix(cell_monitoring): catch ValueError on invalid oneof names in _which_oneof Protobuf's `WhichOneof(name)` raises `ValueError` if a message does not define the requested oneof group (e.g. across PySpark proto versions). Return `None` from `_which_oneof` on `ValueError` so callers fall back gracefully instead of aborting plan extraction, and add a focused unit test covering both real protobufs and nested relation fallbacks. --- .../managed_spark_connect/_cell_monitoring.py | 5 ++++- tests/unit/test_cell_monitoring.py | 17 +++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/google/cloud/managed_spark_connect/_cell_monitoring.py b/google/cloud/managed_spark_connect/_cell_monitoring.py index eb5a02a0..4eee18e1 100644 --- a/google/cloud/managed_spark_connect/_cell_monitoring.py +++ b/google/cloud/managed_spark_connect/_cell_monitoring.py @@ -100,7 +100,10 @@ def _which_oneof(msg: Any, oneof_name: str) -> Optional[str]: fn = getattr(msg, "WhichOneof", None) if not callable(fn): return None - val = fn(oneof_name) + try: + val = fn(oneof_name) + except ValueError: + return None return val if isinstance(val, str) and val else None diff --git a/tests/unit/test_cell_monitoring.py b/tests/unit/test_cell_monitoring.py index dc34702d..65beee2f 100644 --- a/tests/unit/test_cell_monitoring.py +++ b/tests/unit/test_cell_monitoring.py @@ -1731,6 +1731,23 @@ def test_execute_and_monitored_stream_forward_extracted_query(self): ], ) + def test_which_oneof_invalid_oneof_name_returns_none(self): + # Real protobuf raises ValueError for unknown oneof group names. + self.assertIsNone( + _cell_monitoring._which_oneof( + relations_pb2.Relation(), "nonexistent_oneof" + ) + ) + # Fallback formatting still succeeds if a nested message lacks an expected oneof. + bad_read = types.SimpleNamespace( + WhichOneof=lambda _name: (_ for _ in ()).throw( + ValueError("Protocol message has no oneof.") + ) + ) + self.assertEqual( + _cell_monitoring._format_read_relation(bad_read), "read()" + ) + if __name__ == "__main__": unittest.main()