Skip to content

feat(cell_monitoring): extract query and DataFrame plan summary for JobTable - #251

Draft
ptch314 wants to merge 2 commits into
mainfrom
feat/b-593173986-job-query-column
Draft

ptch314 wants to merge 2 commits into
mainfrom
feat/b-593173986-job-query-column

Conversation

@ptch314

@ptch314 ptch314 commented Dec 4, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Extracts a concise query or DataFrame operation description from Spark Connect ExecutePlanRequest.plan on the client and forwards it to managed-spark-cell-monitoring so the Spark Monitor job table can show what each job is executing alongside Job <id>.

Changes

  • Client-side plan extractor (google/cloud/managed_spark_connect/_cell_monitoring.py):
    • Added exception-safe, depth-bounded extract_operation_query(req) supporting:
      • Pure SQL: Command.sql_command (PySpark 4.x input.sql.query and PySpark 3.5 .sql) and SQL-rooted Relation trees 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 internal toDF('_c0', ...).selectExpr(...) wrapper).
      • SQL + PySpark transforms: Chained DataFrame transformations on top of spark.sql(...) (e.g., .filter().count(), .select(), .groupBy(), .agg()) are formatted as sql(<query>).<ops>() so they stay visually distinct from bare SQL and distinguish multiple derivations off the same SQL base.
      • Pure DataFrame plans & commands: Concise pipeline summaries for 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, and MlCommand.
    • Dedents/trims whitespace and caps extracted text at 2,000 characters (...).
  • Backward-compatible bridge & session hooks (_cell_monitoring.py, session.py):
    • Updated SessionCellMonitorBridge.begin_operation(operation_id, *, query=None) to pass query= when non-None, falling back cleanly to 1-arg poller.begin_operation(operation_id) on TypeError when paired with older managed-spark-cell-monitoring releases.
    • Updated execute_hook and _monitored_stream in ManagedSparkSession to extract and pass query for monitored non-lazy operations.
  • Tests (tests/unit/test_cell_monitoring.py):
    • Added comprehensive unit tests covering SQL commands (v3.5 & v4.x), SQL relations (pure vs. %%sparksql display wrapper vs. chained PySpark transforms), pure DataFrame plans, write/DDL/ML commands, multi-line dedent & length cap, malformed/deep inputs, begin_operation forwarding & legacy 1-arg fallback, and _execute / _monitored_stream integration.

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 passed
  • pyink . --check — pass
  • vermin --target=3.10- — pass
  • Cross-repo end-to-end check against managed-spark-cell-monitoring worktree — pass

…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.

@gemini-code-assist gemini-code-assist Bot left a comment

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.

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.

Comment on lines +97 to +104
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

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.

medium

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(

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.

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]:

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.

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants