Repository navigation
Conversation
…obTable 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(...).<ops>()`, and pure DataFrame/command plans (`table`, `read.<fmt>`, `range`, `createDataFrame`, `count`/`agg`/`groupBy`, `join`, set ops, `saveAsTable`, `write.<fmt>`, `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.
There was a problem hiding this comment.
Code Review
This pull request introduces query extraction and forwarding capabilities to the Spark Connect cell monitoring bridge. It adds logic to parse and format various SQL queries, DataFrame transformations, and commands from ExecutePlanRequest payloads, passing the extracted query string to the session poller. Comprehensive unit tests have been added to verify the extraction logic and legacy fallback behavior. The reviewer suggests improving the robustness of the _which_oneof helper function by explicitly catching ValueError when querying invalid oneof fields.
| 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 |
There was a problem hiding this comment.
In Python's protobuf library, calling WhichOneof with a name that is not a valid oneof field in the message descriptor raises a ValueError. While extract_operation_query wraps the entire extraction in a general try...except Exception block, it is safer and more self-contained to handle ValueError directly inside _which_oneof to prevent unexpected failures if this helper is ever reused or called in other contexts.
def _which_oneof(msg: Any, oneof_name: str) -> Optional[str]:\n if msg is None:\n return None\n fn = getattr(msg, \"WhichOneof\", None)\n if not callable(fn):\n return None\n try:\n val = fn(oneof_name)\n except ValueError:\n return None\n return val if isinstance(val, str) and val else None…ch_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.
| ) | ||
| ) | ||
| ) | ||
| chain = relations_pb2.Relation( |
There was a problem hiding this comment.
I feel like these tests would be clearer if they mapped specific pyspark/sql snippets to the final query descriptions, basically like the screenshots in GoogleCloudDataproc/managed-spark-cell-monitoring#66
IIUC, this is doing more or less that, just starting with plans expressed as hand-crafted protobuf, so it's probably fine. But it's still hard to tell at a glance that this proto is really the same as "table(db.orders).filter().groupBy().show()".
Is there a way we can do the pyspark/sql -> proto parsing here, without pulling in a full local pyspark?
| return None | ||
|
|
||
|
|
||
| def extract_operation_query(req: Any) -> Optional[str]: |
There was a problem hiding this comment.
Can you explain more why this plan-to-string conversion logic lives here instead of managed-spark-cell-monitoring? The business logic is more closely coupled to that library. Basically just attach the req to begin_operation and move all the parsing downstream.
Summary
Extracts a concise query or DataFrame operation description from Spark Connect
ExecutePlanRequest.planon the client and forwards it tomanaged-spark-cell-monitoringso the Spark Monitor job table can show what each job is executing alongsideJob <id>.Changes
google/cloud/managed_spark_connect/_cell_monitoring.py):extract_operation_query(req)supporting:Command.sql_command(PySpark 4.xinput.sql.queryand PySpark 3.5.sql) and SQL-rootedRelationtrees wrapped only in display/materialization nodes (show_string,html_string,limit,tail,offset,subquery_alias,to_df,hint,collect_metrics,with_relations, and%%sparksql's internaltoDF('_c0', ...).selectExpr(...)wrapper).spark.sql(...)(e.g.,.filter().count(),.select(),.groupBy(),.agg()) are formatted assql(<query>).<ops>()so they stay visually distinct from bare SQL and distinguish multiple derivations off the same SQL base.Read(table(...),read.<fmt>(...)),Range,LocalRelation,Catalog, unary ops (collapsing consecutive duplicates and distinguishing.count(),.agg(), and.groupBy()), binary ops (join,union/intersect/except,cogroup),WriteOperation(saveAsTable,write.<fmt>),WriteOperationV2(writeTo),CreateDataFrameView,WriteStreamOperationStart,MergeIntoTableCommand,CheckpointCommand, andMlCommand....)._cell_monitoring.py,session.py):SessionCellMonitorBridge.begin_operation(operation_id, *, query=None)to passquery=when non-None, falling back cleanly to 1-argpoller.begin_operation(operation_id)onTypeErrorwhen paired with oldermanaged-spark-cell-monitoringreleases.execute_hookand_monitored_streaminManagedSparkSessionto extract and passqueryfor monitored non-lazy operations.tests/unit/test_cell_monitoring.py):%%sparksqldisplay wrapper vs. chained PySpark transforms), pure DataFrame plans, write/DDL/ML commands, multi-line dedent & length cap, malformed/deep inputs,begin_operationforwarding & legacy 1-arg fallback, and_execute/_monitored_streamintegration.Companion PR
Pairs with GoogleCloudDataproc/managed-spark-cell-monitoring#66 (Spark Monitor Query column and poller update). Both PRs are backward-compatible and can be merged in either order.
Verification
pytest tests/unit/test_cell_monitoring.py -v— 20/20 passedpyink . --check— passvermin --target=3.10-— passmanaged-spark-cell-monitoringworktree — pass