diff --git a/packages/google-cloud-spanner/google/cloud/spanner_v1/testing/mock_spanner.py b/packages/google-cloud-spanner/google/cloud/spanner_v1/testing/mock_spanner.py index 38e028661c48..b254bb5b7040 100644 --- a/packages/google-cloud-spanner/google/cloud/spanner_v1/testing/mock_spanner.py +++ b/packages/google-cloud-spanner/google/cloud/spanner_v1/testing/mock_spanner.py @@ -13,11 +13,15 @@ # limitations under the License. import base64 import inspect +from collections import deque +from collections.abc import Iterable, Sequence from concurrent import futures from dataclasses import dataclass +from threading import Lock import grpc from google.protobuf import empty_pb2 +from google.protobuf.struct_pb2 import Value from google.rpc.code_pb2 import OK from grpc_status.rpc_status import _Status @@ -32,19 +36,151 @@ from google.cloud.spanner_v1.types.transaction import TransactionOptions +@dataclass +class ExecuteStreamingSqlErrorConfig: + """Configuration for a mid-stream ExecuteStreamingSql/StreamingRead error.""" + + partial_index: int + error: _Status + + +@dataclass +class PartialResultSetConfig: + """Options controlling how a ResultSet is split into PartialResultSets.""" + + max_values_per_chunk: int | None = None + max_string_chunk_length: int | None = None + emit_resume_tokens: bool = True + set_last_flag: bool = False + + def __post_init__(self) -> None: + if self.max_values_per_chunk is not None and self.max_values_per_chunk <= 0: + raise ValueError("max_values_per_chunk must be positive") + if ( + self.max_string_chunk_length is not None + and self.max_string_chunk_length <= 0 + ): + raise ValueError("max_string_chunk_length must be positive") + + +class _PartialResultSetBuilder: + """Accumulates Values into PartialResultSet chunks with Spanner token rules.""" + + def __init__( + self, + metadata: ResultSetMetadata, + chunk_config: PartialResultSetConfig, + ) -> None: + self._chunk_config = chunk_config + self._partials: list[result_set.PartialResultSet] = [] + self._token_counter = 0 + self._current_partial = result_set.PartialResultSet() + self._current_partial.metadata = ResultSetMetadata(metadata) + self._current_partial_pb = type(self._current_partial).pb(self._current_partial) + + def flush(self, ends_at_row_boundary: bool, chunked_value: bool) -> None: + """Finalize the current chunk and assign a resume_token only on row ends.""" + self._current_partial_pb.chunked_value = chunked_value + if ( + self._chunk_config.emit_resume_tokens + and ends_at_row_boundary + and not chunked_value + ): + self._token_counter += 1 + self._current_partial_pb.resume_token = f"{self._token_counter}".encode( + "utf-8" + ) + self._partials.append(self._current_partial) + self._current_partial = result_set.PartialResultSet() + self._current_partial_pb = type(self._current_partial).pb(self._current_partial) + + @staticmethod + def _split_string_cell( + cell: Value, max_string_chunk_length: int | None + ) -> list[Value]: + # Only top-level string_value cells are split automatically to cover + # chunked_value=True flows; callers needing nested list_value chunks + # can register explicit partials via add_execute_streaming_sql_results. + if ( + max_string_chunk_length is None + or cell.WhichOneof("kind") != "string_value" + or len(cell.string_value) <= max_string_chunk_length + ): + return [cell] + text = cell.string_value + return [ + Value(string_value=text[offset : offset + max_string_chunk_length]) + for offset in range(0, len(text), max_string_chunk_length) + ] + + def append_cell(self, cell: Value) -> None: + """Append one cell, flushing intermediate chunks for oversized strings.""" + pieces = self._split_string_cell( + cell, self._chunk_config.max_string_chunk_length + ) + for piece in pieces[:-1]: + self._current_partial_pb.values.append(piece) + self.flush(ends_at_row_boundary=False, chunked_value=True) + self._current_partial_pb.values.append(pieces[-1]) + + def append_row(self, row_values: Sequence[Value], is_last_row: bool) -> None: + """Append one row, flushing on chunk size limits or row boundaries.""" + column_count = len(row_values) + max_values = self._chunk_config.max_values_per_chunk + if column_count == 0: + if is_last_row or max_values is None: + self.flush(ends_at_row_boundary=True, chunked_value=False) + return + + for column_index, cell in enumerate(row_values): + self.append_cell(cell) + is_last_column = column_index == column_count - 1 + reached_chunk_limit = ( + max_values is not None + and len(self._current_partial_pb.values) >= max_values + ) + flush_at_row_end = is_last_column and (is_last_row or max_values is None) + if reached_chunk_limit or flush_at_row_end: + self.flush( + ends_at_row_boundary=is_last_column, + chunked_value=False, + ) + + def build( + self, stats: result_set.ResultSetStats + ) -> list[result_set.PartialResultSet]: + """Return finalized chunks with trailing stats and optional last flag.""" + if not self._partials: + self._partials.append(self._current_partial) + self._partials[-1].stats = stats + if self._chunk_config.set_last_flag: + self._partials[-1].last = True + return self._partials + + class MockSpanner: def __init__(self): self.results = {} + self.result_chunk_configs: dict[str, PartialResultSetConfig] = {} self.execute_streaming_sql_results = {} + self.execute_streaming_sql_errors: dict[ + str, deque[ExecuteStreamingSqlErrorConfig] + ] = {} + self._execute_streaming_sql_errors_lock = Lock() self.partition_results = {} self.errors = {} self.headers = {} def clear_results(self): self.results = {} + self.result_chunk_configs = {} self.execute_streaming_sql_results = {} + with self._execute_streaming_sql_errors_lock: + self.execute_streaming_sql_errors = {} self.partition_results = {} self.errors = {} + if hasattr(self, "_errors_list"): + self._errors_list = {} self.headers = {} def add_header(self, method: str, header: str, value: str): @@ -57,8 +193,26 @@ def send_initial_metadata(self, method_name: str, context): if headers: context.send_initial_metadata(tuple(headers)) - def add_result(self, sql: str, result: result_set.ResultSet): - self.results[sql.lower().strip()] = result + def add_result( + self, + sql: str, + result: result_set.ResultSet, + chunk_config: PartialResultSetConfig | None = None, + ) -> None: + normalized_sql = sql.lower().strip() + self.results[normalized_sql] = result + # Ensure re-registering via add_result overrides prior explicit partials. + self.execute_streaming_sql_results.pop(normalized_sql, None) + if chunk_config is not None: + self.result_chunk_configs[normalized_sql] = chunk_config + else: + self.result_chunk_configs.pop(normalized_sql, None) + + @staticmethod + def read_request_sql(table: str, columns: Iterable[str]) -> str: + """Build the canonical synthetic SELECT query key for a ReadRequest.""" + columns_clause = ", ".join(columns) if columns else "*" + return f"SELECT {columns_clause} FROM {table}" def add_partition_result(self, sql: str, result: spanner.PartitionResponse): self.partition_results[sql.lower().strip()] = result @@ -68,6 +222,40 @@ def add_execute_streaming_sql_results( ): self.execute_streaming_sql_results[sql.lower().strip()] = partial_result_sets + def add_execute_streaming_sql_error( + self, sql: str, partial_index: int, error: _Status + ) -> None: + """Queue an error to abort streaming after yielding partial_index chunks.""" + if partial_index < 0: + raise ValueError("partial_index must be non-negative") + normalized_sql = sql.lower().strip() + config = ExecuteStreamingSqlErrorConfig( + partial_index=partial_index, error=error + ) + with self._execute_streaming_sql_errors_lock: + if normalized_sql not in self.execute_streaming_sql_errors: + self.execute_streaming_sql_errors[normalized_sql] = deque() + self.execute_streaming_sql_errors[normalized_sql].append(config) + + def pop_execute_streaming_sql_error( + self, sql: str + ) -> ExecuteStreamingSqlErrorConfig | None: + """Pop the next queued mid-stream error for the given SQL, if any.""" + normalized_sql = sql.lower().strip() + with self._execute_streaming_sql_errors_lock: + errors = self.execute_streaming_sql_errors.get(normalized_sql) + if errors: + return errors.popleft() + return None + + def has_execute_streaming_sql_result(self, sql: str) -> bool: + """Return whether a result or partial stream is registered for the SQL.""" + normalized_sql = sql.lower().strip() + return ( + normalized_sql in self.execute_streaming_sql_results + or normalized_sql in self.results + ) + def get_result(self, sql: str) -> result_set.ResultSet: result = self.results.get(sql.lower().strip()) if result is None: @@ -88,8 +276,8 @@ def add_error(self, method: str, error: _Status): self._errors_list[method].append(error) self.errors[method] = error - def pop_error(self, context): - name = inspect.currentframe().f_back.f_code.co_name + def pop_error(self, context, method_name: str | None = None): + name = method_name or inspect.currentframe().f_back.f_code.co_name if hasattr(self, "_errors_list") and name in self._errors_list: if self._errors_list[name]: error = self._errors_list[name].pop(0) @@ -105,34 +293,47 @@ def pop_error(self, context): def get_execute_streaming_sql_results( self, sql: str, started_transaction: transaction.Transaction ) -> list[result_set.PartialResultSet]: - if self.execute_streaming_sql_results.get(sql.lower().strip()): - partials = self.execute_streaming_sql_results[sql.lower().strip()] + normalized_sql = sql.lower().strip() + if normalized_sql in self.execute_streaming_sql_results: + partials = list(self.execute_streaming_sql_results[normalized_sql]) + if started_transaction and partials: + first_partial = result_set.PartialResultSet() + type(first_partial).pb(first_partial).CopyFrom( + type(partials[0]).pb(partials[0]) + ) + partials[0] = first_partial else: partials = self.get_result_as_partial_result_sets(sql) - if started_transaction: + if started_transaction and partials: partials[0].metadata.transaction = started_transaction return partials def get_result_as_partial_result_sets( self, sql: str ) -> list[result_set.PartialResultSet]: + normalized_sql = sql.lower().strip() result: result_set.ResultSet = self.get_result(sql) - partials = [] - first = True - if len(result.rows) == 0: - partial = result_set.PartialResultSet() - partial.metadata = ResultSetMetadata(result.metadata) - partials.append(partial) - else: - for row in result.rows: - partial = result_set.PartialResultSet() - if first: - partial.metadata = ResultSetMetadata(result.metadata) - first = False - partial.values.extend(row) - partials.append(partial) - partials[len(partials) - 1].stats = result.stats - return partials + chunk_config = self.result_chunk_configs.get( + normalized_sql, PartialResultSetConfig() + ) + return self._split_result_into_partial_result_sets(result, chunk_config) + + @staticmethod + def _split_result_into_partial_result_sets( + result: result_set.ResultSet, chunk_config: PartialResultSetConfig + ) -> list[result_set.PartialResultSet]: + """Convert a ResultSet into PartialResultSets with row-boundary resume tokens. + + Auto-chunking emits resume_token only when emit_resume_tokens is True at a + non-chunked row boundary; callers testing mid-row or chunked_value=True + resume tokens can supply explicit chunks via add_execute_streaming_sql_results. + """ + result_pb = type(result).pb(result) + builder = _PartialResultSetBuilder(result.metadata, chunk_config) + total_rows = len(result_pb.rows) + for row_index, row in enumerate(result_pb.rows): + builder.append_row(row.values, is_last_row=(row_index == total_rows - 1)) + return builder.build(result.stats) @dataclass @@ -174,6 +375,7 @@ def add_batch_dml_response_status(self, status, include_transaction_id=True): def clear_results(self): self.mock_spanner.clear_results() + self._batch_dml_response_configs = [] def CreateSession(self, request, context): self._requests.append(request) @@ -222,16 +424,99 @@ def ExecuteSql(self, request, context): result.metadata.transaction = started_transaction return result - def ExecuteStreamingSql(self, request, context): + @staticmethod + def _advance_past_resume_token( + partials: Iterable[result_set.PartialResultSet], resume_token: bytes + ) -> Iterable[result_set.PartialResultSet] | None: + """Advance past the chunk matching resume_token, returning remaining chunks or None.""" + iterator = iter(partials) + for partial in iterator: + if partial.resume_token == resume_token: + return iterator + return None + + @staticmethod + def _read_request_to_sql(request: spanner.ReadRequest) -> str: + """Convert a ReadRequest to a SELECT query key for MockSpanner lookup. + + Read results share MockSpanner's SQL-keyed registry, matched by table and + columns only (key_set, index, limit, and partition_token are ignored). + """ + return MockSpanner.read_request_sql(request.table, request.columns) + + def _execute_streaming( + self, + method_name: str, + sql: str, + request, + context, + allow_missing_result: bool = False, + ): + """Stream PartialResultSets for ExecuteStreamingSql or StreamingRead. + + Results and queued errors are keyed by normalized SQL (ignoring + partition_token), and precommit_token fields are emitted only when + present on explicitly registered PartialResultSets. + """ self._requests.append(request) - self.mock_spanner.pop_error(context) - self.mock_spanner.send_initial_metadata("ExecuteStreamingSql", context) + self.mock_spanner.pop_error(context, method_name=method_name) + self.mock_spanner.send_initial_metadata(method_name, context) + if request.resume_token and type(request.transaction).pb( + request.transaction + ).HasField("begin"): + context.abort( + grpc.StatusCode.INVALID_ARGUMENT, + "Cannot combine begin transaction with resume_token.", + ) + return + stream_error = self.mock_spanner.pop_execute_streaming_sql_error(sql) + if stream_error is not None and stream_error.partial_index == 0: + context.abort_with_status(stream_error.error) + return started_transaction = self.__maybe_create_transaction(request) - partials = self.mock_spanner.get_execute_streaming_sql_results( - request.sql, started_transaction - ) - for result in partials: + if ( + allow_missing_result + and not self.mock_spanner.has_execute_streaming_sql_result(sql) + ): + partials: Iterable[result_set.PartialResultSet] = [ + result_set.PartialResultSet(), + result_set.PartialResultSet(), + ] + if started_transaction: + partials[0].metadata.transaction = started_transaction + else: + partials = self.mock_spanner.get_execute_streaming_sql_results( + sql, started_transaction + ) + if request.resume_token: + resumed_partials = self._advance_past_resume_token( + partials, request.resume_token + ) + if resumed_partials is None: + context.abort( + grpc.StatusCode.INVALID_ARGUMENT, + "Invalid resume_token.", + ) + return + partials = resumed_partials + for index, result in enumerate(partials): + if stream_error is not None and index == stream_error.partial_index: + context.abort_with_status(stream_error.error) + return yield result + # Errors with partial_index >= len(partials) abort after the final chunk + # (even when last=True), allowing tests to exercise trailing stream errors. + if stream_error is not None: + context.abort_with_status(stream_error.error) + + def ExecuteStreamingSql(self, request, context): + yield from self._execute_streaming( + "ExecuteStreamingSql", + request.sql, + request, + context, + allow_missing_result=False, + ) def ExecuteBatchDml(self, request, context): self._requests.append(request) @@ -274,11 +559,14 @@ def Read(self, request, context): return result_set.ResultSet() def StreamingRead(self, request, context): - self._requests.append(request) - self.mock_spanner.pop_error(context) - self.mock_spanner.send_initial_metadata("StreamingRead", context) - for result in [result_set.PartialResultSet(), result_set.PartialResultSet()]: - yield result + sql = self._read_request_to_sql(request) + yield from self._execute_streaming( + "StreamingRead", + sql, + request, + context, + allow_missing_result=True, + ) def BeginTransaction(self, request, context): self._requests.append(request) diff --git a/packages/google-cloud-spanner/tests/mockserver_tests/mock_server_test_base.py b/packages/google-cloud-spanner/tests/mockserver_tests/mock_server_test_base.py index 1b4baec79ab5..525f1bd434c0 100644 --- a/packages/google-cloud-spanner/tests/mockserver_tests/mock_server_test_base.py +++ b/packages/google-cloud-spanner/tests/mockserver_tests/mock_server_test_base.py @@ -42,6 +42,8 @@ from google.cloud.spanner_v1.instance import Instance from google.cloud.spanner_v1.testing.mock_database_admin import DatabaseAdminServicer from google.cloud.spanner_v1.testing.mock_spanner import ( + MockSpanner, + PartialResultSetConfig, SpannerServicer, start_mock_server, ) @@ -50,38 +52,41 @@ current_service = ContextVar("current_service", default=None) -# Creates an aborted status with the smallest possible retry delay. -def aborted_status() -> _Status: - error = status_pb2.Status( - code=code_pb2.ABORTED, - message="Transaction was aborted.", - ) - retry_info = RetryInfo(retry_delay=Duration(seconds=0, nanos=1)) - status = _Status( +def _make_status(code: int, message: str, with_retry_info: bool = False) -> _Status: + """Create a gRPC status with optional minimal RetryInfo.""" + error = status_pb2.Status(code=code, message=message) + trailing_metadata = [("grpc-status-details-bin", error.SerializeToString())] + if with_retry_info: + retry_info = RetryInfo(retry_delay=Duration(seconds=0, nanos=1)) + trailing_metadata.append( + ("google.rpc.retryinfo-bin", retry_info.SerializeToString()) + ) + return _Status( code=code_to_grpc_status_code(error.code), details=error.message, - trailing_metadata=( - ("grpc-status-details-bin", error.SerializeToString()), - ( - "google.rpc.retryinfo-bin", - retry_info.SerializeToString(), - ), - ), + trailing_metadata=tuple(trailing_metadata), ) - return status -def invalid_argument_status() -> _Status: - error = status_pb2.Status( - code=code_pb2.INVALID_ARGUMENT, - message="Invalid argument.", - ) - status = _Status( - code=code_to_grpc_status_code(error.code), - details=error.message, - trailing_metadata=(("grpc-status-details-bin", error.SerializeToString()),), +# Creates an aborted status with the smallest possible retry delay. +def aborted_status() -> _Status: + return _make_status( + code_pb2.ABORTED, "Transaction was aborted.", with_retry_info=True ) - return status + + +def invalid_argument_status() -> _Status: + return _make_status(code_pb2.INVALID_ARGUMENT, "Invalid argument.") + + +def deadline_exceeded_status() -> _Status: + return _make_status(code_pb2.DEADLINE_EXCEEDED, "Deadline exceeded.") + + +def internal_server_error_status( + message: str = "Internal server error.", +) -> _Status: + return _make_status(code_pb2.INTERNAL, message) def _make_partial_result_sets( @@ -101,29 +106,19 @@ def _make_partial_result_sets( for value in result["values"]: partial_result_set.values.append(_make_value_pb(value)) partial_result_set.last = result.get("last") or False + partial_result_set.chunked_value = result.get("chunked_value") or False + resume_token = result.get("resume_token") + if resume_token is not None: + partial_result_set.resume_token = resume_token partial_result_sets.append(partial_result_set) return partial_result_sets # Creates an UNAVAILABLE status with the smallest possible retry delay. def unavailable_status() -> _Status: - error = status_pb2.Status( - code=code_pb2.UNAVAILABLE, - message="Service unavailable.", + return _make_status( + code_pb2.UNAVAILABLE, "Service unavailable.", with_retry_info=True ) - retry_info = RetryInfo(retry_delay=Duration(seconds=0, nanos=1)) - status = _Status( - code=code_to_grpc_status_code(error.code), - details=error.message, - trailing_metadata=( - ("grpc-status-details-bin", error.SerializeToString()), - ( - "google.rpc.retryinfo-bin", - retry_info.SerializeToString(), - ), - ), - ) - return status def get_spanner_service(): @@ -143,8 +138,14 @@ def add_header(method: str, header: str, value: str): get_spanner_service().mock_spanner.add_header(method, header, value) -def add_result(sql: str, result: result_set.ResultSet): - get_spanner_service().mock_spanner.add_result(sql, result) +def add_result( + sql: str, + result: result_set.ResultSet, + chunk_config: PartialResultSetConfig | None = None, +): + get_spanner_service().mock_spanner.add_result( + sql, result, chunk_config=chunk_config + ) def add_update_count( @@ -170,31 +171,57 @@ def add_execute_streaming_sql_results( ) -def add_single_result( - sql: str, column_name: str, type_code: spanner_type.TypeCode, row -): +def add_execute_streaming_sql_error( + sql: str, partial_index: int, error: _Status +) -> None: + """Queue a mid-stream error for ExecuteStreamingSql on the active mock server.""" + get_spanner_service().mock_spanner.add_execute_streaming_sql_error( + sql, partial_index, error + ) + + +def add_streaming_read_error( + table: str, columns: list[str], partial_index: int, error: _Status +) -> None: + """Queue a mid-stream error for StreamingRead on the active mock server.""" + sql = MockSpanner.read_request_sql(table, columns) + add_execute_streaming_sql_error(sql, partial_index, error) + + +def add_multi_column_result( + sql: str, + columns: list[tuple[str, spanner_type.TypeCode]], + rows: list[tuple], + chunk_config: PartialResultSetConfig | None = None, +) -> None: + """Register a multi-column ResultSet with optional PartialResultSet chunking config.""" + fields = [ + spanner_type.StructType.Field( + dict(name=column_name, type=spanner_type.Type(dict(code=type_code))) + ) + for column_name, type_code in columns + ] result = result_set.ResultSet( dict( metadata=result_set.ResultSetMetadata( - dict( - row_type=spanner_type.StructType( - dict( - fields=[ - spanner_type.StructType.Field( - dict( - name=column_name, - type=spanner_type.Type(dict(code=type_code)), - ) - ) - ] - ) - ) - ) - ), + dict(row_type=spanner_type.StructType(dict(fields=fields))) + ) ) ) - result.rows.extend(row) - get_spanner_service().mock_spanner.add_result(sql, result) + result.rows.extend(rows) + add_result(sql, result, chunk_config=chunk_config) + + +def add_single_result( + sql: str, + column_name: str, + type_code: spanner_type.TypeCode, + row, + chunk_config: PartialResultSetConfig | None = None, +): + add_multi_column_result( + sql, [(column_name, type_code)], row, chunk_config=chunk_config + ) class MockServerTestBase(unittest.TestCase): @@ -413,6 +440,7 @@ async def asyncSetUp(self): async def asyncTearDown(self): AsyncMockServerTestBase.spanner_service.clear_requests() + AsyncMockServerTestBase.spanner_service.clear_results() AsyncMockServerTestBase.database_admin_service.clear_requests() @property diff --git a/packages/google-cloud-spanner/tests/mockserver_tests/test_aborted_transaction.py b/packages/google-cloud-spanner/tests/mockserver_tests/test_aborted_transaction.py index 62651978c8bc..dc21b36d90ea 100644 --- a/packages/google-cloud-spanner/tests/mockserver_tests/test_aborted_transaction.py +++ b/packages/google-cloud-spanner/tests/mockserver_tests/test_aborted_transaction.py @@ -19,6 +19,8 @@ CommitRequest, ExecuteBatchDmlRequest, ExecuteSqlRequest, + KeySet, + ReadRequest, TypeCode, ) from google.cloud.spanner_v1.database_sessions_manager import TransactionType @@ -28,7 +30,9 @@ MockServerTestBase, aborted_status, add_error, + add_execute_streaming_sql_error, add_single_result, + add_streaming_read_error, add_update_count, ) @@ -95,6 +99,74 @@ def test_run_in_transaction_query_aborted(self): TransactionType.READ_WRITE, ) + def test_run_in_transaction_query_mid_stream_aborted(self): + # Verify mid-stream Aborted on ExecuteStreamingSql triggers full transaction + # retry after yielding partial rows from the first attempt. + sql = "select value from my_table where id=1" + add_single_result( + sql, + "value", + TypeCode.STRING, + [("row1",), ("row2",)], + ) + add_execute_streaming_sql_error(sql, 1, aborted_status()) + + observed_attempts = [] + partial_rows_seen = [] + + def _query_tracking_partials(transaction: Transaction): + attempt_rows = [] + for row in transaction.execute_sql(sql): + attempt_rows.append(row) + partial_rows_seen.append(row) + observed_attempts.append(attempt_rows) + return attempt_rows + + result = self.database.run_in_transaction(_query_tracking_partials) + self.assertEqual([["row1"], ["row2"]], result) + self.assertEqual([[["row1"], ["row2"]]], observed_attempts) + self.assertEqual([["row1"], ["row1"], ["row2"]], partial_rows_seen) + requests = self.spanner_service.requests + self.assert_requests_sequence( + requests, + [ExecuteSqlRequest, ExecuteSqlRequest, CommitRequest], + TransactionType.READ_WRITE, + ) + + def test_run_in_transaction_streaming_read_mid_stream_aborted(self): + # Verify mid-stream Aborted on StreamingRead triggers full transaction retry + # after yielding partial rows from the first attempt. + add_single_result( + "SELECT value FROM my_table", + "value", + TypeCode.STRING, + [("row1",), ("row2",)], + ) + add_streaming_read_error("my_table", ["value"], 1, aborted_status()) + + partial_rows_seen = [] + + def _read_tracking_partials(transaction: Transaction): + attempt_rows = [] + for row in transaction.read( + table="my_table", + columns=["value"], + keyset=KeySet(all_=True), + ): + attempt_rows.append(row) + partial_rows_seen.append(row) + return attempt_rows + + result = self.database.run_in_transaction(_read_tracking_partials) + self.assertEqual([["row1"], ["row2"]], result) + self.assertEqual([["row1"], ["row1"], ["row2"]], partial_rows_seen) + requests = self.spanner_service.requests + self.assert_requests_sequence( + requests, + [ReadRequest, ReadRequest, CommitRequest], + TransactionType.READ_WRITE, + ) + def test_run_in_transaction_batch_dml_aborted(self): add_update_count("update my_table set my_col=1 where id=1", 1) add_update_count("update my_table set my_col=1 where id=2", 1) diff --git a/packages/google-cloud-spanner/tests/mockserver_tests/test_basics.py b/packages/google-cloud-spanner/tests/mockserver_tests/test_basics.py index bc2120a406f9..255bbf8cc0d7 100644 --- a/packages/google-cloud-spanner/tests/mockserver_tests/test_basics.py +++ b/packages/google-cloud-spanner/tests/mockserver_tests/test_basics.py @@ -12,6 +12,14 @@ # See the License for the specific language governing permissions and # limitations under the License. +import unittest +from contextlib import asynccontextmanager + +import grpc.aio +from google.api_core import exceptions +from google.api_core.client_options import ClientOptions +from google.auth.credentials import AnonymousCredentials + from google.cloud.spanner_admin_database_v1.types import spanner_database_admin from google.cloud.spanner_dbapi import Connection from google.cloud.spanner_dbapi.parsed_statement import AutocommitDmlMode @@ -19,25 +27,53 @@ BeginTransactionRequest, ExecuteBatchDmlRequest, ExecuteSqlRequest, + KeySet, + ReadRequest, TransactionOptions, + TransactionSelector, TypeCode, ) +from google.cloud.spanner_v1._async.client import Client as AsyncClient +from google.cloud.spanner_v1._async.pool import FixedSizePool as AsyncFixedSizePool from google.cloud.spanner_v1.database_sessions_manager import TransactionType -from google.cloud.spanner_v1.testing.mock_spanner import SpannerServicer +from google.cloud.spanner_v1.services.spanner.async_client import SpannerAsyncClient +from google.cloud.spanner_v1.services.spanner.transports import ( + SpannerGrpcAsyncIOTransport, +) +from google.cloud.spanner_v1.testing.mock_spanner import ( + PartialResultSetConfig, + SpannerServicer, +) from google.cloud.spanner_v1.transaction import Transaction from tests._helpers import is_multiplexed_enabled from tests.mockserver_tests.mock_server_test_base import ( + AsyncMockServerTestBase, MockServerTestBase, _make_partial_result_sets, + aborted_status, add_error, + add_execute_streaming_sql_error, add_execute_streaming_sql_results, + add_multi_column_result, add_select1_result, add_single_result, + add_streaming_read_error, add_update_count, + deadline_exceeded_status, + internal_server_error_status, + invalid_argument_status, unavailable_status, ) +def _requests_of_type(spanner_service: SpannerServicer, request_type: type) -> list: + return [ + request + for request in spanner_service.requests + if isinstance(request, request_type) + ] + + class TestBasics(MockServerTestBase): def test_select1(self): add_select1_result() @@ -223,6 +259,842 @@ def test_execute_streaming_sql_last_field(self): TransactionType.READ_ONLY, ) + def test_execute_streaming_sql_mid_stream_error_at_zero(self): + # Verify partial_index=0 aborts the stream before any rows are yielded. + sql = "select id from my_table" + add_single_result(sql, "id", TypeCode.INT64, [("1",), ("2",)]) + add_execute_streaming_sql_error(sql, 0, deadline_exceeded_status()) + with self.database.snapshot() as snapshot: + results = snapshot.execute_sql(sql) + row_iterator = iter(results) + with self.assertRaisesRegex( + exceptions.DeadlineExceeded, "Deadline exceeded." + ): + next(row_iterator) + + def test_execute_streaming_sql_mid_stream_error_after_partial_rows(self): + # Verify partial_index=1 yields the first chunk's row before failing mid-stream. + sql = "select id from my_table" + add_single_result(sql, "id", TypeCode.INT64, [("1",), ("2",), ("3",)]) + add_execute_streaming_sql_error(sql, 1, deadline_exceeded_status()) + with self.database.snapshot() as snapshot: + results = snapshot.execute_sql(sql) + row_iterator = iter(results) + self.assertEqual([1], next(row_iterator)) + with self.assertRaisesRegex( + exceptions.DeadlineExceeded, "Deadline exceeded." + ): + next(row_iterator) + + def test_execute_streaming_sql_mid_stream_error_after_all_chunks(self): + # Verify partial_index >= len(chunks) yields every row then fails at stream end. + sql = "select id from my_table" + add_single_result(sql, "id", TypeCode.INT64, [("1",), ("2",)]) + add_execute_streaming_sql_error(sql, 2, internal_server_error_status()) + with self.database.snapshot() as snapshot: + results = snapshot.execute_sql(sql) + row_iterator = iter(results) + self.assertEqual([1], next(row_iterator)) + self.assertEqual([2], next(row_iterator)) + with self.assertRaisesRegex( + exceptions.InternalServerError, "Internal server error." + ): + next(row_iterator) + + def test_execute_streaming_sql_mid_stream_unavailable_resumes(self): + # Verify mid-stream UNAVAILABLE resumes via chunk 0's resume_token without losing rows. + sql = "select id from my_table" + add_single_result(sql, "id", TypeCode.INT64, [("1",), ("2",), ("3",)]) + add_execute_streaming_sql_error(sql, 1, unavailable_status()) + with self.database.snapshot() as snapshot: + rows = list(snapshot.execute_sql(sql)) + self.assertEqual([[1], [2], [3]], rows) + execute_requests = _requests_of_type(self.spanner_service, ExecuteSqlRequest) + self.assertEqual(2, len(execute_requests)) + self.assertEqual(b"", execute_requests[0].resume_token) + self.assertEqual(b"1", execute_requests[1].resume_token) + + def test_execute_streaming_sql_error_queue_and_validation(self): + # Verify negative partial_index validation, FIFO per-call error dequeuing, + # normal fallback once drained, and cleanup via clear_results(). + sql = "select id from my_table" + add_single_result(sql, "id", TypeCode.INT64, [("1",), ("2",)]) + with self.assertRaisesRegex(ValueError, "partial_index must be non-negative"): + add_execute_streaming_sql_error(sql, -1, aborted_status()) + + add_execute_streaming_sql_error(sql, 1, deadline_exceeded_status()) + add_execute_streaming_sql_error(sql, 0, invalid_argument_status()) + + with self.database.snapshot() as snapshot: + first_iter = iter(snapshot.execute_sql(sql)) + self.assertEqual([1], next(first_iter)) + with self.assertRaisesRegex( + exceptions.DeadlineExceeded, "Deadline exceeded." + ): + next(first_iter) + + with self.database.snapshot() as snapshot: + second_iter = iter(snapshot.execute_sql(sql)) + with self.assertRaisesRegex( + exceptions.InvalidArgument, "Invalid argument." + ): + next(second_iter) + + with self.database.snapshot() as snapshot: + self.assertEqual([[1], [2]], list(snapshot.execute_sql(sql))) + + add_execute_streaming_sql_error(sql, 0, aborted_status()) + self.spanner_service.clear_results() + add_single_result(sql, "id", TypeCode.INT64, [("1",)]) + with self.database.snapshot() as snapshot: + self.assertEqual([[1]], list(snapshot.execute_sql(sql))) + + def test_execute_streaming_sql_mid_stream_error_with_explicit_partials(self): + # Verify mid-stream error injection works with custom PartialResultSet streams. + sql = "select id from my_table" + partials = _make_partial_result_sets( + [("id", TypeCode.INT64)], + [ + {"values": ["1"], "resume_token": b"tok1"}, + {"values": ["2"], "resume_token": b"tok2", "last": True}, + ], + ) + add_execute_streaming_sql_results(sql, partials) + add_execute_streaming_sql_error(sql, 1, invalid_argument_status()) + with self.database.snapshot() as snapshot: + row_iterator = iter(snapshot.execute_sql(sql)) + self.assertEqual([1], next(row_iterator)) + with self.assertRaisesRegex( + exceptions.InvalidArgument, "Invalid argument." + ): + next(row_iterator) + + def test_streaming_read_mid_stream_error_and_resumption(self): + # Verify StreamingRead supports both mid-stream failures and resume_token recovery. + add_multi_column_result( + "SELECT id, name FROM my_table", + [("id", TypeCode.INT64), ("name", TypeCode.STRING)], + [("1", "Alice"), ("2", "Bob"), ("3", "Charlie")], + ) + add_streaming_read_error( + "my_table", ["id", "name"], 1, deadline_exceeded_status() + ) + with self.database.snapshot() as snapshot: + row_iterator = iter( + snapshot.read( + table="my_table", + columns=["id", "name"], + keyset=KeySet(all_=True), + ) + ) + self.assertEqual([1, "Alice"], next(row_iterator)) + with self.assertRaisesRegex( + exceptions.DeadlineExceeded, "Deadline exceeded." + ): + next(row_iterator) + + self.spanner_service.clear_requests() + add_streaming_read_error("my_table", ["id", "name"], 1, unavailable_status()) + with self.database.snapshot() as snapshot: + rows = list( + snapshot.read( + table="my_table", + columns=["id", "name"], + keyset=KeySet(all_=True), + ) + ) + self.assertEqual([[1, "Alice"], [2, "Bob"], [3, "Charlie"]], rows) + + read_requests = _requests_of_type(self.spanner_service, ReadRequest) + self.assertEqual(2, len(read_requests)) + self.assertEqual(b"", read_requests[0].resume_token) + self.assertEqual(b"1", read_requests[1].resume_token) + + def test_partial_result_set_mid_row_splitting_and_resume_tokens(self): + # Verify max_values_per_chunk omits resume_token on mid-row chunks and only + # emits tokens on row boundaries, restarting from b"" before a token arrives. + sql = "select id, name, role from members" + config = PartialResultSetConfig(max_values_per_chunk=2) + add_multi_column_result( + sql, + [ + ("id", TypeCode.INT64), + ("name", TypeCode.STRING), + ("role", TypeCode.STRING), + ], + [ + ("1", "Alice", "admin"), + ("2", "Bob", "user"), + ("3", "Charlie", "guest"), + ], + chunk_config=config, + ) + + partials = self.spanner_service.mock_spanner.get_result_as_partial_result_sets( + sql + ) + # 9 values with max 2 values/chunk: + # [1, Alice] (mid-row -> no token), [admin, 2] (mid-row -> no token), + # [Bob, user] (row boundary -> b"1"), [3, Charlie] (mid-row -> no token), + # [guest] (row boundary -> b"2") + self.assertEqual(5, len(partials)) + self.assertEqual( + [b"", b"", b"1", b"", b"2"], + [partial.resume_token for partial in partials], + ) + self.assertTrue(all(not partial.chunked_value for partial in partials)) + + # Unavailable after mid-row chunk 0 (no resume_token received yet) restarts from scratch. + add_execute_streaming_sql_error(sql, 1, unavailable_status()) + with self.database.snapshot() as snapshot: + rows = list(snapshot.execute_sql(sql)) + self.assertEqual( + [[1, "Alice", "admin"], [2, "Bob", "user"], [3, "Charlie", "guest"]], + rows, + ) + execute_requests = _requests_of_type(self.spanner_service, ExecuteSqlRequest) + self.assertEqual(2, len(execute_requests)) + self.assertEqual(b"", execute_requests[1].resume_token) + + # Unavailable after chunk 2 (row 2 boundary, resume_token=b"1") resumes from chunk 3. + self.spanner_service.clear_requests() + add_execute_streaming_sql_error(sql, 3, unavailable_status()) + with self.database.snapshot() as snapshot: + rows = list(snapshot.execute_sql(sql)) + self.assertEqual( + [[1, "Alice", "admin"], [2, "Bob", "user"], [3, "Charlie", "guest"]], + rows, + ) + execute_requests = _requests_of_type(self.spanner_service, ExecuteSqlRequest) + self.assertEqual(2, len(execute_requests)) + self.assertEqual(b"1", execute_requests[1].resume_token) + + def test_partial_result_set_chunked_values_and_resume_tokens(self): + # Verify max_string_chunk_length sets chunked_value=True without resume_token on + # intermediate string splits and resumes from b"" until a row end emits a token. + sql = "select id, payload from docs" + config = PartialResultSetConfig(max_string_chunk_length=4) + add_multi_column_result( + sql, + [("id", TypeCode.STRING), ("payload", TypeCode.STRING)], + [("id1", "hello world"), ("id2", "abcdef")], + chunk_config=config, + ) + + partials = self.spanner_service.mock_spanner.get_result_as_partial_result_sets( + sql + ) + # Row 1: ["id1", "hell"] (chunked -> no token), ["o wo"] (chunked -> no token), + # ["rld"] (row end -> b"1") + # Row 2: ["id2", "abcd"] (chunked -> no token), ["ef"] (row end -> b"2") + self.assertEqual(5, len(partials)) + self.assertEqual( + [True, True, False, True, False], + [partial.chunked_value for partial in partials], + ) + self.assertEqual( + [b"", b"", b"1", b"", b"2"], + [partial.resume_token for partial in partials], + ) + + # Unavailable during chunked value (before resume_token) restarts cleanly. + add_execute_streaming_sql_error(sql, 1, unavailable_status()) + with self.database.snapshot() as snapshot: + rows = list(snapshot.execute_sql(sql)) + self.assertEqual([["id1", "hello world"], ["id2", "abcdef"]], rows) + execute_requests = _requests_of_type(self.spanner_service, ExecuteSqlRequest) + self.assertEqual(b"", execute_requests[1].resume_token) + + # Unavailable after row 1 completed (resume_token=b"1") resumes at row 2. + self.spanner_service.clear_requests() + add_execute_streaming_sql_error(sql, 3, unavailable_status()) + with self.database.snapshot() as snapshot: + rows = list(snapshot.execute_sql(sql)) + self.assertEqual([["id1", "hello world"], ["id2", "abcdef"]], rows) + execute_requests = _requests_of_type(self.spanner_service, ExecuteSqlRequest) + self.assertEqual(b"1", execute_requests[1].resume_token) + + def test_partial_result_set_without_resume_tokens_and_explicit_chunked_value(self): + # Verify emit_resume_tokens=False suppresses tokens (forcing client buffering + # until failure) and manual _make_partial_result_sets chunked_value reassembly. + sql = "select id, text from notes" + add_multi_column_result( + sql, + [("id", TypeCode.INT64), ("text", TypeCode.STRING)], + [("1", "one"), ("2", "two")], + chunk_config=PartialResultSetConfig(emit_resume_tokens=False), + ) + partials = self.spanner_service.mock_spanner.get_result_as_partial_result_sets( + sql + ) + self.assertEqual([b"", b""], [partial.resume_token for partial in partials]) + + # Without resume_token on chunk 0, _restart_on_unavailable buffers until chunk 1 errors. + add_execute_streaming_sql_error(sql, 1, deadline_exceeded_status()) + with self.database.snapshot() as snapshot: + row_iterator = iter(snapshot.execute_sql(sql)) + with self.assertRaisesRegex( + exceptions.DeadlineExceeded, "Deadline exceeded." + ): + next(row_iterator) + + # With emit_resume_tokens=False, UNAVAILABLE drops the buffered chunk and + # restarts from b"" without duplicating rows. + self.spanner_service.clear_requests() + add_execute_streaming_sql_error(sql, 1, unavailable_status()) + with self.database.snapshot() as snapshot: + self.assertEqual([[1, "one"], [2, "two"]], list(snapshot.execute_sql(sql))) + execute_requests = _requests_of_type(self.spanner_service, ExecuteSqlRequest) + self.assertEqual( + [b"", b""], [request.resume_token for request in execute_requests] + ) + + # Verify _make_partial_result_sets supports chunked_value=True with a + # non-empty resume_token and resumes cleanly mid-string on UNAVAILABLE. + explicit_partials = _make_partial_result_sets( + [("id", TypeCode.INT64), ("text", TypeCode.STRING)], + [ + { + "values": ["1", "hel"], + "chunked_value": True, + "resume_token": b"mid_tok", + }, + {"values": ["lo"], "last": True}, + ], + ) + add_execute_streaming_sql_results(sql, explicit_partials) + self.spanner_service.clear_requests() + add_execute_streaming_sql_error(sql, 1, unavailable_status()) + with self.database.snapshot() as snapshot: + self.assertEqual([[1, "hello"]], list(snapshot.execute_sql(sql))) + execute_requests = _requests_of_type(self.spanner_service, ExecuteSqlRequest) + self.assertEqual( + [b"", b"mid_tok"], [request.resume_token for request in execute_requests] + ) + + def test_partial_result_set_config_validation(self): + # Verify PartialResultSetConfig rejects non-positive chunking thresholds. + with self.assertRaisesRegex( + ValueError, "max_values_per_chunk must be positive" + ): + PartialResultSetConfig(max_values_per_chunk=0) + with self.assertRaisesRegex( + ValueError, "max_string_chunk_length must be positive" + ): + PartialResultSetConfig(max_string_chunk_length=0) + + def test_partial_result_set_set_last_flag_and_non_mutation(self): + # Verify set_last_flag marks only the final chunk and inline-begin transaction + # metadata does not mutate caller-registered explicit PartialResultSet objects. + sql = "select id from last_flag_table" + add_single_result( + sql, + "id", + TypeCode.INT64, + [("1",), ("2",)], + chunk_config=PartialResultSetConfig(set_last_flag=True), + ) + partials = self.spanner_service.mock_spanner.get_result_as_partial_result_sets( + sql + ) + self.assertEqual([False, True], [partial.last for partial in partials]) + + # Registered explicit partials should not be mutated by inline begin transactions. + explicit_sql = "select id from explicit_table" + explicit_partials = _make_partial_result_sets( + [("id", TypeCode.INT64)], + [{"values": ["1"], "last": True}], + ) + add_execute_streaming_sql_results(explicit_sql, explicit_partials) + self.database.run_in_transaction( + lambda transaction: list(transaction.execute_sql(explicit_sql)) + ) + self.assertEqual(b"", explicit_partials[0].metadata.transaction.id) + + def test_partial_result_set_combined_chunking_options(self): + # Verify combining max_values_per_chunk, max_string_chunk_length, and set_last_flag. + sql = "select id, payload, tag from items" + add_multi_column_result( + sql, + [ + ("id", TypeCode.INT64), + ("payload", TypeCode.STRING), + ("tag", TypeCode.STRING), + ], + [("1", "abcdefgh", "t1"), ("2", "xy", "t2")], + chunk_config=PartialResultSetConfig( + max_values_per_chunk=2, + max_string_chunk_length=4, + set_last_flag=True, + ), + ) + partials = self.spanner_service.mock_spanner.get_result_as_partial_result_sets( + sql + ) + # Row 1: [1, "abcd"] (chunked -> no token), ["efgh", "t1"] (row end -> b"1"), + # Row 2: [2, "xy"] (mid-row -> no token), ["t2"] (last -> b"2", last=True) + self.assertEqual( + [True, False, False, False], + [partial.chunked_value for partial in partials], + ) + self.assertEqual( + [b"", b"1", b"", b"2"], [partial.resume_token for partial in partials] + ) + self.assertEqual( + [False, False, False, True], [partial.last for partial in partials] + ) + with self.database.snapshot() as snapshot: + self.assertEqual( + [[1, "abcdefgh", "t1"], [2, "xy", "t2"]], + list(snapshot.execute_sql(sql)), + ) + + def test_partial_result_set_single_column_batching_and_resets(self): + # Verify multiple 1-column rows batch into a single chunk ending at a row + # boundary, and re-registering via add_result resets chunking & explicit partials. + batch_sql = "select id from batched" + add_single_result( + batch_sql, + "id", + TypeCode.INT64, + [("1",), ("2",), ("3",)], + chunk_config=PartialResultSetConfig(max_values_per_chunk=2), + ) + batch_partials = ( + self.spanner_service.mock_spanner.get_result_as_partial_result_sets( + batch_sql + ) + ) + self.assertEqual(2, len(batch_partials)) + self.assertEqual( + [b"1", b"2"], [partial.resume_token for partial in batch_partials] + ) + with self.database.snapshot() as snapshot: + self.assertEqual([[1], [2], [3]], list(snapshot.execute_sql(batch_sql))) + + # Re-registering without chunk_config resets previous chunking behavior, and + # overrides any earlier add_execute_streaming_sql_results registration. + add_execute_streaming_sql_results(batch_sql, []) + add_single_result(batch_sql, "id", TypeCode.INT64, [("1",), ("2",), ("3",)]) + reset_partials = ( + self.spanner_service.mock_spanner.get_result_as_partial_result_sets( + batch_sql + ) + ) + self.assertEqual(3, len(reset_partials)) + with self.database.snapshot() as snapshot: + self.assertEqual([[1], [2], [3]], list(snapshot.execute_sql(batch_sql))) + + def test_partial_result_set_empty_result_set_with_set_last_flag(self): + # Verify 0-row ResultSet honors set_last_flag=True without emitting a resume_token. + empty_sql = "select id from empty_table" + add_single_result( + empty_sql, + "id", + TypeCode.INT64, + [], + chunk_config=PartialResultSetConfig(set_last_flag=True), + ) + empty_partials = ( + self.spanner_service.mock_spanner.get_result_as_partial_result_sets( + empty_sql + ) + ) + self.assertEqual(1, len(empty_partials)) + self.assertTrue(empty_partials[0].last) + self.assertEqual(b"", empty_partials[0].resume_token) + with self.database.snapshot() as snapshot: + self.assertEqual([], list(snapshot.execute_sql(empty_sql))) + + def test_partial_result_set_last_flag_without_tokens_and_trailing_error(self): + # Verify set_last_flag=True with emit_resume_tokens=False completes cleanly, + # and trailing errors past last=True are drained without failing the caller. + no_token_last_sql = "select id from no_token_last" + add_single_result( + no_token_last_sql, + "id", + TypeCode.INT64, + [("10",), ("20",)], + chunk_config=PartialResultSetConfig( + emit_resume_tokens=False, set_last_flag=True + ), + ) + with self.database.snapshot() as snapshot: + self.assertEqual( + [[10], [20]], list(snapshot.execute_sql(no_token_last_sql)) + ) + add_execute_streaming_sql_error( + no_token_last_sql, 5, internal_server_error_status() + ) + with self.database.snapshot() as snapshot: + self.assertEqual( + [[10], [20]], list(snapshot.execute_sql(no_token_last_sql)) + ) + + def test_streaming_read_empty_columns_wildcard_lookup(self): + # Verify ReadRequest with empty columns maps to SELECT * FROM . + add_single_result( + "SELECT * FROM wildcard_table", "id", TypeCode.INT64, [("9",)] + ) + add_streaming_read_error( + "wildcard_table", [], 1, internal_server_error_status() + ) + with self.database.snapshot() as snapshot: + row_iterator = iter( + snapshot.read( + table="wildcard_table", + columns=[], + keyset=KeySet(all_=True), + ) + ) + self.assertEqual([9], next(row_iterator)) + with self.assertRaisesRegex( + exceptions.InternalServerError, "Internal server error." + ): + next(row_iterator) + + def test_streaming_read_chunking_and_boundary_errors(self): + # Verify StreamingRead handles combined mid-row/string chunking plus + # boundary errors at partial_index=0 and partial_index >= len(chunks). + add_multi_column_result( + "SELECT id, payload FROM chunked_read", + [("id", TypeCode.INT64), ("payload", TypeCode.STRING)], + [("1", "hello world"), ("2", "ok")], + chunk_config=PartialResultSetConfig( + max_values_per_chunk=2, + max_string_chunk_length=4, + ), + ) + add_streaming_read_error( + "chunked_read", ["id", "payload"], 1, unavailable_status() + ) + with self.database.snapshot() as snapshot: + self.assertEqual( + [[1, "hello world"], [2, "ok"]], + list( + snapshot.read( + table="chunked_read", + columns=["id", "payload"], + keyset=KeySet(all_=True), + ) + ), + ) + + # partial_index=0 and partial_index >= chunk count on StreamingRead. + add_streaming_read_error( + "chunked_read", ["id", "payload"], 0, invalid_argument_status() + ) + with self.database.snapshot() as snapshot: + row_iterator = iter( + snapshot.read( + table="chunked_read", + columns=["id", "payload"], + keyset=KeySet(all_=True), + ) + ) + with self.assertRaisesRegex( + exceptions.InvalidArgument, "Invalid argument." + ): + next(row_iterator) + + add_streaming_read_error( + "chunked_read", ["id", "payload"], 10, internal_server_error_status() + ) + with self.database.snapshot() as snapshot: + row_iterator = iter( + snapshot.read( + table="chunked_read", + columns=["id", "payload"], + keyset=KeySet(all_=True), + ) + ) + self.assertEqual([1, "hello world"], next(row_iterator)) + self.assertEqual([2, "ok"], next(row_iterator)) + with self.assertRaisesRegex( + exceptions.InternalServerError, "Internal server error." + ): + next(row_iterator) + + def test_execute_streaming_sql_multiple_resumptions_and_rst_stream(self): + # Verify sequential mid-stream UNAVAILABLE and RST_STREAM errors trigger + # multi-hop resumption using per-RPC partial_index offsets (b"" -> b"1" -> b"2"). + sql = "select id from multi_resume" + add_single_result(sql, "id", TypeCode.INT64, [("1",), ("2",), ("3",), ("4",)]) + # First RPC yields chunk 0 (token b"1"), fails at per-RPC index 1; + # second RPC resumes at b"1", yields chunk 1 (token b"2"), fails at per-RPC index 1; + # third RPC resumes at b"2", yields chunks 2 and 3. + add_execute_streaming_sql_error(sql, 1, unavailable_status()) + add_execute_streaming_sql_error( + sql, + 1, + internal_server_error_status("Received RST_STREAM with error code 2"), + ) + with self.database.snapshot() as snapshot: + self.assertEqual([[1], [2], [3], [4]], list(snapshot.execute_sql(sql))) + execute_requests = _requests_of_type(self.spanner_service, ExecuteSqlRequest) + self.assertEqual( + [b"", b"1", b"2"], + [request.resume_token for request in execute_requests], + ) + + def test_inline_begin_transaction_mid_stream_unavailable_switches_to_id(self): + # Verify resuming an inline-begin read-write stream switches from + # transaction.begin to transaction.id when sending resume_token. + sql = "select id from rw_resume" + add_single_result(sql, "id", TypeCode.INT64, [("1",), ("2",)]) + add_execute_streaming_sql_error(sql, 1, unavailable_status()) + + def _query(transaction: Transaction): + return list(transaction.execute_sql(sql)) + + rows = self.database.run_in_transaction(_query) + self.assertEqual([[1], [2]], rows) + execute_requests = _requests_of_type(self.spanner_service, ExecuteSqlRequest) + self.assertEqual(2, len(execute_requests)) + self.assertNotEqual(TransactionOptions(), execute_requests[0].transaction.begin) + self.assertEqual(b"", execute_requests[0].resume_token) + self.assertEqual(TransactionOptions(), execute_requests[1].transaction.begin) + self.assertTrue(execute_requests[1].transaction.id) + self.assertEqual(b"1", execute_requests[1].resume_token) + + def test_execute_streaming_sql_server_validation_and_empty_partials(self): + # Verify mock server rejects unknown resume_token and begin+resume_token with + # INVALID_ARGUMENT, and returns empty results when [] partials are registered. + sql = "select id from validation_table" + add_single_result(sql, "id", TypeCode.INT64, [("1",), ("2",)]) + + session = self.database.session() + session.create() + api = self.database.spanner_api + + # Unknown resume_token must raise InvalidArgument instead of returning empty OK. + request_metadata = [("x-goog-spanner-request-id", "1.1.1.1.1.1")] + with self.assertRaisesRegex(exceptions.InvalidArgument, "Invalid resume_token"): + list( + api.execute_streaming_sql( + request=ExecuteSqlRequest( + session=session.name, + sql=sql, + resume_token=b"non-existent-token", + ), + metadata=request_metadata, + ) + ) + + # Combining transaction.begin with non-empty resume_token must raise InvalidArgument. + with self.assertRaisesRegex( + exceptions.InvalidArgument, + "Cannot combine begin transaction with resume_token", + ): + list( + api.execute_streaming_sql( + request=ExecuteSqlRequest( + session=session.name, + sql=sql, + transaction=TransactionSelector( + begin=TransactionOptions(read_only={}) + ), + resume_token=b"1", + ), + metadata=request_metadata, + ) + ) + + # Explicitly registered empty PartialResultSet list does not fall back to results. + empty_explicit_sql = "select id from explicit_empty" + add_execute_streaming_sql_results(empty_explicit_sql, []) + with self.database.snapshot() as snapshot: + self.assertEqual([], list(snapshot.execute_sql(empty_explicit_sql))) + + def test_streamed_result_set_helpers_with_chunked_streams(self): + # Verify StreamedResultSet helpers (one, one_or_none, to_dict_list, lazy_decode) + # reassemble mid-row and chunked_value=True streams cleanly. + sql_one = "select id, payload from helper_one" + add_multi_column_result( + sql_one, + [("id", TypeCode.INT64), ("payload", TypeCode.STRING)], + [("7", "hello world")], + chunk_config=PartialResultSetConfig( + max_values_per_chunk=1, max_string_chunk_length=4 + ), + ) + with self.database.snapshot(multi_use=True) as snapshot: + self.assertEqual([7, "hello world"], snapshot.execute_sql(sql_one).one()) + self.assertEqual( + [7, "hello world"], snapshot.execute_sql(sql_one).one_or_none() + ) + self.assertEqual( + [{"id": 7, "payload": "hello world"}], + snapshot.execute_sql(sql_one).to_dict_list(), + ) + lazy_results = snapshot.execute_sql(sql_one, lazy_decode=True) + lazy_rows = list(lazy_results) + self.assertEqual([7, "hello world"], lazy_results.decode_row(lazy_rows[0])) + + # TODO(https://github.com/googleapis/google-cloud-python/issues/19079): + # Remove @unittest.expectedFailure once Cursor._fetch raises mid-stream + # errors instead of silently returning truncated partial rows. + @unittest.expectedFailure + def test_dbapi_fetchall_mid_stream_deadline_exceeded_issue_19079(self): + sql = "select id from issue_19079_deadline" + add_single_result(sql, "id", TypeCode.INT64, [("1",), ("2",)]) + for read_only in (True, False): + add_execute_streaming_sql_error(sql, 1, deadline_exceeded_status()) + connection = Connection(self.instance, self.database, read_only=read_only) + try: + with connection.cursor() as cursor: + cursor.execute(sql) + with self.assertRaisesRegex( + exceptions.DeadlineExceeded, "Deadline exceeded." + ): + cursor.fetchall() + finally: + connection.close() + + # TODO(https://github.com/googleapis/google-cloud-python/issues/19079): + # Remove @unittest.expectedFailure once Cursor._fetch properly retries + # mid-stream Aborted in read-write transactions and returns all rows. + @unittest.expectedFailure + def test_dbapi_fetchall_mid_stream_aborted_issue_19079(self): + sql = "select id from issue_19079_aborted" + add_single_result(sql, "id", TypeCode.INT64, [("1",), ("2",)]) + add_execute_streaming_sql_error(sql, 1, aborted_status()) + connection = Connection(self.instance, self.database, read_only=False) + try: + with connection.cursor() as cursor: + cursor.execute(sql) + self.assertEqual([[1], [2]], cursor.fetchall()) + finally: + connection.close() + + +class TestBasicsAsync(AsyncMockServerTestBase): + @asynccontextmanager + async def _async_database(self): + client = AsyncClient( + project="p", + credentials=AnonymousCredentials(), + client_options=ClientOptions( + api_endpoint=f"localhost:{AsyncMockServerTestBase.port}" + ), + disable_builtin_metrics=True, + ) + instance = client.instance("test-instance") + database = await instance.database( + "test-database", pool=AsyncFixedSizePool(size=10) + ) + async with grpc.aio.insecure_channel( + f"localhost:{AsyncMockServerTestBase.port}" + ) as channel: + database._spanner_api = SpannerAsyncClient( + client_info=client._client_info, + transport=SpannerGrpcAsyncIOTransport(channel=channel), + ) + yield database + + async def test_async_execute_streaming_sql_restarts_without_resume_token(self): + # Verify chunk 0 without a resume_token (chunked_value=True) restarts from b"". + sql = "select id, payload from async_restart_docs" + add_multi_column_result( + sql, + [("id", TypeCode.INT64), ("payload", TypeCode.STRING)], + [("1", "hello world"), ("2", "abcdef")], + chunk_config=PartialResultSetConfig( + max_values_per_chunk=2, max_string_chunk_length=4 + ), + ) + add_execute_streaming_sql_error(sql, 1, unavailable_status()) + async with self._async_database() as database: + async with database.snapshot() as snapshot: + results = await snapshot.execute_sql(sql) + rows = [row async for row in results] + self.assertEqual([[1, "hello world"], [2, "abcdef"]], rows) + execute_requests = _requests_of_type(self.spanner_service, ExecuteSqlRequest) + self.assertEqual( + [b"", b""], [request.resume_token for request in execute_requests] + ) + + async def test_async_execute_streaming_sql_resumes_with_resume_token(self): + # Verify chunk 2 row boundary emits resume_token=b"1" and resumes at index 3. + sql = "select id, payload from async_row_boundary_docs" + add_multi_column_result( + sql, + [("id", TypeCode.INT64), ("payload", TypeCode.STRING)], + [("1", "hello world"), ("2", "abcdef")], + chunk_config=PartialResultSetConfig(max_string_chunk_length=4), + ) + add_execute_streaming_sql_error(sql, 3, unavailable_status()) + async with self._async_database() as database: + async with database.snapshot() as snapshot: + results = await snapshot.execute_sql(sql) + rows = [row async for row in results] + self.assertEqual([[1, "hello world"], [2, "abcdef"]], rows) + execute_requests = _requests_of_type(self.spanner_service, ExecuteSqlRequest) + self.assertEqual( + [b"", b"1"], [request.resume_token for request in execute_requests] + ) + + async def test_async_streaming_read_resumes_with_resume_token(self): + # Verify async StreamingRead resumes from non-empty resume_token=b"1". + add_multi_column_result( + "SELECT id, payload FROM async_read_docs", + [("id", TypeCode.INT64), ("payload", TypeCode.STRING)], + [("1", "hello world"), ("2", "abcdef")], + ) + add_streaming_read_error( + "async_read_docs", ["id", "payload"], 1, unavailable_status() + ) + async with self._async_database() as database: + async with database.snapshot() as snapshot: + read_results = await snapshot.read( + table="async_read_docs", + columns=["id", "payload"], + keyset=KeySet(all_=True), + ) + read_rows = [row async for row in read_results] + self.assertEqual([[1, "hello world"], [2, "abcdef"]], read_rows) + read_requests = _requests_of_type(self.spanner_service, ReadRequest) + self.assertEqual( + [b"", b"1"], [request.resume_token for request in read_requests] + ) + + async def test_async_execute_streaming_sql_mid_stream_deadline_exceeded(self): + # Verify async iteration yields row 1 before raising mid-stream DeadlineExceeded. + sql = "select id, payload from async_deadline_docs" + add_multi_column_result( + sql, + [("id", TypeCode.INT64), ("payload", TypeCode.STRING)], + [("1", "hello world"), ("2", "abcdef")], + chunk_config=PartialResultSetConfig(max_string_chunk_length=4), + ) + add_execute_streaming_sql_error(sql, 3, deadline_exceeded_status()) + async with self._async_database() as database: + async with database.snapshot() as snapshot: + results = await snapshot.execute_sql(sql) + row_iterator = results.__aiter__() + self.assertEqual([1, "hello world"], await row_iterator.__anext__()) + with self.assertRaisesRegex( + exceptions.DeadlineExceeded, "Deadline exceeded." + ): + await row_iterator.__anext__() + + async def test_async_execute_streaming_sql_last_flag_trailing_error_drained(self): + # Verify async _drain_stream absorbs trailing errors sent after last=True. + sql = "select id from async_last_flag" + add_single_result( + sql, + "id", + TypeCode.INT64, + [("10",), ("20",)], + chunk_config=PartialResultSetConfig(set_last_flag=True), + ) + add_execute_streaming_sql_error(sql, 5, internal_server_error_status()) + async with self._async_database() as database: + async with database.snapshot() as snapshot: + results = await snapshot.execute_sql(sql) + rows = [row async for row in results] + self.assertEqual([[10], [20]], rows) + def _execute_query(transaction: Transaction, sql: str): rows = transaction.execute_sql(sql, last_statement=True)