diff --git a/packages/google-cloud-storage/google/cloud/storage/asyncio/async_appendable_object_writer.py b/packages/google-cloud-storage/google/cloud/storage/asyncio/async_appendable_object_writer.py index b0081278cbc5..cb2597448237 100644 --- a/packages/google-cloud-storage/google/cloud/storage/asyncio/async_appendable_object_writer.py +++ b/packages/google-cloud-storage/google/cloud/storage/asyncio/async_appendable_object_writer.py @@ -441,6 +441,31 @@ def _on_open_error(self, exc): self._created_generation = True self.generation = redirect_proto.generation + async def _abort_stream(self) -> None: + """Best-effort close of the current stream, then marks the writer closed.""" + if self.write_obj_stream is not None and self.write_obj_stream.is_stream_open: + try: + await self.write_obj_stream.close() + except Exception as e: + logger.debug(f"Closing the write stream resulted in: {e}") + self._is_stream_open = False + + def _raise_if_offset_lost(self, expected_offset: Optional[int]) -> None: + """Raises DataLoss if a reconnect reports fewer bytes than were sent. + + ``DataLoss`` is not retryable, so ``close()`` and ``finalize()`` fail + fast instead of reopening the stream until the retry deadline. + """ + if ( + self.offset is not None + and expected_offset is not None + and self.offset != expected_offset + ): + raise exceptions.DataLoss( + f"Unrecoverable data loss during reconnect. " + f"Expected offset {expected_offset}, got {self.offset}." + ) + def _merge_retry_policy( self, retry_policy: Optional[AsyncRetry] = None ) -> AsyncRetry: @@ -553,10 +578,13 @@ async def append( calling `self.append` will append bytes at the end of the current size ie. `self.offset` bytes relative to the begining of the object. - This method sends the provided `data` to the GCS server in chunks. - and persists data in GCS at every `_DEFAULT_FLUSH_INTERVAL_BYTES` bytes - or at the last chunk whichever is earlier. Persisting is done by setting - `flush=True` on request. + This method sends the provided `data` to the GCS server in chunks and + requests persistence (``flush=True``) each time ``flush_interval`` + bytes have been sent since the last flush. Bytes after the last + ``flush_interval`` boundary are only guaranteed durable after + ``flush()`` or ``close()``. If the stream breaks before then and the + server lost them, a later ``append()`` raises + :class:`~google.api_core.exceptions.DataLoss`. :type data: bytes :param data: The bytes to append to the object. @@ -571,6 +599,9 @@ async def append( :param enable_checksum: (Optional) If True, calculates and checks checksums for each chunk. Defaults to True. :raises ValueError: If the stream is not open. + :raises google.api_core.exceptions.DataLoss: If reconnecting after a + stream failure reveals that unpersisted bytes from an earlier + ``append()`` call were lost. """ if not self._is_stream_open: raise ValueError("Stream is not open. Call open() before append().") @@ -618,15 +649,22 @@ async def generator(): self._is_stream_open = False await self.open(metadata=current_metadata) + self.bytes_appended_since_last_flush = 0 + + if (self.persisted_size or 0) < write_state.initial_offset: + # Close the reopened stream so a later close() can't + # finalize the truncated object. + await self._abort_stream() + raise exceptions.DataLoss( + f"Unrecoverable data loss during reconnect. " + f"Expected persisted_size >= {write_state.initial_offset}, " + f"got {self.persisted_size}." + ) write_state.persisted_size = self.persisted_size write_state.write_handle = self.write_handle write_state.routing_token = None - - write_state.user_buffer.seek(write_state.persisted_size) - write_state.bytes_sent = write_state.persisted_size - write_state.bytes_since_last_flush = 0 - self.bytes_appended_since_last_flush = 0 + write_state.reset_to_persisted() requests = strategy.generate_requests(state) @@ -662,15 +700,14 @@ async def generator(): buffer, self.flush_interval, enable_checksum=enable_checksum, + initial_offset=self.offset or 0, ) write_state.write_handle = self.write_handle write_state.persisted_size = self.persisted_size - # offset is set during `open()` call. - write_state.bytes_sent = self.offset or 0 write_state.bytes_since_last_flush = self.bytes_appended_since_last_flush retry_manager = _BidiStreamRetryManager( - _WriteResumptionStrategy(), + strategy, lambda r, s: send_and_recv_generator(r, s, metadata), ) await retry_manager.execute({"write_state": write_state}, retry_policy) @@ -753,10 +790,16 @@ async def close( :type retry_policy: :class:`~google.api_core.retry_async.AsyncRetry` :param retry_policy: (Optional) The retry policy to use for the operation. - rtype: Union[int, _storage_v2.Object] - returns: Updated `self.persisted_size` by default after closing the - bidi-gRPC stream. However, if `finalize_on_close=True` is passed, - returns the finalized object resource. + :rtype: Union[int, _storage_v2.Object] + :returns: By default, ``self.persisted_size``. This is the size the + server last confirmed as persisted, from the most recent + ``flush()``, ``state_lookup()`` or flush inside ``append()``. + Closing persists any bytes appended after that, but this value is + not refreshed, so it can be smaller than the object size by up to + ``flush_interval`` bytes. For the exact size, call ``flush()`` + before ``close()``, or use ``self.offset``. If + ``finalize_on_close=True`` is passed, returns the finalized object + resource, whose ``size`` is exact. :raises ValueError: If the stream is not open (i.e., `open()` has not been called). @@ -765,6 +808,8 @@ async def close( :raises google.api_core.exceptions.InvalidArgument: If the provided full_object_checksum does not match the checksum computed by the server. + :raises google.api_core.exceptions.DataLoss: If reconnecting after a + stream failure reveals that the server lost appended bytes. """ if not self._is_stream_open: @@ -797,14 +842,7 @@ async def _do_close(): ) self._is_stream_open = False await self.open() - if ( - self.offset is not None - and expected_offset is not None - and self.offset != expected_offset - ): - raise exceptions.InternalServerError( - f"Unrecoverable data loss during reconnect. Expected offset {expected_offset}, got {self.offset}" - ) + self._raise_if_offset_lost(expected_offset) await self.write_obj_stream.close() return self.persisted_size @@ -812,7 +850,8 @@ async def _do_close(): try: return await retry_policy(_do_close)() finally: - self._is_stream_open = False + # Closes a stream reopened by a retry that then failed. + await self._abort_stream() async def finalize( self, @@ -854,6 +893,8 @@ async def finalize( :raises google.api_core.exceptions.InvalidArgument: If the provided full_object_checksum does not match the checksum computed by the server. + :raises google.api_core.exceptions.DataLoss: If reconnecting after a + stream failure reveals that the server lost appended bytes. """ if not self._is_stream_open: raise ValueError("Stream is not open. Call open() before finalize().") @@ -890,14 +931,7 @@ async def _do_finalize(): ) self._is_stream_open = False await self.open() - if ( - self.offset is not None - and expected_offset is not None - and self.offset != expected_offset - ): - raise exceptions.InternalServerError( - f"Unrecoverable data loss during reconnect. Expected offset {expected_offset}, got {self.offset}" - ) + self._raise_if_offset_lost(expected_offset) await self.write_obj_stream.send(finalize_req) response = await self.write_obj_stream.recv() diff --git a/packages/google-cloud-storage/google/cloud/storage/asyncio/retry/writes_resumption_strategy.py b/packages/google-cloud-storage/google/cloud/storage/asyncio/retry/writes_resumption_strategy.py index bec0b31c5407..7a45d49a0749 100644 --- a/packages/google-cloud-storage/google/cloud/storage/asyncio/retry/writes_resumption_strategy.py +++ b/packages/google-cloud-storage/google/cloud/storage/asyncio/retry/writes_resumption_strategy.py @@ -37,6 +37,13 @@ class _WriteState: :type flush_interval: int :param flush_interval: The flush interval at which the data is flushed. + + :type enable_checksum: bool + :param enable_checksum: Whether to compute CRC32C checksums for chunks. + + :type initial_offset: int + :param initial_offset: The object byte offset corresponding to position 0 of + ``user_buffer``. """ def __init__( @@ -45,16 +52,18 @@ def __init__( user_buffer: IO[bytes], flush_interval: int, enable_checksum: bool = True, + initial_offset: int = 0, ): self.chunk_size = chunk_size self.user_buffer = user_buffer + self.initial_offset: int = initial_offset self.persisted_size: int = 0 # Bytes sent to the server (it may be unpersisted), # i.e. latest object size = persisted_size + some more bytes. # Please note: these bytes are sent from client to server, server might have also received it. # but might not have persisted it yet (may be in memory buffer on server side). # This variable is same as `offset variable` in the instance of `AppendableObjectWriter`. - self.bytes_sent: int = 0 + self.bytes_sent: int = initial_offset self.bytes_since_last_flush: int = 0 self.flush_interval: int = flush_interval self.write_handle: Union[bytes, storage_type.BidiWriteHandle, None] = None @@ -62,6 +71,13 @@ def __init__( self.is_finalized: bool = False self.enable_checksum: bool = enable_checksum + def reset_to_persisted(self) -> None: + """Rewinds user_buffer and byte counters to persisted_size.""" + persisted_offset = max(self.persisted_size or 0, self.initial_offset) + self.user_buffer.seek(persisted_offset - self.initial_offset) + self.bytes_sent = persisted_offset + self.bytes_since_last_flush = 0 + class _WriteResumptionStrategy(_BaseResumptionStrategy): """The concrete resumption strategy for bidi writes.""" @@ -150,6 +166,4 @@ async def recover_state_on_failure( # We must assume any data sent beyond 'persisted_size' was lost. # Reset the user buffer to the last known good byte confirmed by the server. - write_state.user_buffer.seek(write_state.persisted_size) - write_state.bytes_sent = write_state.persisted_size - write_state.bytes_since_last_flush = 0 + write_state.reset_to_persisted() diff --git a/packages/google-cloud-storage/tests/unit/asyncio/retry/test_writes_resumption_strategy.py b/packages/google-cloud-storage/tests/unit/asyncio/retry/test_writes_resumption_strategy.py index 2af036f80cb2..b4e70e6b9f2b 100644 --- a/packages/google-cloud-storage/tests/unit/asyncio/retry/test_writes_resumption_strategy.py +++ b/packages/google-cloud-storage/tests/unit/asyncio/retry/test_writes_resumption_strategy.py @@ -381,8 +381,63 @@ def test_write_state_initialization(self): buffer = io.BytesIO(b"test") ws = _WriteState(chunk_size=10, user_buffer=buffer, flush_interval=100) + assert ws.initial_offset == 0 assert ws.persisted_size == 0 assert ws.bytes_sent == 0 assert ws.bytes_since_last_flush == 0 assert ws.flush_interval == 100 assert not ws.is_finalized + + @pytest.mark.parametrize( + "initial_offset, persisted_size, expected_tell, expected_bytes_sent, expected_chunks", + [ + # Partial persistence inside current buffer: seek to persisted_size - initial_offset. + (20, 24, 4, 24, [(24, b"efgh"), (28, b"ij")]), + # Cached persisted_size below initial_offset before stream reopen: clamp to 0. + (20, 0, 0, 20, [(20, b"abcd"), (24, b"efgh"), (28, b"ij")]), + # persisted_size exactly at initial_offset: resend the whole buffer. + (20, 20, 0, 20, [(20, b"abcd"), (24, b"efgh"), (28, b"ij")]), + # Whole buffer persisted before the error: nothing left to send. + (20, 30, 10, 30, []), + # Stale cached persisted_size from an unaligned prior append: clamp to 0. + (20, 12, 0, 20, [(20, b"abcd"), (24, b"efgh"), (28, b"ij")]), + ], + ) + @pytest.mark.asyncio + async def test_recover_state_on_failure_with_initial_offset( + self, + strategy, + initial_offset, + persisted_size, + expected_tell, + expected_bytes_sent, + expected_chunks, + ): + """Verify recovery rewinds user_buffer relative to initial_offset.""" + user_buffer = io.BytesIO(b"abcdefghij") + write_state = _WriteState( + chunk_size=4, + user_buffer=user_buffer, + flush_interval=100, + initial_offset=initial_offset, + ) + assert write_state.bytes_sent == initial_offset + + write_state.bytes_sent = initial_offset + 8 + write_state.persisted_size = persisted_size + write_state.bytes_since_last_flush = 8 + user_buffer.seek(8) + + state = {"write_state": write_state} + await strategy.recover_state_on_failure( + exceptions.ServiceUnavailable("busy"), state + ) + + assert user_buffer.tell() == expected_tell + assert write_state.bytes_sent == expected_bytes_sent + assert write_state.bytes_since_last_flush == 0 + + requests = strategy.generate_requests(state) + assert [ + (req.write_offset, req.checksummed_data.content) for req in requests + ] == expected_chunks diff --git a/packages/google-cloud-storage/tests/unit/asyncio/test_async_appendable_object_writer.py b/packages/google-cloud-storage/tests/unit/asyncio/test_async_appendable_object_writer.py index 93b78f07db1f..ff0ce80ce616 100644 --- a/packages/google-cloud-storage/tests/unit/asyncio/test_async_appendable_object_writer.py +++ b/packages/google-cloud-storage/tests/unit/asyncio/test_async_appendable_object_writer.py @@ -38,6 +38,7 @@ WRITE_HANDLE = b"test-write-handle" PERSISTED_SIZE = 456 EIGHT_MIB = 8 * 1024 * 1024 +MIB = 1024 * 1024 DATA_LESS_THAN_FLUSH_INTERVAL = ( b"test-data" # 9 bytes, less than default flush interval ) @@ -799,6 +800,247 @@ async def mock_execute(state, policy): mock_writer_open.assert_awaited() assert writer.persisted_size == 5 + @staticmethod + def _attach_in_memory_server(mock_stream, fail_at_offset, failure): + """Configures mock_stream as an in-memory appendable object that fails once.""" + server_bytes = bytearray() + persisted_bytes = 0 + failed_once = False + open_metadata = [] + + async def fake_open(metadata=None): + open_metadata.append(metadata) + mock_stream.is_stream_open = True + mock_stream.generation_number = GENERATION + mock_stream.write_handle = WRITE_HANDLE + mock_stream.persisted_size = persisted_bytes + del server_bytes[persisted_bytes:] + + async def fake_send(request): + nonlocal persisted_bytes, failed_once + chunk_content = request.checksummed_data.content + if chunk_content: + if not failed_once and request.write_offset >= fail_at_offset: + failed_once = True + raise failure + assert request.write_offset == len(server_bytes) + server_bytes.extend(chunk_content) + if request.flush: + persisted_bytes = len(server_bytes) + + async def fake_recv(): + return storage_type.BidiWriteObjectResponse( + persisted_size=persisted_bytes, + write_handle=storage_type.BidiWriteHandle(handle=WRITE_HANDLE), + ) + + mock_stream.open.side_effect = fake_open + mock_stream.send.side_effect = fake_send + mock_stream.recv.side_effect = fake_recv + return server_bytes, open_metadata + + @staticmethod + def _payload(segments): + """Builds bytes from (byte, length) segments, so slice mix-ups show up.""" + return b"".join(byte * length for byte, length in segments) + + @pytest.mark.parametrize( + "flush_interval, first_segments, second_segments, fail_at_offset, failure, " + "expected_routing_token, expected_persisted_size, expected_since_last_flush", + [ + # persisted_size > len(second_payload): must not seek past buffer EOF. + pytest.param( + _MAX_CHUNK_SIZE_BYTES, + [(b"A", 2 * _MAX_CHUNK_SIZE_BYTES)], + [(b"B", _MAX_CHUNK_SIZE_BYTES), (b"C", 512)], + 3 * _MAX_CHUNK_SIZE_BYTES, + exceptions.ServiceUnavailable("transient 503"), + None, + 3 * _MAX_CHUNK_SIZE_BYTES, + 512, + id="persisted-past-buffer-end", + ), + # initial_offset < persisted_size < len(second_payload): seek relative to initial_offset. + pytest.param( + _MAX_CHUNK_SIZE_BYTES, + [(b"0", _MAX_CHUNK_SIZE_BYTES)], + [ + (b"1", _MAX_CHUNK_SIZE_BYTES), + (b"2", _MAX_CHUNK_SIZE_BYTES), + (b"3", _MAX_CHUNK_SIZE_BYTES), + ], + 2 * _MAX_CHUNK_SIZE_BYTES, + exceptions.ServiceUnavailable("transient 503"), + None, + 4 * _MAX_CHUNK_SIZE_BYTES, + 0, + id="persisted-inside-buffer", + ), + # Redirect error during second append: forwards routing_token and preserves offset. + pytest.param( + _MAX_CHUNK_SIZE_BYTES, + [(b"M", _MAX_CHUNK_SIZE_BYTES)], + [(b"N", 4096)], + _MAX_CHUNK_SIZE_BYTES, + exceptions.Aborted( + "redirect", + errors=[ + BidiWriteObjectRedirectedError( + routing_token="redirect-token-2", + write_handle=storage_type.BidiWriteHandle( + handle=b"redirected-handle" + ), + ) + ], + ), + "redirect-token-2", + _MAX_CHUNK_SIZE_BYTES, + 4096, + id="redirect", + ), + # Payloads not aligned to flush_interval (gcsfs put_file shape): the + # first append leaves 1 MiB unflushed, the retry starts mid-buffer + # after the flush at 9 MiB. + pytest.param( + 4 * MIB, + [(b"P", 4 * MIB), (b"O", 1 * MIB)], + [(b"Q", 2 * MIB), (b"R", 2 * MIB), (b"S", 1 * MIB)], + 9 * MIB, + exceptions.ServiceUnavailable("transient 503"), + None, + 9 * MIB, + 1 * MIB, + id="unaligned-to-flush-interval", + ), + ], + ) + @pytest.mark.asyncio + async def test_append_multi_call_retry_preserves_alignment( + self, + mock_appendable_writer, + flush_interval, + first_segments, + second_segments, + fail_at_offset, + failure, + expected_routing_token, + expected_persisted_size, + expected_since_last_flush, + ): + """Verify retries on subsequent append calls preserve byte alignment.""" + from google.api_core.retry_async import AsyncRetry + + first_payload = self._payload(first_segments) + second_payload = self._payload(second_segments) + writer = self._make_one( + mock_appendable_writer["mock_client"], + writer_options={"FLUSH_INTERVAL_BYTES": flush_interval}, + ) + server_bytes, open_metadata = self._attach_in_memory_server( + mock_appendable_writer["mock_stream"], fail_at_offset, failure + ) + fast_retry = AsyncRetry( + predicate=_is_write_retryable, initial=0.0, maximum=0.0, multiplier=1.0 + ) + + await writer.open(retry_policy=fast_retry) + await writer.append(first_payload, retry_policy=fast_retry) + await writer.append( + second_payload, + retry_policy=fast_retry, + metadata=[("x-custom-header", "1")], + ) + + expected_payload = first_payload + second_payload + assert bytes(server_bytes) == expected_payload + assert writer.offset == len(expected_payload) + assert writer.persisted_size == expected_persisted_size + assert writer.bytes_appended_since_last_flush == expected_since_last_flush + if expected_routing_token: + assert ( + "x-goog-request-params", + f"routing_token={expected_routing_token}", + ) in (open_metadata[-1] or []) + + @pytest.mark.asyncio + async def test_append_multi_call_unpersisted_prior_append_raises_data_loss( + self, mock_appendable_writer + ): + """Verify reconnect losing unpersisted bytes from a prior append raises DataLoss.""" + from google.api_core.retry_async import AsyncRetry + + writer = self._make_one(mock_appendable_writer["mock_client"]) + mock_stream = mock_appendable_writer["mock_stream"] + mock_stream.persisted_size = 0 + + await writer.open() + mock_stream.is_stream_open = True + await writer.append(b"unflushed-first-append") + assert writer.offset == len(b"unflushed-first-append") + assert writer.persisted_size == 0 + + mock_stream.send.side_effect = exceptions.ServiceUnavailable("stream reset") + fast_retry = AsyncRetry( + predicate=_is_write_retryable, + initial=0.0, + maximum=0.0, + multiplier=1.0, + deadline=0.1, + ) + + with pytest.raises( + exceptions.DataLoss, match="Unrecoverable data loss during reconnect" + ): + await writer.append(b"second-append", retry_policy=fast_retry) + + assert mock_stream.open.await_count == 2 + assert writer.offset == 0 + assert writer.bytes_appended_since_last_flush == 0 + # The reopened stream is closed, so a later close(finalize_on_close=True) + # raises instead of finalizing the truncated object. + mock_stream.close.assert_awaited() + assert not writer.is_stream_open + with pytest.raises(ValueError, match="Stream is not open"): + await writer.close(finalize_on_close=True) + + @pytest.mark.asyncio + async def test_append_from_file_multi_block_retry_preserves_data( + self, mock_appendable_writer + ): + """Verify append_from_file preserves all blocks across a mid-transfer retry.""" + from google.api_core.retry_async import AsyncRetry + + writer = self._make_one( + mock_appendable_writer["mock_client"], + writer_options={"FLUSH_INTERVAL_BYTES": _MAX_CHUNK_SIZE_BYTES}, + ) + server_bytes, _ = self._attach_in_memory_server( + mock_appendable_writer["mock_stream"], + _MAX_CHUNK_SIZE_BYTES, + exceptions.ServiceUnavailable("transient 503 on block 2"), + ) + await writer.open() + + full_file_bytes = ( + b"X" * _MAX_CHUNK_SIZE_BYTES + b"Y" * _MAX_CHUNK_SIZE_BYTES + b"Z" * 1024 + ) + with mock.patch( + "google.cloud.storage.asyncio.async_appendable_object_writer.AsyncRetry", + side_effect=lambda **kwargs: AsyncRetry( + predicate=kwargs["predicate"], + on_error=kwargs.get("on_error"), + initial=0.0, + maximum=0.0, + multiplier=1.0, + ), + ): + await writer.append_from_file( + io.BytesIO(full_file_bytes), block_size=_MAX_CHUNK_SIZE_BYTES + ) + + assert bytes(server_bytes) == full_file_bytes + assert writer.offset == len(full_file_bytes) + @pytest.mark.asyncio async def test_append_unimplemented_string_raises(self, mock_appendable_writer): writer = self._make_one(mock_appendable_writer["mock_client"]) @@ -1162,3 +1404,47 @@ async def test_close_retry_on_redirect_error(self, mock_appendable_writer): assert writer.write_handle.handle == b"h2" writer.open.assert_awaited_once() assert not writer._is_stream_open + + @pytest.mark.parametrize("finalize_on_close", [False, True]) + @pytest.mark.asyncio + async def test_close_reconnect_offset_mismatch_raises_data_loss_without_retry( + self, mock_appendable_writer, finalize_on_close + ): + """Verify close() and finalize() fail fast when a reconnect lost bytes.""" + from google.api_core.retry_async import AsyncRetry + + writer = self._make_one(mock_appendable_writer["mock_client"]) + mock_stream = mock_appendable_writer["mock_stream"] + writer._is_stream_open = True + writer.write_obj_stream = mock_stream + mock_stream.is_stream_open = True + writer.offset = 18 * MIB + + transient = exceptions.ServiceUnavailable("stream reset") + if finalize_on_close: + mock_stream.recv.side_effect = transient + else: + mock_stream.close.side_effect = transient + + async def reopen_with_lost_tail(*args, **kwargs): + writer._is_stream_open = True + writer.persisted_size = 16 * MIB + writer.offset = 16 * MIB + + writer.open = mock.AsyncMock(side_effect=reopen_with_lost_tail) + fast_retry = AsyncRetry( + predicate=_is_write_retryable, initial=0.0, maximum=0.0, multiplier=1.0 + ) + + with pytest.raises( + exceptions.DataLoss, + match=f"Expected offset {18 * MIB}, got {16 * MIB}", + ): + await writer.close( + finalize_on_close=finalize_on_close, retry_policy=fast_retry + ) + + writer.open.assert_awaited_once() + assert not writer._is_stream_open + # The stream reopened by the retry is closed again, not leaked. + assert mock_stream.close.await_count == (1 if finalize_on_close else 2)