From 82ee00f8a7d62d8f3430e6b58990719ee97c78ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Knut=20Olav=20L=C3=B8ite?= Date: Tue, 1 Dec 2026 11:33:23 +0100 Subject: [PATCH] fix(spanner): preserve explicit DB-API transactions across retries When autocommit was enabled and a transaction was explicitly started with `begin()`, retrying an aborted transaction cleared the connection's explicit-transaction flag. As a result, replayed and subsequent statements fell back to autocommit mode instead of executing atomically, and `commit()` or `rollback()` became no-ops. This change fixes that by: - Keeping the explicit-transaction state active across retry attempts until the transaction is committed or rolled back. - Skipping retry recording for successful `BEGIN`, `COMMIT`, and `ROLLBACK` SQL statements (and failed `COMMIT` or `ROLLBACK` calls), so `BEGIN` is not re-executed on an already-started transaction during replay and `COMMIT`/`ROLLBACK` cannot leak into the next transaction's retry history. Failed `BEGIN` calls are still recorded so retries verify the same error. - Clearing the cursor's previous parsed statement before parsing a new one, so a statement parsing failure cannot inherit the prior statement's retry rules. --- .../google/cloud/spanner_dbapi/cursor.py | 32 +- .../cloud/spanner_dbapi/parsed_statement.py | 19 + .../cloud/spanner_dbapi/transaction_helper.py | 6 +- .../mockserver_tests/test_dbapi_autocommit.py | 623 ++++++++++++++++++ .../tests/unit/spanner_dbapi/test_cursor.py | 313 +++++++++ .../unit/spanner_dbapi/test_parse_utils.py | 20 + .../spanner_dbapi/test_transaction_helper.py | 21 + 7 files changed, 1025 insertions(+), 9 deletions(-) diff --git a/packages/google-cloud-spanner/google/cloud/spanner_dbapi/cursor.py b/packages/google-cloud-spanner/google/cloud/spanner_dbapi/cursor.py index 73581f456be8..1a12e75a6ad8 100644 --- a/packages/google-cloud-spanner/google/cloud/spanner_dbapi/cursor.py +++ b/packages/google-cloud-spanner/google/cloud/spanner_dbapi/cursor.py @@ -16,6 +16,7 @@ from collections import namedtuple from dataclasses import replace +from typing import Optional import sqlparse from google.api_core.exceptions import ( @@ -321,6 +322,7 @@ def _reset(self): self._result_set = None self._row_count = None self._batch_dml_rows_count = None + self._parsed_statement = None @check_not_closed def execute(self, sql, args=None): @@ -402,13 +404,8 @@ def _execute(self, sql, args=None, call_from_execute_many=False): raise finally: - if ( - not self._in_retry_mode - and not call_from_execute_many - and not ( - self._parsed_statement is not None - and self._parsed_statement.statement_type == StatementType.DDL - ) + if not call_from_execute_many and self._should_record_execute_for_retry( + exception ): self.transaction_helper.add_execute_statement_for_retry( self, sql, args, exception, False @@ -416,6 +413,27 @@ def _execute(self, sql, args=None, call_from_execute_many=False): if self.connection._client_transaction_started is False: self.connection._spanner_transaction_started = False + def _should_record_execute_for_retry(self, exception: Optional[Exception]) -> bool: + """Return whether the current execute() call should be recorded for retry.""" + if self._in_retry_mode: + return False + if self._parsed_statement is None: + return True + if self._parsed_statement.statement_type == StatementType.DDL: + return False + if ( + self._parsed_statement.statement_type == StatementType.CLIENT_SIDE + and self._parsed_statement.client_side_statement_type is not None + ): + # Transaction boundary statements (such as BEGIN, COMMIT, ROLLBACK) + # alter client-side transaction lifecycle state rather than a single + # Spanner attempt; COMMIT/ROLLBACK also reset retry state on failure. + statement_type = self._parsed_statement.client_side_statement_type + if exception is None: + return statement_type.should_record_success_for_retry + return statement_type.should_record_failure_for_retry + return True + def _execute_in_rw_transaction(self): # For every other operation, we've got to ensure that # any prior DDL statements were run. diff --git a/packages/google-cloud-spanner/google/cloud/spanner_dbapi/parsed_statement.py b/packages/google-cloud-spanner/google/cloud/spanner_dbapi/parsed_statement.py index 3a2defb76bd3..8d3a029bbbfd 100644 --- a/packages/google-cloud-spanner/google/cloud/spanner_dbapi/parsed_statement.py +++ b/packages/google-cloud-spanner/google/cloud/spanner_dbapi/parsed_statement.py @@ -43,6 +43,25 @@ class ClientSideStatementType(Enum): SET_AUTO_PARTITION_MODE = 15 SHOW_AUTO_PARTITION_MODE = 16 + @property + def should_record_success_for_retry(self) -> bool: + """Whether a successful statement should be recorded for transaction retry.""" + return self not in ( + ClientSideStatementType.BEGIN, + ClientSideStatementType.COMMIT, + ClientSideStatementType.ROLLBACK, + ) + + @property + def should_record_failure_for_retry(self) -> bool: + """Whether a failed statement should be recorded for transaction retry.""" + # COMMIT and ROLLBACK reset transaction state in finally blocks, so + # recording a failure would leak into the next transaction. + return self not in ( + ClientSideStatementType.COMMIT, + ClientSideStatementType.ROLLBACK, + ) + class AutocommitDmlMode(Enum): TRANSACTIONAL = 1 diff --git a/packages/google-cloud-spanner/google/cloud/spanner_dbapi/transaction_helper.py b/packages/google-cloud-spanner/google/cloud/spanner_dbapi/transaction_helper.py index b9e9f816ca72..919110bac296 100644 --- a/packages/google-cloud-spanner/google/cloud/spanner_dbapi/transaction_helper.py +++ b/packages/google-cloud-spanner/google/cloud/spanner_dbapi/transaction_helper.py @@ -51,9 +51,11 @@ def __init__(self, connection: "Connection"): # new cursor object used in the retry self._cursor_map: Dict[Cursor, Cursor] = {} - def _set_connection_for_retry(self): + def _set_connection_for_retry(self) -> None: + # Only reset Spanner-side transaction and batch state here. Client-side + # transaction state (such as whether begin() was called) must remain + # active across retry attempts. self._connection._spanner_transaction_started = False - self._connection._transaction_begin_marked = False self._connection._batch_mode = BatchMode.NONE def reset(self): diff --git a/packages/google-cloud-spanner/tests/mockserver_tests/test_dbapi_autocommit.py b/packages/google-cloud-spanner/tests/mockserver_tests/test_dbapi_autocommit.py index 6a234ca72b34..dfabf7425d09 100644 --- a/packages/google-cloud-spanner/tests/mockserver_tests/test_dbapi_autocommit.py +++ b/packages/google-cloud-spanner/tests/mockserver_tests/test_dbapi_autocommit.py @@ -12,17 +12,29 @@ # See the License for the specific language governing permissions and # limitations under the License. +import warnings +from unittest import mock + from google.cloud.spanner_dbapi import Connection +from google.cloud.spanner_dbapi.exceptions import OperationalError, RetryAborted +from google.cloud.spanner_dbapi.transaction_helper import RETRY_ABORTED_ERROR from google.cloud.spanner_v1 import ( CommitRequest, ExecuteBatchDmlRequest, ExecuteSqlRequest, + FixedSizePool, + RollbackRequest, + TransactionOptions, TypeCode, ) +from google.cloud.spanner_v1.testing.mock_spanner import SpannerServicer from tests.mockserver_tests.mock_server_test_base import ( MockServerTestBase, + aborted_status, + add_error, add_single_result, add_update_count, + internal_server_error_status, ) @@ -33,6 +45,11 @@ def setUp(self): "select name from singers", "name", TypeCode.STRING, [("Some Singer",)] ) add_update_count("insert into singers (id, name) values (1, 'Some Singer')", 1) + add_update_count("insert into singers (id, name) values (2, 'Other Singer')", 1) + + def tearDown(self): + self.spanner_service.mock_spanner._errors_list = {} + super().tearDown() def test_select_autocommit(self): connection = Connection(self.instance, self.database) @@ -124,3 +141,609 @@ def test_batch_dml_autocommit(self): ) ) self.assertEqual(1, len(commit_requests)) + + def _assert_autocommit_begin_commit_aborted_retries_atomically( + self, use_sql_begin: bool + ): + connection = Connection(self.instance, self.database) + connection.autocommit = True + try: + with connection.cursor() as cursor: + if use_sql_begin: + cursor.execute("begin isolation level repeatable read") + else: + connection.begin( + isolation_level=TransactionOptions.IsolationLevel.REPEATABLE_READ + ) + cursor.execute( + "insert into singers (id, name) values (1, 'Some Singer')" + ) + cursor.execute( + "insert into singers (id, name) values (2, 'Other Singer')" + ) + + add_error(SpannerServicer.Commit.__name__, aborted_status()) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.simplefilter("always") + connection.commit() + + self.assertEqual(caught_warnings, []) + self.assertFalse(connection._transaction_begin_marked) + + execute_requests = [ + request + for request in self.spanner_service.requests + if isinstance(request, ExecuteSqlRequest) + ] + self.assertEqual(len(execute_requests), 4) + self.assertTrue( + all(not request.last_statement for request in execute_requests) + ) + self.assertEqual( + execute_requests[0].transaction.begin.isolation_level, + TransactionOptions.IsolationLevel.REPEATABLE_READ, + ) + self.assertEqual( + execute_requests[2].transaction.begin.isolation_level, + TransactionOptions.IsolationLevel.REPEATABLE_READ, + ) + + commit_requests = [ + request + for request in self.spanner_service.requests + if isinstance(request, CommitRequest) + ] + self.assertEqual(len(commit_requests), 2) + finally: + connection.close() + + def test_autocommit_begin_commit_aborted_retries_atomically(self): + self._assert_autocommit_begin_commit_aborted_retries_atomically( + use_sql_begin=False + ) + + def test_autocommit_begin_dml_aborted_preserves_rollback(self): + connection = Connection(self.instance, self.database) + connection.autocommit = True + connection.begin() + try: + with connection.cursor() as cursor: + cursor.execute( + "insert into singers (id, name) values (1, 'Some Singer')" + ) + add_error( + SpannerServicer.ExecuteStreamingSql.__name__, aborted_status() + ) + cursor.execute( + "insert into singers (id, name) values (2, 'Other Singer')" + ) + + self.assertTrue(connection._transaction_begin_marked) + self.assertTrue(connection._client_transaction_started) + + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.simplefilter("always") + connection.rollback() + + self.assertEqual(caught_warnings, []) + self.assertFalse(connection._transaction_begin_marked) + + commit_requests = [ + request + for request in self.spanner_service.requests + if isinstance(request, CommitRequest) + ] + self.assertEqual(commit_requests, []) + + rollback_requests = [ + request + for request in self.spanner_service.requests + if isinstance(request, RollbackRequest) + ] + self.assertEqual(len(rollback_requests), 1) + finally: + connection.close() + + def test_autocommit_sql_begin_commit_aborted_retries_atomically(self): + self._assert_autocommit_begin_commit_aborted_retries_atomically( + use_sql_begin=True + ) + + def test_autocommit_begin_first_statement_aborted_retries_atomically(self): + connection = Connection(self.instance, self.database) + connection.autocommit = True + connection.begin() + try: + add_error(SpannerServicer.ExecuteStreamingSql.__name__, aborted_status()) + with connection.cursor() as cursor: + cursor.execute( + "insert into singers (id, name) values (1, 'Some Singer')" + ) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.simplefilter("always") + connection.commit() + + self.assertEqual(caught_warnings, []) + self.assertFalse(connection._transaction_begin_marked) + + execute_requests = [ + request + for request in self.spanner_service.requests + if isinstance(request, ExecuteSqlRequest) + ] + self.assertEqual(len(execute_requests), 2) + self.assertTrue( + all(not request.last_statement for request in execute_requests) + ) + commit_requests = [ + request + for request in self.spanner_service.requests + if isinstance(request, CommitRequest) + ] + self.assertEqual(len(commit_requests), 1) + finally: + connection.close() + + def test_autocommit_begin_select_and_dml_aborted_retries_in_rw_transaction(self): + connection = Connection(self.instance, self.database) + connection.autocommit = True + connection.begin() + try: + with connection.cursor() as cursor: + cursor.execute( + "insert into singers (id, name) values (1, 'Some Singer')" + ) + cursor.execute("select name from singers") + rows = cursor.fetchall() + self.assertEqual(rows, [("Some Singer",)]) + + add_error(SpannerServicer.Commit.__name__, aborted_status()) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.simplefilter("always") + connection.commit() + + self.assertEqual(caught_warnings, []) + self.assertFalse(connection._transaction_begin_marked) + + execute_requests = [ + request + for request in self.spanner_service.requests + if isinstance(request, ExecuteSqlRequest) + ] + self.assertEqual(len(execute_requests), 4) + select_requests = [ + request + for request in execute_requests + if request.sql == "select name from singers" + ] + self.assertEqual(len(select_requests), 2) + # Both the initial query and the retry replay must run inside the RW transaction. + self.assertTrue( + all("id" in request.transaction for request in select_requests) + ) + self.assertTrue( + all(not request.last_statement for request in execute_requests) + ) + commit_requests = [ + request + for request in self.spanner_service.requests + if isinstance(request, CommitRequest) + ] + self.assertEqual(len(commit_requests), 2) + finally: + connection.close() + + def test_autocommit_begin_executemany_aborted_retries_atomically(self): + connection = Connection(self.instance, self.database) + connection.autocommit = True + connection.begin() + try: + add_error(SpannerServicer.ExecuteBatchDml.__name__, aborted_status()) + with connection.cursor() as cursor: + cursor.executemany( + "insert into singers (id, name) values (1, 'Some Singer')", [(), ()] + ) + self.assertEqual(cursor.rowcount, 2) + + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.simplefilter("always") + connection.commit() + + self.assertEqual(caught_warnings, []) + batch_requests = [ + request + for request in self.spanner_service.requests + if isinstance(request, ExecuteBatchDmlRequest) + ] + self.assertEqual(len(batch_requests), 2) + self.assertTrue( + all(not request.last_statements for request in batch_requests) + ) + commit_requests = [ + request + for request in self.spanner_service.requests + if isinstance(request, CommitRequest) + ] + self.assertEqual(len(commit_requests), 1) + finally: + connection.close() + + def test_autocommit_begin_batch_dml_and_abort_batch_retry_atomically(self): + connection = Connection(self.instance, self.database) + connection.autocommit = True + connection.begin() + try: + with connection.cursor() as cursor: + cursor.execute("start batch dml") + cursor.execute( + "insert into singers (id, name) values (1, 'Some Singer')" + ) + cursor.execute("abort batch") + cursor.execute("start batch dml") + cursor.execute( + "insert into singers (id, name) values (1, 'Some Singer')" + ) + cursor.execute( + "insert into singers (id, name) values (2, 'Other Singer')" + ) + cursor.execute("run batch") + self.assertEqual(cursor.rowcount, 2) + + add_error(SpannerServicer.Commit.__name__, aborted_status()) + connection.commit() + + batch_requests = [ + request + for request in self.spanner_service.requests + if isinstance(request, ExecuteBatchDmlRequest) + ] + self.assertEqual(len(batch_requests), 2) + self.assertTrue( + all(not request.last_statements for request in batch_requests) + ) + commit_requests = [ + request + for request in self.spanner_service.requests + if isinstance(request, CommitRequest) + ] + self.assertEqual(len(commit_requests), 2) + finally: + connection.close() + + def test_autocommit_begin_commit_retry_mismatch_raises_without_autocommit(self): + connection = Connection(self.instance, self.database) + connection.autocommit = True + connection.begin() + try: + with connection.cursor() as cursor: + cursor.execute( + "insert into singers (id, name) values (1, 'Some Singer')" + ) + cursor.execute("select name from singers") + self.assertEqual(cursor.fetchall(), [("Some Singer",)]) + + add_error(SpannerServicer.Commit.__name__, aborted_status()) + # Change query result on replay so retry detects concurrent modification. + add_single_result( + "select name from singers", "name", TypeCode.STRING, [("Changed",)] + ) + + with self.assertRaisesRegex(RetryAborted, RETRY_ABORTED_ERROR): + connection.commit() + + self.assertFalse(connection._transaction_begin_marked) + commit_requests = [ + request + for request in self.spanner_service.requests + if isinstance(request, CommitRequest) + ] + # Only the aborted Commit was attempted; the mismatching replay did not autocommit. + self.assertEqual(len(commit_requests), 1) + finally: + connection.close() + + def test_autocommit_begin_post_commit_reverts_to_autocommit(self): + connection = Connection(self.instance, self.database) + connection.autocommit = True + connection.begin() + try: + with connection.cursor() as cursor: + cursor.execute( + "insert into singers (id, name) values (1, 'Some Singer')" + ) + add_error(SpannerServicer.Commit.__name__, aborted_status()) + connection.commit() + + self.assertFalse(connection._transaction_begin_marked) + # Subsequent statement after commit must run in autocommit mode again. + cursor.execute( + "insert into singers (id, name) values (2, 'Other Singer')" + ) + + # And a new explicit begin() must succeed. + connection.begin() + self.assertTrue(connection._transaction_begin_marked) + connection.rollback() + + execute_requests = [ + request + for request in self.spanner_service.requests + if isinstance(request, ExecuteSqlRequest) + ] + self.assertEqual(len(execute_requests), 3) + self.assertFalse(execute_requests[0].last_statement) + self.assertFalse(execute_requests[1].last_statement) + self.assertTrue(execute_requests[2].last_statement) + finally: + connection.close() + + def test_autocommit_false_sql_commit_and_rollback_across_transactions(self): + connection = Connection(self.instance, self.database) + connection.autocommit = False + try: + with connection.cursor() as cursor: + cursor.execute( + "insert into singers (id, name) values (1, 'Some Singer')" + ) + cursor.execute("commit") + + cursor.execute( + "insert into singers (id, name) values (1, 'Some Singer')" + ) + cursor.execute("rollback") + + cursor.execute( + "insert into singers (id, name) values (1, 'Some Singer')" + ) + add_error( + SpannerServicer.Commit.__name__, + internal_server_error_status("commit failed"), + ) + with self.assertRaises(OperationalError) as exc_context: + cursor.execute("commit") + self.assertIn("commit failed", str(exc_context.exception.__cause__)) + + # Next transaction must not replay any of the prior COMMIT/ROLLBACK statements. + cursor.execute( + "insert into singers (id, name) values (2, 'Other Singer')" + ) + add_error(SpannerServicer.Commit.__name__, aborted_status()) + connection.commit() + + execute_requests = [ + request + for request in self.spanner_service.requests + if isinstance(request, ExecuteSqlRequest) + ] + # 3 inserts in prior txns + 1 insert in final txn + 1 replayed insert on abort = 5. + self.assertEqual(len(execute_requests), 5) + finally: + connection.close() + + def test_autocommit_begin_client_side_show_and_set_retry_atomically(self): + connection = Connection(self.instance, self.database) + connection.autocommit = True + connection.begin() + try: + with connection.cursor() as cursor: + cursor.execute("set data_boost_enabled = true") + cursor.execute("show variable data_boost_enabled") + self.assertEqual(cursor.fetchall(), [(True,)]) + # Flip back to false before aborting so replay MUST re-run the first + # SET to satisfy the [(True,)] checksum above. + cursor.execute("set data_boost_enabled = false") + cursor.execute("show variable data_boost_enabled") + self.assertEqual(cursor.fetchall(), [(False,)]) + cursor.execute( + "insert into singers (id, name) values (1, 'Some Singer')" + ) + + add_error(SpannerServicer.Commit.__name__, aborted_status()) + connection.commit() + + self.assertFalse(connection.data_boost_enabled) + self.assertFalse(connection._transaction_begin_marked) + commit_requests = [ + request + for request in self.spanner_service.requests + if isinstance(request, CommitRequest) + ] + self.assertEqual(len(commit_requests), 2) + finally: + connection.close() + + def test_autocommit_sql_begin_sql_commit_and_rollback_aborted_atomically(self): + connection = Connection(self.instance, self.database) + connection.autocommit = True + try: + with connection.cursor() as cursor: + cursor.execute("begin") + cursor.execute( + "insert into singers (id, name) values (1, 'Some Singer')" + ) + # Two consecutive Commit aborts verify multi-attempt retry preservation. + add_error(SpannerServicer.Commit.__name__, aborted_status()) + add_error(SpannerServicer.Commit.__name__, aborted_status()) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.simplefilter("always") + cursor.execute("commit") + self.assertEqual(caught_warnings, []) + self.assertFalse(connection._transaction_begin_marked) + + # Subsequent DML runs in autocommit mode again. + cursor.execute( + "insert into singers (id, name) values (2, 'Other Singer')" + ) + + # A second SQL BEGIN + DML abort + SQL ROLLBACK must roll back atomically + # without replaying the earlier COMMIT. + cursor.execute("begin") + cursor.execute( + "insert into singers (id, name) values (1, 'Some Singer')" + ) + add_error( + SpannerServicer.ExecuteStreamingSql.__name__, aborted_status() + ) + cursor.execute( + "insert into singers (id, name) values (2, 'Other Singer')" + ) + cursor.execute("rollback") + self.assertFalse(connection._transaction_begin_marked) + + execute_requests = [ + request + for request in self.spanner_service.requests + if isinstance(request, ExecuteSqlRequest) + ] + # 3 attempts for first txn + 1 autocommit + 4 for second txn (2 initial, 2 retry) = 8. + self.assertEqual(len(execute_requests), 8) + self.assertTrue(execute_requests[3].last_statement) + self.assertFalse(execute_requests[4].last_statement) + + commit_requests = [ + request + for request in self.spanner_service.requests + if isinstance(request, CommitRequest) + ] + # 3 commits for first txn (2 aborted + 1 ok) + 1 autocommit = 4; 0 for rolled-back txn. + self.assertEqual(len(commit_requests), 4) + rollback_requests = [ + request + for request in self.spanner_service.requests + if isinstance(request, RollbackRequest) + ] + self.assertEqual(len(rollback_requests), 1) + finally: + connection.close() + + def test_autocommit_begin_run_batch_aborted_directly_retries_atomically(self): + connection = Connection(self.instance, self.database) + connection.autocommit = True + connection.begin() + try: + with connection.cursor() as cursor: + cursor.execute("start batch dml") + cursor.execute( + "insert into singers (id, name) values (1, 'Some Singer')" + ) + cursor.execute( + "insert into singers (id, name) values (2, 'Other Singer')" + ) + add_error(SpannerServicer.ExecuteBatchDml.__name__, aborted_status()) + cursor.execute("run batch") + self.assertEqual(cursor.rowcount, 2) + + self.assertTrue(connection._transaction_begin_marked) + connection.commit() + self.assertFalse(connection._transaction_begin_marked) + + batch_requests = [ + request + for request in self.spanner_service.requests + if isinstance(request, ExecuteBatchDmlRequest) + ] + self.assertEqual(len(batch_requests), 2) + self.assertTrue( + all(not request.last_statements for request in batch_requests) + ) + commit_requests = [ + request + for request in self.spanner_service.requests + if isinstance(request, CommitRequest) + ] + self.assertEqual(len(commit_requests), 1) + finally: + connection.close() + + def test_autocommit_false_sql_commit_retry_aborted_does_not_leak(self): + connection = Connection(self.instance, self.database) + connection.autocommit = False + try: + with connection.cursor() as cursor: + cursor.execute("select name from singers") + self.assertEqual(cursor.fetchall(), [("Some Singer",)]) + + add_error(SpannerServicer.Commit.__name__, aborted_status()) + add_single_result( + "select name from singers", "name", TypeCode.STRING, [("Changed",)] + ) + with self.assertRaisesRegex(RetryAborted, RETRY_ABORTED_ERROR): + cursor.execute("commit") + + # Next transaction must not replay the failed COMMIT. + cursor.execute( + "insert into singers (id, name) values (1, 'Some Singer')" + ) + add_error(SpannerServicer.Commit.__name__, aborted_status()) + connection.commit() + + insert_requests = [ + request + for request in self.spanner_service.requests + if isinstance(request, ExecuteSqlRequest) + and request.sql.startswith("insert") + ] + self.assertEqual(len(insert_requests), 2) + finally: + connection.close() + + def test_autocommit_begin_fetchone_and_fetchmany_commit_aborted(self): + connection = Connection(self.instance, self.database) + connection.autocommit = True + connection.begin() + try: + with connection.cursor() as cursor: + cursor.execute( + "insert into singers (id, name) values (1, 'Some Singer')" + ) + cursor.execute("select name from singers") + self.assertEqual(cursor.fetchone(), ("Some Singer",)) + self.assertEqual(cursor.fetchmany(2), []) + + add_error(SpannerServicer.Commit.__name__, aborted_status()) + connection.commit() + self.assertFalse(connection._transaction_begin_marked) + + commit_requests = [ + request + for request in self.spanner_service.requests + if isinstance(request, CommitRequest) + ] + self.assertEqual(len(commit_requests), 2) + finally: + connection.close() + + def test_autocommit_begin_regular_pool_releases_session_after_retry(self): + pool = FixedSizePool(size=1) + database = self.instance.database(self.database.database_id, pool=pool) + with ( + mock.patch.object( + database._sessions_manager, "_use_multiplexed", return_value=False + ), + mock.patch.object( + database._sessions_manager, + "put_session", + wraps=database._sessions_manager.put_session, + ) as mock_put_session, + ): + connection = Connection(self.instance, database) + connection.autocommit = True + try: + self.assertEqual(pool._sessions.qsize(), 1) + connection.begin() + with connection.cursor() as cursor: + cursor.execute( + "insert into singers (id, name) values (1, 'Some Singer')" + ) + self.assertEqual(pool._sessions.qsize(), 0) + self.assertIsNotNone(connection._session) + self.assertFalse(connection._session.is_multiplexed) + + add_error(SpannerServicer.Commit.__name__, aborted_status()) + connection.commit() + + self.assertIsNone(connection._session) + self.assertEqual(pool._sessions.qsize(), 1) + mock_put_session.assert_called_once() + finally: + connection.close() diff --git a/packages/google-cloud-spanner/tests/unit/spanner_dbapi/test_cursor.py b/packages/google-cloud-spanner/tests/unit/spanner_dbapi/test_cursor.py index 567c617092c5..ff4ef1ce67a1 100644 --- a/packages/google-cloud-spanner/tests/unit/spanner_dbapi/test_cursor.py +++ b/packages/google-cloud-spanner/tests/unit/spanner_dbapi/test_cursor.py @@ -1913,3 +1913,316 @@ def test_transaction_retry_unqualified_executemany_does_not_duplicate_where_clau ) self.assertNotIn("WHERE 1=1 WHERE 1=1", retried_statements[0].sql) self.assertNotIn("WHERE 1=1 WHERE 1=1", retried_statements[1].sql) + + def _assert_autocommit_begin_retry_preserves_state(self, use_sql_begin: bool): + connection = self._make_connection(self.INSTANCE, mock.MagicMock()) + connection.autocommit = True + cursor = self._make_one(connection) + if use_sql_begin: + cursor.execute("BEGIN") + self.assertEqual( + cursor.transaction_helper._statement_result_details_list, [] + ) + else: + connection.begin() + self.assertTrue(connection._transaction_begin_marked) + + metadata_mock = mock.Mock() + metadata_mock.trailing_metadata.return_value = {} + mock_result_set = mock.MagicMock() + mock_result_set.metadata.row_type = None + mock_result_set.stats.row_count_exact = 1 + + connection.run_statement = mock.Mock( + side_effect=[ + mock_result_set, + Aborted("Aborted", errors=[metadata_mock]), + mock_result_set, + mock_result_set, + ] + ) + + cursor.execute("UPDATE singers SET name = 'a' WHERE id = 1") + cursor.execute("UPDATE singers SET name = 'b' WHERE id = 2") + + self.assertTrue(connection._transaction_begin_marked) + self.assertTrue(connection._client_transaction_started) + self.assertEqual(connection.run_statement.call_count, 4) + connection.database.run_in_transaction.assert_not_called() + + def test_autocommit_explicit_begin_retry_preserves_transaction_state(self): + """Retrying after Aborted in an autocommit + begin() transaction must not fall back to autocommit.""" + self._assert_autocommit_begin_retry_preserves_state(use_sql_begin=False) + + def test_autocommit_sql_begin_retry_preserves_transaction_state(self): + """Successful SQL BEGIN is not replayed as a statement and preserves transaction state on retry.""" + self._assert_autocommit_begin_retry_preserves_state(use_sql_begin=True) + + def test_failed_sql_begin_is_recorded_and_verified_on_retry(self): + """A failing SQL BEGIN must still be recorded and fail deterministically on retry.""" + from google.cloud.spanner_dbapi.exceptions import OperationalError + + connection = self._make_connection(self.INSTANCE, mock.MagicMock()) + connection.autocommit = True + connection.begin() + cursor = self._make_one(connection) + + with self.assertRaisesRegex( + OperationalError, "A transaction has already started" + ): + cursor.execute("BEGIN") + + self.assertEqual( + len(cursor.transaction_helper._statement_result_details_list), 1 + ) + + metadata_mock = mock.Mock() + metadata_mock.trailing_metadata.return_value = {} + mock_result_set = mock.MagicMock() + mock_result_set.metadata.row_type = None + mock_result_set.stats.row_count_exact = 1 + + connection.run_statement = mock.Mock( + side_effect=[ + Aborted("Aborted", errors=[metadata_mock]), + mock_result_set, + ] + ) + + cursor.execute("UPDATE singers SET name = 'a' WHERE id = 1") + + self.assertTrue(connection._transaction_begin_marked) + self.assertEqual(connection.run_statement.call_count, 2) + connection.database.run_in_transaction.assert_not_called() + + def test_should_record_execute_for_retry_matrix(self): + """Verify _should_record_execute_for_retry across all statement types and outcomes.""" + from google.cloud.spanner_dbapi.parsed_statement import ClientSideStatementType + + connection = self._make_connection(self.INSTANCE, mock.MagicMock()) + cursor = self._make_one(connection) + error = RuntimeError("failure") + + cursor._in_retry_mode = True + cursor._parsed_statement = ParsedStatement(StatementType.UPDATE, Statement("u")) + self.assertFalse(cursor._should_record_execute_for_retry(None)) + self.assertFalse(cursor._should_record_execute_for_retry(error)) + + cursor._in_retry_mode = False + cursor._parsed_statement = None + self.assertTrue(cursor._should_record_execute_for_retry(None)) + self.assertTrue(cursor._should_record_execute_for_retry(error)) + + cursor._parsed_statement = ParsedStatement( + StatementType.DDL, Statement("CREATE TABLE T (Id INT64) PRIMARY KEY (Id)") + ) + self.assertFalse(cursor._should_record_execute_for_retry(None)) + self.assertFalse(cursor._should_record_execute_for_retry(error)) + + cursor._parsed_statement = ParsedStatement( + StatementType.CLIENT_SIDE, Statement("CUSTOM"), None + ) + self.assertTrue(cursor._should_record_execute_for_retry(None)) + self.assertTrue(cursor._should_record_execute_for_retry(error)) + + for statement_type in ClientSideStatementType: + cursor._parsed_statement = ParsedStatement( + StatementType.CLIENT_SIDE, + Statement(statement_type.name), + statement_type, + ) + self.assertEqual( + cursor._should_record_execute_for_retry(None), + statement_type.should_record_success_for_retry, + ) + self.assertEqual( + cursor._should_record_execute_for_retry(error), + statement_type.should_record_failure_for_retry, + ) + + for statement_type in ( + StatementType.QUERY, + StatementType.UPDATE, + StatementType.INSERT, + StatementType.UNKNOWN, + ): + cursor._parsed_statement = ParsedStatement(statement_type, Statement("SQL")) + self.assertTrue(cursor._should_record_execute_for_retry(None)) + self.assertTrue(cursor._should_record_execute_for_retry(error)) + + def test_autocommit_false_sql_commit_and_rollback_not_recorded(self): + """Successful and failed SQL COMMIT/ROLLBACK must not leak into the next transaction.""" + from google.cloud.spanner_dbapi.exceptions import OperationalError + + connection = self._make_connection(self.INSTANCE, mock.MagicMock()) + connection.autocommit = False + cursor = self._make_one(connection) + + cursor.execute("COMMIT") + self.assertEqual(cursor.transaction_helper._statement_result_details_list, []) + + cursor.execute("ROLLBACK") + self.assertEqual(cursor.transaction_helper._statement_result_details_list, []) + + with mock.patch.object( + connection, + "commit", + side_effect=OperationalError("commit failed"), + ): + with self.assertRaisesRegex(OperationalError, "commit failed"): + cursor.execute("COMMIT") + self.assertEqual(cursor.transaction_helper._statement_result_details_list, []) + + with mock.patch.object( + connection, + "rollback", + side_effect=OperationalError("rollback failed"), + ): + with self.assertRaisesRegex(OperationalError, "rollback failed"): + cursor.execute("ROLLBACK") + self.assertEqual(cursor.transaction_helper._statement_result_details_list, []) + + def test_autocommit_false_explicit_begin_retry_preserves_begin_marked(self): + """With autocommit=False, explicit begin() remains marked across retry.""" + from google.cloud.spanner_dbapi.exceptions import OperationalError + + connection = self._make_connection(self.INSTANCE, mock.MagicMock()) + connection.autocommit = False + connection.begin() + cursor = self._make_one(connection) + + metadata_mock = mock.Mock() + metadata_mock.trailing_metadata.return_value = {} + mock_result_set = mock.MagicMock() + mock_result_set.metadata.row_type = None + mock_result_set.stats.row_count_exact = 1 + + connection.run_statement = mock.Mock( + side_effect=[ + Aborted("Aborted", errors=[metadata_mock]), + mock_result_set, + ] + ) + + cursor.execute("UPDATE singers SET name = 'a' WHERE id = 1") + + self.assertTrue(connection._transaction_begin_marked) + with self.assertRaisesRegex( + OperationalError, "A transaction has already started" + ): + connection.begin() + + def test_autocommit_explicit_begin_multiple_aborts_and_first_statement_abort(self): + """Repeated Aborted errors on the first statement preserve begin state without crashing.""" + connection = self._make_connection(self.INSTANCE, mock.MagicMock()) + connection.autocommit = True + connection.begin() + cursor = self._make_one(connection) + + metadata_mock = mock.Mock() + metadata_mock.trailing_metadata.return_value = {} + mock_result_set = mock.MagicMock() + mock_result_set.metadata.row_type = None + mock_result_set.stats.row_count_exact = 1 + + connection.run_statement = mock.Mock( + side_effect=[ + Aborted("Aborted 1", errors=[metadata_mock]), + Aborted("Aborted 2", errors=[metadata_mock]), + mock_result_set, + ] + ) + + cursor.execute("UPDATE singers SET name = 'a' WHERE id = 1") + + self.assertTrue(connection._transaction_begin_marked) + self.assertTrue(connection._client_transaction_started) + self.assertEqual(connection.run_statement.call_count, 3) + connection.database.run_in_transaction.assert_not_called() + + def test_autocommit_explicit_begin_invalid_statement_caught_then_aborted(self): + """A caught Invalid Statement (_parsed_statement is None) is recorded and verified on retry.""" + from google.cloud.spanner_dbapi.exceptions import ProgrammingError + + connection = self._make_connection(self.INSTANCE, mock.MagicMock()) + connection.autocommit = True + connection.begin() + cursor = self._make_one(connection) + + with self.assertRaisesRegex(ProgrammingError, "Invalid Statement."): + cursor.execute("") + + self.assertEqual( + len(cursor.transaction_helper._statement_result_details_list), 1 + ) + + metadata_mock = mock.Mock() + metadata_mock.trailing_metadata.return_value = {} + mock_result_set = mock.MagicMock() + mock_result_set.metadata.row_type = None + mock_result_set.stats.row_count_exact = 1 + + connection.run_statement = mock.Mock( + side_effect=[ + Aborted("Aborted", errors=[metadata_mock]), + mock_result_set, + ] + ) + + cursor.execute("UPDATE singers SET name = 'a' WHERE id = 1") + + self.assertTrue(connection._transaction_begin_marked) + self.assertEqual(connection.run_statement.call_count, 2) + connection.database.run_in_transaction.assert_not_called() + + def test_reset_clears_parsed_statement_on_classify_failure(self): + """A classify_statement failure after COMMIT/DDL must not inherit stale _parsed_statement.""" + from google.cloud.spanner_dbapi.exceptions import Error + + connection = self._make_connection(self.INSTANCE, mock.MagicMock()) + connection.autocommit = True + connection.begin() + cursor = self._make_one(connection) + + cursor.execute( + "CREATE TABLE Singers (SingerId INT64 NOT NULL) PRIMARY KEY (SingerId)" + ) + self.assertIsNotNone(cursor._parsed_statement) + + with self.assertRaisesRegex(Error, "pyformat_args"): + cursor.execute("SELECT %s", (1, 2)) + + self.assertIsNone(cursor._parsed_statement) + self.assertEqual( + len(cursor.transaction_helper._statement_result_details_list), 1 + ) + + def test_caught_statement_failure_succeeds_on_retry_raises_retry_aborted(self): + """If a caught failing statement succeeds during replay, retry must raise RetryAborted.""" + from google.cloud.spanner_dbapi.exceptions import OperationalError, RetryAborted + from google.cloud.spanner_dbapi.transaction_helper import RETRY_ABORTED_ERROR + + connection = self._make_connection(self.INSTANCE, mock.MagicMock()) + connection.autocommit = True + connection.begin() + cursor = self._make_one(connection) + + with self.assertRaisesRegex( + OperationalError, "A transaction has already started" + ): + cursor.execute("BEGIN") + + metadata_mock = mock.Mock() + metadata_mock.trailing_metadata.return_value = {} + connection.run_statement = mock.Mock( + side_effect=Aborted("Aborted", errors=[metadata_mock]) + ) + + # Simulate the first BEGIN no longer failing on replay (e.g. if state diverged). + with mock.patch.object( + connection, + "begin", + return_value=None, + ): + with self.assertRaisesRegex(RetryAborted, RETRY_ABORTED_ERROR): + cursor.execute("UPDATE singers SET name = 'a' WHERE id = 1") diff --git a/packages/google-cloud-spanner/tests/unit/spanner_dbapi/test_parse_utils.py b/packages/google-cloud-spanner/tests/unit/spanner_dbapi/test_parse_utils.py index 4587e2f0fa83..16e35c2f51c3 100644 --- a/packages/google-cloud-spanner/tests/unit/spanner_dbapi/test_parse_utils.py +++ b/packages/google-cloud-spanner/tests/unit/spanner_dbapi/test_parse_utils.py @@ -716,3 +716,23 @@ def test_ensure_where_clause_is_idempotent(self): # Second invocation must be a no-op self.assertEqual(ensure_where_clause(with_where), with_where) self.assertNotIn("WHERE 1=1 WHERE 1=1", ensure_where_clause(with_where)) + + def test_client_side_statement_type_should_record_for_retry(self): + non_recorded_on_success = { + ClientSideStatementType.BEGIN, + ClientSideStatementType.COMMIT, + ClientSideStatementType.ROLLBACK, + } + non_recorded_on_failure = { + ClientSideStatementType.COMMIT, + ClientSideStatementType.ROLLBACK, + } + for statement_type in ClientSideStatementType: + self.assertEqual( + statement_type.should_record_success_for_retry, + statement_type not in non_recorded_on_success, + ) + self.assertEqual( + statement_type.should_record_failure_for_retry, + statement_type not in non_recorded_on_failure, + ) diff --git a/packages/google-cloud-spanner/tests/unit/spanner_dbapi/test_transaction_helper.py b/packages/google-cloud-spanner/tests/unit/spanner_dbapi/test_transaction_helper.py index f425b2b32f90..0945be7bf82c 100644 --- a/packages/google-cloud-spanner/tests/unit/spanner_dbapi/test_transaction_helper.py +++ b/packages/google-cloud-spanner/tests/unit/spanner_dbapi/test_transaction_helper.py @@ -16,6 +16,7 @@ from google.api_core.exceptions import Aborted +from google.cloud.spanner_dbapi.batch_dml_executor import BatchMode from google.cloud.spanner_dbapi.checksum import ResultsChecksum from google.cloud.spanner_dbapi.exceptions import RetryAborted from google.cloud.spanner_dbapi.parsed_statement import ParsedStatement, StatementType @@ -26,6 +27,7 @@ ResultType, TransactionRetryHelper, ) +from google.cloud.spanner_v1 import TransactionOptions def _get_checksum(row): @@ -617,3 +619,22 @@ def test_add_fetch_statement_for_retry_when_last_statement_is_not_fetch(self): self._under_test._statement_result_details_list, [execute_statement, expected_fetch_statement], ) + + def test_set_connection_for_retry_preserves_transaction_begin_marked(self): + """Verify _set_connection_for_retry preserves client-side begin state.""" + self._under_test._connection._spanner_transaction_started = True + self._under_test._connection._transaction_begin_marked = True + self._under_test._connection._transaction_isolation_level = ( + TransactionOptions.IsolationLevel.REPEATABLE_READ + ) + self._under_test._connection._batch_mode = BatchMode.DML + + self._under_test._set_connection_for_retry() + + self.assertFalse(self._under_test._connection._spanner_transaction_started) + self.assertTrue(self._under_test._connection._transaction_begin_marked) + self.assertEqual( + self._under_test._connection._transaction_isolation_level, + TransactionOptions.IsolationLevel.REPEATABLE_READ, + ) + self.assertEqual(self._under_test._connection._batch_mode, BatchMode.NONE)