From 747f4c52cce2690117b24740f3592d6c02594e77 Mon Sep 17 00:00:00 2001 From: Patrick Chen Date: Mon, 30 Nov 2026 22:00:32 +0000 Subject: [PATCH 1/3] fix: classify SQL DML/CTAS queries as eager in _sql_lazy_transformation --- google/cloud/managed_spark_connect/session.py | 125 +++++++++++++++++- tests/unit/test_cell_monitoring.py | 26 ++-- tests/unit/test_session.py | 67 ++++++++++ 3 files changed, 207 insertions(+), 11 deletions(-) diff --git a/google/cloud/managed_spark_connect/session.py b/google/cloud/managed_spark_connect/session.py index c58d9a73..917968dd 100644 --- a/google/cloud/managed_spark_connect/session.py +++ b/google/cloud/managed_spark_connect/session.py @@ -799,6 +799,125 @@ def _session_state_attrs(session: Any) -> Dict[str, Any]: return attrs +_LAZY_SQL_KEYWORDS = frozenset({"select", "values", "table", "from"}) + + +def _skip_sql_ws_and_comments(sql: str, pos: int) -> int: + """Advance ``pos`` past whitespace, ``--`` comments, and ``/* ... */``.""" + n = len(sql) + while pos < n: + if sql[pos].isspace(): + pos += 1 + elif sql.startswith("--", pos): + nl = sql.find("\n", pos + 2) + pos = n if nl == -1 else nl + 1 + elif sql.startswith("/*", pos): + depth, pos = 1, pos + 2 + while pos < n and depth > 0: + if sql.startswith("/*", pos): + depth, pos = depth + 1, pos + 2 + elif sql.startswith("*/", pos): + depth, pos = depth - 1, pos + 2 + else: + pos += 1 + else: + break + return pos + + +def _next_sql_token(sql: str, pos: int) -> Tuple[Optional[str], int]: + """Return the next lexical SQL token and offset, skipping comments.""" + pos = _skip_sql_ws_and_comments(sql, pos) + n = len(sql) + if pos >= n: + return None, pos + ch = sql[pos] + if ch in ("(", ")", ","): + return ch, pos + 1 + if ch in ("'", '"', "`"): + start, pos = pos, pos + 1 + while pos < n: + if sql[pos] == "\\" and ch != "`": + pos += 2 + elif sql[pos] == ch: + pos += 1 + if pos < n and sql[pos] == ch: + pos += 1 + else: + break + else: + pos += 1 + return sql[start:pos], pos + if ch.isalpha() or ch == "_": + end = pos + 1 + while end < n and (sql[end].isalnum() or sql[end] == "_"): + end += 1 + return sql[pos:end], end + return ch, pos + 1 + + +def _skip_sql_parens(sql: str, pos: int) -> Optional[int]: + """Skip past a parenthesized block whose opening ``(`` was just read.""" + depth = 1 + while depth > 0: + tok, pos = _next_sql_token(sql, pos) + if tok is None: + return None + if tok == "(": + depth += 1 + elif tok == ")": + depth -= 1 + return pos + + +def _is_lazy_sql_query(query: str) -> bool: + """Whether a SQL statement is a lazy query rather than eager DML/DDL.""" + tok, pos = _next_sql_token(query, 0) + while tok == "(": + tok, pos = _next_sql_token(query, pos) + if tok is None: + return False + kw = tok.lower() + if kw in _LAZY_SQL_KEYWORDS: + return True + if kw != "with": + return False + + tok, pos = _next_sql_token(query, pos) + if tok is not None and tok.lower() == "recursive": + tok, pos = _next_sql_token(query, pos) + + while tok is not None: + if not (tok.startswith("`") or tok[0].isalpha() or tok[0] == "_"): + return False + tok, pos = _next_sql_token(query, pos) + if tok == "(": + next_pos = _skip_sql_parens(query, pos) + if next_pos is None: + return False + tok, pos = _next_sql_token(query, next_pos) + if tok is None or tok.lower() != "as": + return False + tok, pos = _next_sql_token(query, pos) + if tok is not None and tok.lower() == "not": + tok, pos = _next_sql_token(query, pos) + if tok is not None and tok.lower() == "materialized": + tok, pos = _next_sql_token(query, pos) + if tok != "(": + return False + next_pos = _skip_sql_parens(query, pos) + if next_pos is None: + return False + tok, pos = _next_sql_token(query, next_pos) + if tok == ",": + tok, pos = _next_sql_token(query, pos) + continue + while tok == "(": + tok, pos = _next_sql_token(query, pos) + return tok is not None and tok.lower() in _LAZY_SQL_KEYWORDS + return False + + class ManagedSparkSession(SparkSession): """The entry point to programming Spark with the Dataset and DataFrame API. @@ -2567,12 +2686,14 @@ def _set_tqdm_factory(cls, factory: Optional[Callable[..., Any]]) -> None: @staticmethod def _sql_lazy_transformation(req): - # Select SQL command + # Lazy SQL query (SELECT, VALUES, TABLE, FROM, or WITH ... query) try: query = req.plan.command.sql_command.input.sql.query - return "select" in query.strip().lower().split() except AttributeError: return False + if not isinstance(query, str): + return False + return _is_lazy_sql_query(query) def _monitored_stream( self, diff --git a/tests/unit/test_cell_monitoring.py b/tests/unit/test_cell_monitoring.py index e8054b77..ddca171e 100644 --- a/tests/unit/test_cell_monitoring.py +++ b/tests/unit/test_cell_monitoring.py @@ -644,18 +644,26 @@ def _exec_behavior(req, *a, **kw): mock_classify.assert_not_called() mock_link.assert_called_once_with(req_unmon.operation_id) - mock_link.reset_mock() - eager_unmon = s.client._execute_plan_request_with_metadata() - eager_unmon.plan.command.sql_command.input.sql.query = ( - "INSERT INTO test_table_2 VALUES (1)" - ) - self.assertEqual(s.client._execute(eager_unmon, {}), "exec-ok") - mock_link.assert_called_once_with(eager_unmon.operation_id) + for eager_sql in ( + "INSERT INTO test_table_2 VALUES (1)", + "INSERT INTO dst SELECT * FROM src", + "CREATE TABLE dst AS SELECT * FROM src", + "WITH cte AS (SELECT 1) INSERT INTO dst SELECT * FROM cte", + ): + mock_link.reset_mock() + eager_unmon = s.client._execute_plan_request_with_metadata() + eager_unmon.plan.command.sql_command.input.sql.query = ( + eager_sql + ) + self.assertEqual( + s.client._execute(eager_unmon, {}), "exec-ok" + ) + mock_link.assert_called_once_with(eager_unmon.operation_id) mock_link.reset_mock() lazy_unmon = s.client._execute_plan_request_with_metadata() lazy_unmon.plan.command.sql_command.input.sql.query = ( - "SELECT * FROM tbl" + "-- comment\nSELECT * FROM tbl" ) self.assertEqual(s.client._execute(lazy_unmon, {}), "exec-ok") mock_link.assert_not_called() @@ -746,7 +754,7 @@ def _fake_stream(req, *a, **kw): req_unmon_dml = s.client._execute_plan_request_with_metadata() req_unmon_dml.plan.command.sql_command.input.sql.query = ( - "INSERT INTO test_table_2 VALUES (1)" + "INSERT INTO dst SELECT * FROM src" ) self.assertEqual( list( diff --git a/tests/unit/test_session.py b/tests/unit/test_session.py index 73ba97c7..42eaebfb 100644 --- a/tests/unit/test_session.py +++ b/tests/unit/test_session.py @@ -2761,6 +2761,73 @@ def test_sql_lazy_transformation(self): ) ) + def _make_sql_req(query: str) -> ExecutePlanRequest: + return ExecutePlanRequest( + session_id="mock-session_id-from-super", + client_type="mock-client_type-from-super", + plan=Plan( + command=Command( + sql_command=SqlCommand( + input=Relation(sql=SQL(query=query)) + ) + ) + ), + tags=["mock-tag-from-super"], + user_context=UserContext(user_id="mock-user-from-super"), + operation_id=test_uuid, + ) + + lazy_queries = [ + "SELECT 1", + "-- lead comment\n/* block SELECT INSERT */\n SELECT * FROM tbl", + "/* /* nested */ */ (SELECT * FROM tbl)", + "VALUES (1, 'a'), (2, 'b')", + "TABLE catalog.db.tbl", + "FROM tbl SELECT a, b", + "WITH cte AS (SELECT 1) SELECT * FROM cte", + "WITH RECURSIVE cte(n) AS (\n SELECT 1 UNION ALL SELECT n + 1 FROM cte WHERE n < 5\n) SELECT * FROM cte", + "WITH cte1 AS (SELECT ') AS INSERT' AS s), cte2(x) AS (SELECT 1) (SELECT * FROM cte1)", + "WITH `select_cte` AS (SELECT 1) VALUES (1)", + ] + for query in lazy_queries: + with self.subTest(lazy=query): + self.assertTrue( + ManagedSparkSession._sql_lazy_transformation( + _make_sql_req(query) + ) + ) + + eager_queries = [ + "INSERT INTO dst SELECT * FROM src", + "INSERT OVERWRITE TABLE dst SELECT * FROM src", + "CREATE TABLE dst AS SELECT * FROM src", + "CREATE OR REPLACE TABLE dst USING DELTA AS SELECT * FROM src", + "REPLACE TABLE dst AS SELECT * FROM src", + "MERGE INTO tgt USING (SELECT * FROM src) s ON tgt.id = s.id WHEN MATCHED THEN DELETE", + "UPDATE tgt SET v = 1 WHERE id IN (SELECT id FROM src)", + "DELETE FROM tgt WHERE id IN (SELECT id FROM src)", + "CACHE TABLE cached AS SELECT * FROM src", + "COPY INTO dst FROM (SELECT * FROM src)", + "WITH cte AS (SELECT 1) INSERT INTO dst SELECT * FROM cte", + "WITH cte AS (SELECT 1), cte2(a) AS (SELECT 2) MERGE INTO tgt USING cte2 ON tgt.a = cte2.a WHEN MATCHED THEN DELETE", + "WITH cte AS (SELECT 1) UPDATE tgt SET a = 1 WHERE EXISTS (SELECT 1 FROM cte)", + "WITH cte AS (SELECT 1) DELETE FROM tgt WHERE id IN (SELECT id FROM cte)", + "-- comment only\n/* also comment */", + "", + ] + for query in eager_queries: + with self.subTest(eager=query): + self.assertFalse( + ManagedSparkSession._sql_lazy_transformation( + _make_sql_req(query) + ) + ) + + self.assertFalse( + ManagedSparkSession._sql_lazy_transformation(mock.MagicMock()) + ) + self.assertFalse(ManagedSparkSession._sql_lazy_transformation(object())) + @mock.patch("google.auth.default") @mock.patch("google.cloud.dataproc_v1.SessionControllerClient") @mock.patch("pyspark.sql.connect.client.SparkConnectClient.config") From 714d4229bf3d4d5f6efa047f3a4f1ba5b2a7474f Mon Sep 17 00:00:00 2001 From: Patrick Chen Date: Mon, 30 Nov 2026 23:10:34 +0000 Subject: [PATCH 2/3] fix: support double-quoted CTE identifiers in _is_lazy_sql_query --- google/cloud/managed_spark_connect/session.py | 4 +++- tests/unit/test_session.py | 2 ++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/google/cloud/managed_spark_connect/session.py b/google/cloud/managed_spark_connect/session.py index 917968dd..e3143318 100644 --- a/google/cloud/managed_spark_connect/session.py +++ b/google/cloud/managed_spark_connect/session.py @@ -888,7 +888,9 @@ def _is_lazy_sql_query(query: str) -> bool: tok, pos = _next_sql_token(query, pos) while tok is not None: - if not (tok.startswith("`") or tok[0].isalpha() or tok[0] == "_"): + if not ( + tok.startswith(("`", '"')) or tok[0].isalpha() or tok[0] == "_" + ): return False tok, pos = _next_sql_token(query, pos) if tok == "(": diff --git a/tests/unit/test_session.py b/tests/unit/test_session.py index 42eaebfb..19f3b4f7 100644 --- a/tests/unit/test_session.py +++ b/tests/unit/test_session.py @@ -2788,6 +2788,7 @@ def _make_sql_req(query: str) -> ExecutePlanRequest: "WITH RECURSIVE cte(n) AS (\n SELECT 1 UNION ALL SELECT n + 1 FROM cte WHERE n < 5\n) SELECT * FROM cte", "WITH cte1 AS (SELECT ') AS INSERT' AS s), cte2(x) AS (SELECT 1) (SELECT * FROM cte1)", "WITH `select_cte` AS (SELECT 1) VALUES (1)", + 'WITH "select_cte" AS (SELECT 1) VALUES (1)', ] for query in lazy_queries: with self.subTest(lazy=query): @@ -2809,6 +2810,7 @@ def _make_sql_req(query: str) -> ExecutePlanRequest: "CACHE TABLE cached AS SELECT * FROM src", "COPY INTO dst FROM (SELECT * FROM src)", "WITH cte AS (SELECT 1) INSERT INTO dst SELECT * FROM cte", + 'WITH "my_cte" AS (SELECT 1) INSERT INTO dst SELECT * FROM "my_cte"', "WITH cte AS (SELECT 1), cte2(a) AS (SELECT 2) MERGE INTO tgt USING cte2 ON tgt.a = cte2.a WHEN MATCHED THEN DELETE", "WITH cte AS (SELECT 1) UPDATE tgt SET a = 1 WHERE EXISTS (SELECT 1 FROM cte)", "WITH cte AS (SELECT 1) DELETE FROM tgt WHERE id IN (SELECT id FROM cte)", From a9302fdce117eee4e96eb82fadbcefe694f698fd Mon Sep 17 00:00:00 2001 From: Patrick Chen Date: Tue, 1 Dec 2026 18:06:37 +0000 Subject: [PATCH 3/3] fix: handle FROM multi-insert, raw strings, optional CTE AS, and nested WITH --- google/cloud/managed_spark_connect/session.py | 109 ++++++++++++------ tests/unit/test_cell_monitoring.py | 24 ++-- tests/unit/test_session.py | 9 ++ 3 files changed, 96 insertions(+), 46 deletions(-) diff --git a/google/cloud/managed_spark_connect/session.py b/google/cloud/managed_spark_connect/session.py index e3143318..1df98bee 100644 --- a/google/cloud/managed_spark_connect/session.py +++ b/google/cloud/managed_spark_connect/session.py @@ -799,7 +799,7 @@ def _session_state_attrs(session: Any) -> Dict[str, Any]: return attrs -_LAZY_SQL_KEYWORDS = frozenset({"select", "values", "table", "from"}) +_LAZY_SQL_KEYWORDS = frozenset({"select", "values", "table"}) def _skip_sql_ws_and_comments(sql: str, pos: int) -> int: @@ -848,6 +848,11 @@ def _next_sql_token(sql: str, pos: int) -> Tuple[Optional[str], int]: else: pos += 1 return sql[start:pos], pos + if ch in ("r", "R") and pos + 1 < n and sql[pos + 1] in ("'", '"'): + quote = sql[pos + 1] + end = sql.find(quote, pos + 2) + end = n if end == -1 else end + 1 + return sql[pos:end], end if ch.isalpha() or ch == "_": end = pos + 1 while end < n and (sql[end].isalnum() or sql[end] == "_"): @@ -870,54 +875,86 @@ def _skip_sql_parens(sql: str, pos: int) -> Optional[int]: return pos -def _is_lazy_sql_query(query: str) -> bool: - """Whether a SQL statement is a lazy query rather than eager DML/DDL.""" - tok, pos = _next_sql_token(query, 0) - while tok == "(": - tok, pos = _next_sql_token(query, pos) - if tok is None: - return False - kw = tok.lower() - if kw in _LAZY_SQL_KEYWORDS: - return True - if kw != "with": - return False - +def _is_lazy_from_statement(query: str, pos: int) -> bool: + """Return False if a FROM statement has a top-level INSERT INTO/OVERWRITE.""" tok, pos = _next_sql_token(query, pos) - if tok is not None and tok.lower() == "recursive": - tok, pos = _next_sql_token(query, pos) - while tok is not None: - if not ( - tok.startswith(("`", '"')) or tok[0].isalpha() or tok[0] == "_" - ): - return False - tok, pos = _next_sql_token(query, pos) if tok == "(": next_pos = _skip_sql_parens(query, pos) if next_pos is None: return False tok, pos = _next_sql_token(query, next_pos) - if tok is None or tok.lower() != "as": - return False + continue + if tok.lower() == "insert": + next_tok, pos = _next_sql_token(query, pos) + if next_tok is not None and next_tok.lower() in ( + "into", + "overwrite", + ): + return False + tok = next_tok + continue tok, pos = _next_sql_token(query, pos) - if tok is not None and tok.lower() == "not": - tok, pos = _next_sql_token(query, pos) - if tok is not None and tok.lower() == "materialized": + return True + + +def _is_lazy_sql_query(query: str) -> bool: + """Whether a SQL statement is a lazy query rather than eager DML/DDL.""" + tok, pos = _next_sql_token(query, 0) + while True: + while tok == "(": tok, pos = _next_sql_token(query, pos) - if tok != "(": + if tok is None: return False - next_pos = _skip_sql_parens(query, pos) - if next_pos is None: + kw = tok.lower() + if kw in _LAZY_SQL_KEYWORDS: + return True + if kw == "from": + return _is_lazy_from_statement(query, pos) + if kw != "with": return False - tok, pos = _next_sql_token(query, next_pos) - if tok == ",": + + tok, pos = _next_sql_token(query, pos) + if tok is not None and tok.lower() == "recursive": tok, pos = _next_sql_token(query, pos) - continue - while tok == "(": + + while True: + if tok is None or not ( + tok.startswith(("`", '"')) or tok[0].isalpha() or tok[0] == "_" + ): + return False tok, pos = _next_sql_token(query, pos) - return tok is not None and tok.lower() in _LAZY_SQL_KEYWORDS - return False + had_paren = False + if tok == "(": + next_pos = _skip_sql_parens(query, pos) + if next_pos is None: + return False + tok, pos = _next_sql_token(query, next_pos) + had_paren = True + if tok is not None and tok.lower() == "as": + tok, pos = _next_sql_token(query, pos) + if tok is not None and tok.lower() == "not": + tok, pos = _next_sql_token(query, pos) + if tok is not None and tok.lower() == "materialized": + tok, pos = _next_sql_token(query, pos) + if tok != "(": + return False + next_pos = _skip_sql_parens(query, pos) + if next_pos is None: + return False + tok, pos = _next_sql_token(query, next_pos) + elif tok == "(": + next_pos = _skip_sql_parens(query, pos) + if next_pos is None: + return False + tok, pos = _next_sql_token(query, next_pos) + elif not had_paren: + return False + + if tok == ",": + tok, pos = _next_sql_token(query, pos) + continue + break class ManagedSparkSession(SparkSession): diff --git a/tests/unit/test_cell_monitoring.py b/tests/unit/test_cell_monitoring.py index ddca171e..85519e8d 100644 --- a/tests/unit/test_cell_monitoring.py +++ b/tests/unit/test_cell_monitoring.py @@ -612,16 +612,20 @@ def _exec_behavior(req, *a, **kw): self.assertEqual(s.client._execute(lazy_req, {}), "exec-ok") self.assertNotIn(lazy_req.operation_id, poller.begun) - dml_req = s.client._execute_plan_request_with_metadata() - dml_req.plan.command.sql_command.input.sql.query = ( - "INSERT INTO test_table_2 VALUES (1)" - ) - self.assertEqual(s.client._execute(dml_req, {}), "exec-ok") - self.assertIn(dml_req.operation_id, poller.begun) - self.assertEqual( - poller.finished[-1], - (dml_req.operation_id, "SUCCEEDED"), - ) + for eager_sql in ( + "INSERT INTO test_table_2 VALUES (1)", + "INSERT INTO dst SELECT * FROM src", + "CREATE TABLE dst AS SELECT * FROM src", + "FROM src INSERT INTO dst SELECT *", + ): + dml_req = s.client._execute_plan_request_with_metadata() + dml_req.plan.command.sql_command.input.sql.query = eager_sql + self.assertEqual(s.client._execute(dml_req, {}), "exec-ok") + self.assertIn(dml_req.operation_id, poller.begun) + self.assertEqual( + poller.finished[-1], + (dml_req.operation_id, "SUCCEEDED"), + ) req_mutate = s.client._execute_plan_request_with_metadata() orig_mutate_id = req_mutate.operation_id diff --git a/tests/unit/test_session.py b/tests/unit/test_session.py index 19f3b4f7..05c56107 100644 --- a/tests/unit/test_session.py +++ b/tests/unit/test_session.py @@ -2789,6 +2789,10 @@ def _make_sql_req(query: str) -> ExecutePlanRequest: "WITH cte1 AS (SELECT ') AS INSERT' AS s), cte2(x) AS (SELECT 1) (SELECT * FROM cte1)", "WITH `select_cte` AS (SELECT 1) VALUES (1)", 'WITH "select_cte" AS (SELECT 1) VALUES (1)', + "WITH cte (SELECT 1) SELECT * FROM cte", + "WITH cte(a) (SELECT 1) SELECT * FROM cte", + r"WITH cte AS (SELECT r'C:\temp\' AS p) SELECT * FROM cte", + "WITH cte1 AS (SELECT 1) (WITH cte2 AS (SELECT 2) SELECT * FROM cte1, cte2)", ] for query in lazy_queries: with self.subTest(lazy=query): @@ -2814,6 +2818,11 @@ def _make_sql_req(query: str) -> ExecutePlanRequest: "WITH cte AS (SELECT 1), cte2(a) AS (SELECT 2) MERGE INTO tgt USING cte2 ON tgt.a = cte2.a WHEN MATCHED THEN DELETE", "WITH cte AS (SELECT 1) UPDATE tgt SET a = 1 WHERE EXISTS (SELECT 1 FROM cte)", "WITH cte AS (SELECT 1) DELETE FROM tgt WHERE id IN (SELECT id FROM cte)", + "FROM src INSERT INTO dst SELECT *", + "FROM src INSERT OVERWRITE TABLE dst SELECT *", + "FROM src INSERT OVERWRITE DIRECTORY '/tmp/out' SELECT *", + "WITH cte AS (SELECT 1) FROM cte INSERT INTO dst SELECT *", + r"WITH cte AS (SELECT r'a\' AS p, 'b) SELECT 1' AS q) INSERT INTO dst SELECT * FROM cte", "-- comment only\n/* also comment */", "", ]