From e747797370361bdae6c27beee63f5f4bab36057c Mon Sep 17 00:00:00 2001 From: Li Yonghui Date: Sun, 15 Nov 2026 14:35:14 +0000 Subject: [PATCH 1/6] fix(storage): seek relative to initial_offset when retrying multi-call append `AsyncAppendableObjectWriter.append(data)` wraps only the current call's payload in `io.BytesIO(data)` starting at `initial_offset = self.offset or 0`, while `persisted_size` tracks the global object size persisted on the server. When a stream retry or redirect occurred on a second or later `append()` call, both `_WriteResumptionStrategy.recover_state_on_failure` and the stream reopen handler sought `user_buffer` to `persisted_size` instead of `persisted_size - initial_offset`. That caused silent truncation when `persisted_size >= len(data)` and shifted-byte corruption when `0 < initial_offset <= persisted_size < len(data)`. Track `initial_offset` on `_WriteState`, centralize buffer and counter rewinding in `_WriteState.reset_to_persisted()`, and raise `google.api_core.exceptions.DataLoss` if reconnecting reveals that unpersisted bytes from an earlier `append()` call were lost on the server. --- .../asyncio/async_appendable_object_writer.py | 22 +- .../retry/writes_resumption_strategy.py | 22 +- .../retry/test_writes_resumption_strategy.py | 49 +++++ .../test_async_appendable_object_writer.py | 193 ++++++++++++++++++ 4 files changed, 274 insertions(+), 12 deletions(-) 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..b4a14a5eaf07 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 @@ -571,6 +571,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 +621,19 @@ 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: + 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 +669,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) 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..ec15528a1128 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,57 @@ 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")]), + ], + ) + @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..e7d2ccbfa9c6 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 @@ -799,6 +799,199 @@ 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 + + @pytest.mark.parametrize( + "first_payload, second_payload, fail_at_offset, failure, expected_routing_token", + [ + # persisted_size > len(second_payload): must not seek past buffer EOF. + ( + 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, + ), + # initial_offset < persisted_size < len(second_payload): seek relative to initial_offset. + ( + 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, + ), + # Redirect error during second append: forwards routing_token and preserves offset. + ( + 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", + ), + ], + ) + @pytest.mark.asyncio + async def test_append_multi_call_retry_preserves_alignment( + self, + mock_appendable_writer, + first_payload, + second_payload, + fail_at_offset, + failure, + expected_routing_token, + ): + """Verify retries on subsequent append calls preserve byte alignment.""" + 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, 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) + 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() + 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 + + @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"]) From f88de785dfd3885c0a6dce50984c64f192a932a0 Mon Sep 17 00:00:00 2001 From: Li Yonghui Date: Tue, 17 Nov 2026 05:58:36 +0000 Subject: [PATCH 2/6] fix(storage): fail fast with DataLoss on close/finalize reconnect mismatch Address review feedback on the multi-call append retry fix. - close() and finalize() raised InternalServerError when a reconnect reported fewer bytes than were sent. _is_write_retryable treats that as retryable, so they reopened the stream until the retry deadline. Raise DataLoss instead, matching append(). - Correct the append() docstring. Bytes after the last flush_interval boundary are only durable after flush() or close(). - Add an unaligned multi-call append retry case (5 MiB + 5 MiB with a 4 MiB flush interval) and assert persisted_size and bytes_appended_since_last_flush. Add recovery boundary cases to the resumption strategy tests. --- .../asyncio/async_appendable_object_writer.py | 49 ++++++++------ .../retry/test_writes_resumption_strategy.py | 6 ++ .../test_async_appendable_object_writer.py | 67 ++++++++++++++++++- 3 files changed, 100 insertions(+), 22 deletions(-) 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 b4a14a5eaf07..a91ab2babbfa 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,22 @@ def _on_open_error(self, exc): self._created_generation = True self.generation = redirect_proto.generation + 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 +569,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. @@ -771,6 +790,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: @@ -803,14 +824,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 @@ -860,6 +874,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().") @@ -896,14 +912,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/tests/unit/asyncio/retry/test_writes_resumption_strategy.py b/packages/google-cloud-storage/tests/unit/asyncio/retry/test_writes_resumption_strategy.py index ec15528a1128..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 @@ -395,6 +395,12 @@ def test_write_state_initialization(self): (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 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 e7d2ccbfa9c6..c62dec6e9b81 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 ) @@ -839,18 +840,23 @@ async def fake_recv(): return server_bytes, open_metadata @pytest.mark.parametrize( - "first_payload, second_payload, fail_at_offset, failure, expected_routing_token", + "flush_interval, first_payload, second_payload, 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. ( + _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, ), # initial_offset < persisted_size < len(second_payload): seek relative to initial_offset. ( + _MAX_CHUNK_SIZE_BYTES, b"0" * _MAX_CHUNK_SIZE_BYTES, b"1" * _MAX_CHUNK_SIZE_BYTES + b"2" * _MAX_CHUNK_SIZE_BYTES @@ -858,9 +864,12 @@ async def fake_recv(): 2 * _MAX_CHUNK_SIZE_BYTES, exceptions.ServiceUnavailable("transient 503"), None, + 4 * _MAX_CHUNK_SIZE_BYTES, + 0, ), # Redirect error during second append: forwards routing_token and preserves offset. ( + _MAX_CHUNK_SIZE_BYTES, b"M" * _MAX_CHUNK_SIZE_BYTES, b"N" * 4096, _MAX_CHUNK_SIZE_BYTES, @@ -876,6 +885,21 @@ async def fake_recv(): ], ), "redirect-token-2", + _MAX_CHUNK_SIZE_BYTES, + 4096, + ), + # 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. + ( + 4 * MIB, + b"P" * (5 * MIB), + b"Q" * (5 * MIB), + 9 * MIB, + exceptions.ServiceUnavailable("transient 503"), + None, + 9 * MIB, + 1 * MIB, ), ], ) @@ -883,18 +907,21 @@ async def fake_recv(): async def test_append_multi_call_retry_preserves_alignment( self, mock_appendable_writer, + flush_interval, first_payload, second_payload, 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 writer = self._make_one( mock_appendable_writer["mock_client"], - writer_options={"FLUSH_INTERVAL_BYTES": _MAX_CHUNK_SIZE_BYTES}, + 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 @@ -914,6 +941,8 @@ async def test_append_multi_call_retry_preserves_alignment( 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", @@ -1355,3 +1384,37 @@ 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.""" + 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 + 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) + + with pytest.raises( + exceptions.DataLoss, + match=f"Expected offset {18 * MIB}, got {16 * MIB}", + ): + await writer.close(finalize_on_close=finalize_on_close) + + writer.open.assert_awaited_once() + assert not writer._is_stream_open From 81158a44e25ee3d8872b39670485324e49c4b3fa Mon Sep 17 00:00:00 2001 From: Li Yonghui Date: Tue, 17 Nov 2026 07:11:54 +0000 Subject: [PATCH 3/6] docs(storage): clarify close() return value in AsyncAppendableObjectWriter close() returns persisted_size, which is only refreshed by flush responses. Closing persists bytes appended after the last flush, but the returned value can be up to flush_interval bytes smaller than the object. Document this, and point to flush() before close() or writer.offset for the exact size. --- .../asyncio/async_appendable_object_writer.py | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) 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 a91ab2babbfa..ca3fd64a0bb6 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 @@ -778,10 +778,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). From 4c8a9fea86ea27235f3f07f7486ec59a92f2e1b2 Mon Sep 17 00:00:00 2001 From: Li Yonghui Date: Wed, 25 Nov 2026 03:31:52 +0000 Subject: [PATCH 4/6] fix(storage): close the reopened stream when a reconnect raises DataLoss Address review feedback on PR #19092. - append() reopens the stream before checking for lost bytes. On DataLoss it now closes that stream and marks the writer closed, so the stream isn't leaked and a later close(finalize_on_close=True) raises instead of finalizing the truncated object. - close() closes a stream reopened by a retry that then failed, instead of only clearing _is_stream_open. - Tests: build the multi-call retry payloads from (byte, length) segments inside the test with readable ids, so the junit XML shrinks from about 27 MB to 22 KB, and vary the bytes in the unaligned case so a wrong slice is caught. Use a fast retry policy in the close fail-fast test. --- .../asyncio/async_appendable_object_writer.py | 15 ++++- .../test_async_appendable_object_writer.py | 66 ++++++++++++++----- 2 files changed, 62 insertions(+), 19 deletions(-) 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 ca3fd64a0bb6..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,15 @@ 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. @@ -643,6 +652,9 @@ async def generator(): 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}, " @@ -838,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, 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 c62dec6e9b81..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 @@ -839,39 +839,48 @@ async def fake_recv(): 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_payload, second_payload, fail_at_offset, failure, " + "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, + [(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, + [(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, + [(b"M", _MAX_CHUNK_SIZE_BYTES)], + [(b"N", 4096)], _MAX_CHUNK_SIZE_BYTES, exceptions.Aborted( "redirect", @@ -887,19 +896,21 @@ async def fake_recv(): "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" * (5 * MIB), - b"Q" * (5 * 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", ), ], ) @@ -908,8 +919,8 @@ async def test_append_multi_call_retry_preserves_alignment( self, mock_appendable_writer, flush_interval, - first_payload, - second_payload, + first_segments, + second_segments, fail_at_offset, failure, expected_routing_token, @@ -919,6 +930,8 @@ async def test_append_multi_call_retry_preserves_alignment( """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}, @@ -961,6 +974,7 @@ async def test_append_multi_call_unpersisted_prior_append_raises_data_loss( 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 @@ -982,6 +996,12 @@ async def test_append_multi_call_unpersisted_prior_append_raises_data_loss( 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( @@ -1391,10 +1411,13 @@ 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") @@ -1409,12 +1432,19 @@ async def reopen_with_lost_tail(*args, **kwargs): 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) + 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) From f7212a235b80af38598fcb46d54a82d28f10c113 Mon Sep 17 00:00:00 2001 From: Li Yonghui Date: Wed, 25 Nov 2026 03:33:06 +0000 Subject: [PATCH 5/6] fix(storage): replay unflushed tail after reconnect in AsyncAppendableObjectWriter append() only flushes every flush_interval bytes, and the counter carries across calls. When a call does not end on a flush boundary, its trailing bytes are sent but not flushed. On Zonal buckets the server can drop them if the stream breaks shortly afterwards. The writer no longer held those bytes, so a reconnect during the next append() raised DataLoss. Keep the bytes sent since the last server-confirmed persisted offset in a bytearray and replay them after a reconnect. - After each append(), add the unconfirmed part of data to the tail and drop bytes the server confirmed (flush responses, flush(), state_lookup()). The tail normally stays below flush_interval and is capped at 2 * flush_interval. - The normal append() path is unchanged. Only when a reconnect reports persisted_size before the start of data does append() swap in io.BytesIO(tail + data) and move _WriteState.initial_offset to the tail start, so reset_to_persisted() rewinds into the tail. - close() and finalize() resend the lost tail bytes with append() after a reconnect, then close, instead of raising DataLoss. - DataLoss remains when the server reports persisted_size below the tail start. Fixes #19101 # Conflicts: # packages/google-cloud-storage/google/cloud/storage/asyncio/async_appendable_object_writer.py # packages/google-cloud-storage/tests/unit/asyncio/test_async_appendable_object_writer.py --- .../asyncio/async_appendable_object_writer.py | 92 +++++-- .../test_async_appendable_object_writer.py | 239 ++++++++++++++++-- 2 files changed, 289 insertions(+), 42 deletions(-) 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 cb2597448237..90a160484ebd 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 @@ -311,6 +311,11 @@ def __init__( f"flush_interval must be a multiple of {_MAX_CHUNK_SIZE_BYTES}, but provided {self.flush_interval}" ) self.bytes_appended_since_last_flush = 0 + # Bytes sent since the last server-confirmed persisted offset, + # starting at `_tail_offset`. They are replayed if the stream breaks + # and the server drops unflushed bytes from earlier calls. + self._tail = bytearray() + self._tail_offset = 0 self._routing_token: Optional[str] = None self.object_resource: Optional[_storage_v2.Object] = None self._flush_count = 0 @@ -425,6 +430,7 @@ async def state_lookup(self) -> int: ) response = await self.write_obj_stream.recv() self.persisted_size = response.persisted_size + self._trim_tail(self.persisted_size) return self.persisted_size def _on_open_error(self, exc): @@ -450,6 +456,63 @@ async def _abort_stream(self) -> None: logger.debug(f"Closing the write stream resulted in: {e}") self._is_stream_open = False + def _trim_tail(self, confirmed_offset: Optional[int]) -> None: + """Drops tail bytes before `confirmed_offset`, which the server persisted.""" + bytes_to_drop = (confirmed_offset or 0) - self._tail_offset + if bytes_to_drop > 0: + del self._tail[:bytes_to_drop] + self._tail_offset = confirmed_offset + + def _record_tail(self, data: bytes, data_offset: int, confirmed_offset: int): + """Keeps the part of `data` the server has not confirmed as persisted.""" + if self._tail_offset + len(self._tail) != data_offset: + self._tail.clear() + self._tail_offset = data_offset + self._trim_tail(confirmed_offset) + keep_from = self._tail_offset + len(self._tail) - data_offset + self._tail += memoryview(data).cast("B")[keep_from:] + # Normally less than flush_interval. Cap it in case confirmations lag. + self._trim_tail(self._tail_offset + len(self._tail) - 2 * self.flush_interval) + + async def _rewind_into_tail(self, write_state: _WriteState, data: bytes) -> None: + """Prepends the tail to the buffer after a reconnect lost earlier bytes. + + Called when the server's persisted size is before the start of the + current buffer. Raises DataLoss if the tail does not cover the gap. + """ + tail_precedes_buffer = ( + self._tail_offset + len(self._tail) == write_state.initial_offset + ) + earliest_held = ( + self._tail_offset if tail_precedes_buffer else write_state.initial_offset + ) + if (self.persisted_size or 0) < earliest_held: + # 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 >= {earliest_held}, " + f"got {self.persisted_size}." + ) + write_state.user_buffer = io.BytesIO(b"".join([self._tail, data])) + write_state.initial_offset = self._tail_offset + + async def _replay_lost_tail(self, expected_offset: Optional[int]) -> None: + """After a reconnect in close() or finalize(), resends lost tail bytes. + + Raises DataLoss if the server lost bytes the tail no longer holds. + """ + if ( + self.offset is not None + and expected_offset == self._tail_offset + len(self._tail) + and self._tail_offset <= self.offset < expected_offset + ): + lost_bytes = bytes(self._tail[self.offset - self._tail_offset :]) + self.bytes_appended_since_last_flush = 0 + await self.append(lost_bytes) + self._raise_if_offset_lost(expected_offset) + def _raise_if_offset_lost(self, expected_offset: Optional[int]) -> None: """Raises DataLoss if a reconnect reports fewer bytes than were sent. @@ -582,9 +645,8 @@ async def append( 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`. + ``flush()`` or ``close()``. The writer keeps those bytes and resends + them if the stream breaks and the server dropped them. :type data: bytes :param data: The bytes to append to the object. @@ -600,8 +662,8 @@ async def append( :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. + stream failure reveals that the server lost bytes the writer no + longer holds. """ if not self._is_stream_open: raise ValueError("Stream is not open. Call open() before append().") @@ -617,6 +679,7 @@ async def append( retry_policy = AsyncRetry(predicate=_is_write_retryable) strategy = _WriteResumptionStrategy() + start_offset = self.offset or 0 buffer = io.BytesIO(data) attempt_count = 0 @@ -652,14 +715,7 @@ async def generator(): 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}." - ) + await self._rewind_into_tail(write_state, data) write_state.persisted_size = self.persisted_size write_state.write_handle = self.write_handle @@ -700,7 +756,7 @@ async def generator(): buffer, self.flush_interval, enable_checksum=enable_checksum, - initial_offset=self.offset or 0, + initial_offset=start_offset, ) write_state.write_handle = self.write_handle write_state.persisted_size = self.persisted_size @@ -715,6 +771,7 @@ async def generator(): # Sync local markers self.bytes_appended_since_last_flush = write_state.bytes_since_last_flush self.offset = write_state.bytes_sent + self._record_tail(data, start_offset, write_state.persisted_size or 0) async def simple_flush(self) -> None: """Flushes the data to the server. @@ -759,6 +816,7 @@ async def flush(self) -> int: self.persisted_size = response.persisted_size self.offset = self.persisted_size self.bytes_appended_since_last_flush = 0 + self._trim_tail(self.persisted_size) return self.persisted_size async def close( @@ -842,9 +900,10 @@ async def _do_close(): ) self._is_stream_open = False await self.open() - self._raise_if_offset_lost(expected_offset) + await self._replay_lost_tail(expected_offset) await self.write_obj_stream.close() + self._tail.clear() return self.persisted_size try: @@ -931,12 +990,13 @@ async def _do_finalize(): ) self._is_stream_open = False await self.open() - self._raise_if_offset_lost(expected_offset) + await self._replay_lost_tail(expected_offset) await self.write_obj_stream.send(finalize_req) response = await self.write_obj_stream.recv() self.object_resource = response.resource self.persisted_size = self.object_resource.size + self._tail.clear() return self.object_resource try: 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 ff0ce80ce616..564bf7e050e4 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 @@ -962,46 +962,233 @@ async def test_append_multi_call_retry_preserves_alignment( f"routing_token={expected_routing_token}", ) in (open_metadata[-1] or []) + @staticmethod + def _fast_retry(): + from google.api_core.retry_async import AsyncRetry + + return AsyncRetry( + predicate=_is_write_retryable, initial=0.0, maximum=0.0, multiplier=1.0 + ) + + @pytest.mark.parametrize( + "flush_interval, payloads, fail_at_offset", + [ + # Unflushed 1 MiB from the first append is lost when the stream + # resets at 6 MiB, before the next flush at 9 MiB. + (4 * MIB, [b"P" * (5 * MIB), b"Q" * (5 * MIB)], 6 * MIB), + # 1 MiB appends: the reset at 5 MiB loses the 5th append. + (4 * MIB, [bytes([65 + i]) * MIB for i in range(10)], 5 * MIB), + # Many small appends share one flush window (gcsfs ZonalFile.write). + ( + _MAX_CHUNK_SIZE_BYTES, + [bytes([i % 251]) * (64 * 1024) for i in range(100)], + 3 * MIB, + ), + ], + ) @pytest.mark.asyncio - async def test_append_multi_call_unpersisted_prior_append_raises_data_loss( + async def test_append_multi_call_replays_lost_tail_from_prior_appends( + self, mock_appendable_writer, flush_interval, payloads, fail_at_offset + ): + """Verify a reset that drops unflushed bytes of earlier calls recovers.""" + writer = self._make_one( + mock_appendable_writer["mock_client"], + writer_options={"FLUSH_INTERVAL_BYTES": flush_interval}, + ) + mock_stream = mock_appendable_writer["mock_stream"] + server_bytes, _ = self._attach_in_memory_server( + mock_stream, + fail_at_offset, + exceptions.ServiceUnavailable("stream reset"), + ) + + await writer.open(retry_policy=self._fast_retry()) + for payload in payloads: + await writer.append(payload, retry_policy=self._fast_retry()) + assert (writer._tail_offset + len(writer._tail)) == writer.offset + assert len(writer._tail) < flush_interval + + expected_payload = b"".join(payloads) + assert bytes(server_bytes) == expected_payload + assert writer.offset == len(expected_payload) + assert mock_stream.open.await_count == 2 + + @pytest.mark.asyncio + async def test_append_replays_copy_when_caller_reuses_buffer( self, mock_appendable_writer ): - """Verify reconnect losing unpersisted bytes from a prior append raises DataLoss.""" - from google.api_core.retry_async import AsyncRetry + """Verify the tail is a copy and the caller's buffer is released.""" + writer = self._make_one( + mock_appendable_writer["mock_client"], + writer_options={"FLUSH_INTERVAL_BYTES": 4 * MIB}, + ) + server_bytes, _ = self._attach_in_memory_server( + mock_appendable_writer["mock_stream"], + MIB, + exceptions.ServiceUnavailable("stream reset"), + ) + await writer.open(retry_policy=self._fast_retry()) + + reused_buffer = bytearray(b"a" * MIB) + await writer.append(reused_buffer, retry_policy=self._fast_retry()) + # Resizing raises BufferError if append() still exports the buffer. + reused_buffer.extend(b"z") + reused_buffer[:MIB] = b"z" * MIB + await writer.append(b"b" * MIB, retry_policy=self._fast_retry()) + + assert bytes(server_bytes) == b"a" * MIB + b"b" * MIB + @pytest.mark.asyncio + async def test_append_raises_data_loss_when_server_lost_bytes_before_tail( + self, mock_appendable_writer + ): + """Verify DataLoss when the server reports less than the tail start.""" writer = self._make_one(mock_appendable_writer["mock_client"]) mock_stream = mock_appendable_writer["mock_stream"] - mock_stream.persisted_size = 0 + mock_stream.persisted_size = 100 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 + await writer.append(b"x" * 10) + assert (writer._tail_offset, len(writer._tail)) == (100, 10) + mock_stream.persisted_size = 50 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="Expected persisted_size >= 100"): + await writer.append(b"y" * 10, retry_policy=self._fast_retry()) + + @pytest.mark.asyncio + async def test_flush_and_state_lookup_trim_tail(self, mock_appendable_writer): + """Verify the tail shrinks only when the server confirms persistence.""" + writer = self._make_one( + mock_appendable_writer["mock_client"], + writer_options={"FLUSH_INTERVAL_BYTES": 4 * MIB}, ) + self._attach_in_memory_server( + mock_appendable_writer["mock_stream"], + 100 * MIB, + exceptions.ServiceUnavailable("unused"), + ) + await writer.open() - with pytest.raises( - exceptions.DataLoss, match="Unrecoverable data loss during reconnect" - ): - await writer.append(b"second-append", retry_policy=fast_retry) + await writer.append(b"a" * MIB) + assert (writer._tail_offset, len(writer._tail)) == (0, MIB) + + # simple_flush() gets no confirmation, so the tail is kept. + await writer.simple_flush() + assert len(writer._tail) == MIB + # state_lookup() reports the persisted size and trims the tail. + await writer.state_lookup() + assert (writer._tail_offset, len(writer._tail)) == (MIB, 0) + await writer.append(b"b" * MIB) + assert (writer._tail_offset, len(writer._tail)) == (MIB, MIB) + await writer.flush() + assert (writer._tail_offset, len(writer._tail)) == (2 * MIB, 0) + + @pytest.mark.asyncio + async def test_state_lookup_inside_tail_drops_whole_segments( + self, mock_appendable_writer + ): + """Verify a confirmation inside the tail drops only fully persisted segments.""" + writer = self._make_one( + mock_appendable_writer["mock_client"], + writer_options={"FLUSH_INTERVAL_BYTES": 4 * MIB}, + ) + self._attach_in_memory_server( + mock_appendable_writer["mock_stream"], + 100 * MIB, + exceptions.ServiceUnavailable("unused"), + ) + await writer.open() + + await writer.append(b"a" * MIB) + # The fake server persists 1 MiB here, but the writer isn't told. + await writer.simple_flush() + await writer.append(b"b" * MIB) + await writer.append(b"c" * MIB) + assert (writer._tail_offset, len(writer._tail)) == (0, 3 * MIB) + + await writer.state_lookup() + assert (writer._tail_offset, len(writer._tail)) == (MIB, 2 * MIB) + + @pytest.mark.asyncio + async def test_append_caps_tail_at_twice_flush_interval( + self, mock_appendable_writer + ): + """Verify the oldest tail bytes are dropped past 2 * flush_interval.""" + writer = self._make_one( + mock_appendable_writer["mock_client"], + writer_options={"FLUSH_INTERVAL_BYTES": _MAX_CHUNK_SIZE_BYTES}, + ) + self._attach_in_memory_server( + mock_appendable_writer["mock_stream"], + 100 * MIB, + exceptions.ServiceUnavailable("unused"), + ) + await writer.open() + + # simple_flush() resets the flush counter without a confirmation, so + # the tail grows past flush_interval. + for payload_size in [MIB // 2, 3 * MIB // 2, 3 * MIB // 2, 3 * MIB // 2]: + await writer.append(b"t" * payload_size) + await writer.simple_flush() + + # 5 MiB of tail exceeds the 4 MiB cap, so the oldest 1 MiB is dropped. + assert writer._tail_offset == MIB + assert len(writer._tail) == 2 * _MAX_CHUNK_SIZE_BYTES + assert (writer._tail_offset + len(writer._tail)) == writer.offset + + @pytest.mark.parametrize("finalize_on_close", [False, True]) + @pytest.mark.asyncio + async def test_close_replays_lost_tail_after_reconnect( + self, mock_appendable_writer, finalize_on_close + ): + """Verify close() and finalize() resend lost tail bytes, then close.""" + writer = self._make_one( + mock_appendable_writer["mock_client"], + writer_options={"FLUSH_INTERVAL_BYTES": 4 * MIB}, + ) + mock_stream = mock_appendable_writer["mock_stream"] + server_bytes, _ = self._attach_in_memory_server( + mock_stream, 100 * MIB, exceptions.ServiceUnavailable("unused") + ) + await writer.open() + # 3 MiB unflushed tail: the replay spans two 2 MiB chunks. + await writer.append(b"c" * (7 * MIB)) + assert (writer._tail_offset, len(writer._tail)) == (4 * MIB, 3 * MIB) + + stream_reset = exceptions.ServiceUnavailable("stream reset") + if finalize_on_close: + server_send = mock_stream.send.side_effect + finish_write_attempts = [] + + async def fail_first_finish_write(request): + if request.finish_write: + finish_write_attempts.append(request) + if len(finish_write_attempts) == 1: + raise stream_reset + await server_send(request) + + mock_stream.send.side_effect = fail_first_finish_write + else: + close_attempts = [] + + async def fail_first_close(): + close_attempts.append(None) + if len(close_attempts) == 1: + raise stream_reset + + mock_stream.close.side_effect = fail_first_close + + await writer.close( + finalize_on_close=finalize_on_close, retry_policy=self._fast_retry() + ) + + assert bytes(server_bytes) == b"c" * (7 * MIB) 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) + assert len(writer._tail) == 0 + if finalize_on_close: + assert len(finish_write_attempts) == 2 @pytest.mark.asyncio async def test_append_from_file_multi_block_retry_preserves_data( From 508f3d13f73db85cd65db232267e8bb825e49bb5 Mon Sep 17 00:00:00 2001 From: Li Yonghui Date: Wed, 25 Nov 2026 03:58:46 +0000 Subject: [PATCH 6/6] fix(storage): recover from a failed append and honor close() retry policy Address review feedback on PR #19102. - If append() fails after a retry reopened the stream (retries exhausted, a non-retryable error, or cancellation), self.offset could be left at the server's persisted size while the tail still held earlier bytes, so a later close(finalize_on_close=True) finalized a truncated object. append() now restores self.offset to the end of the acknowledged bytes, resets the flush counter, cancels the stream, and sets write_obj_stream to None. The next append(), flush(), simple_flush(), state_lookup(), close() or finalize() reconnects and replays the tail. If the server persisted part of the failed append, it raises DataLoss and closes the writer instead. - close() and finalize() clear the tail in finally, so a failed replay doesn't leave it behind. - The reopen and replay inside close() and finalize() use the caller's retry policy, limited to the time left before its deadline. - Tests: the in-memory server now handles finish_write and persists on a graceful close, so the close replay test asserts the returned sizes. Replay workloads use (byte, length) segments with readable ids, and the trim test no longer says "segments". --- .../asyncio/async_appendable_object_writer.py | 116 ++++++- .../test_async_appendable_object_writer.py | 294 ++++++++++++++---- 2 files changed, 343 insertions(+), 67 deletions(-) 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 90a160484ebd..5d6d68cb558a 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 @@ -12,8 +12,10 @@ # See the License for the specific language governing permissions and # limitations under the License. +import contextlib import io import logging +import time from dataclasses import dataclass from io import BufferedReader from typing import Dict, List, Optional, Tuple, Union @@ -422,6 +424,7 @@ async def state_lookup(self) -> int: if not self._is_stream_open: raise ValueError("Stream is not open. Call open() before state_lookup().") + await self._reconnect_if_dropped() async with self._trace_span("Storage.AsyncAppendableObjectWriter.stateLookup"): await self.write_obj_stream.send( _storage_v2.BidiWriteObjectRequest( @@ -498,8 +501,12 @@ async def _rewind_into_tail(self, write_state: _WriteState, data: bytes) -> None write_state.user_buffer = io.BytesIO(b"".join([self._tail, data])) write_state.initial_offset = self._tail_offset - async def _replay_lost_tail(self, expected_offset: Optional[int]) -> None: - """After a reconnect in close() or finalize(), resends lost tail bytes. + async def _replay_lost_tail( + self, + expected_offset: Optional[int], + retry_policy: Optional[AsyncRetry] = None, + ) -> None: + """After a reconnect, resends tail bytes the server lost. Raises DataLoss if the server lost bytes the tail no longer holds. """ @@ -510,9 +517,60 @@ async def _replay_lost_tail(self, expected_offset: Optional[int]) -> None: ): lost_bytes = bytes(self._tail[self.offset - self._tail_offset :]) self.bytes_appended_since_last_flush = 0 - await self.append(lost_bytes) + await self.append(lost_bytes, retry_policy=retry_policy) self._raise_if_offset_lost(expected_offset) + @staticmethod + def _remaining_retry_policy( + retry_policy: Optional[AsyncRetry], deadline_at: Optional[float] + ) -> AsyncRetry: + """The caller's retry policy, limited to the time left before deadline_at.""" + if retry_policy is None: + retry_policy = AsyncRetry(predicate=_is_write_retryable) + if deadline_at is None: + return retry_policy + return retry_policy.with_timeout(max(0.0, deadline_at - time.monotonic())) + + async def _drop_stream_after_failed_append(self, start_offset: int) -> None: + """Forgets the stream after append() failed, so the next call reconnects. + + Bytes before `start_offset` were acknowledged by earlier appends, and + the tail still holds the unpersisted ones. The stream is cancelled + rather than closed, so the server doesn't persist half of this call. + """ + self.offset = start_offset + self.bytes_appended_since_last_flush = 0 + stream, self.write_obj_stream = self.write_obj_stream, None + self._is_stream_open = True + if stream is not None and stream.is_stream_open: + with contextlib.suppress(Exception): + await stream.socket_like_rpc.close() + + async def _reconnect_if_dropped( + self, retry_policy: Optional[AsyncRetry] = None + ) -> None: + """Reopens the stream dropped by a failed append() and replays the tail. + + Raises DataLoss, and closes the writer, if the server lost bytes the + tail no longer holds, or persisted part of the failed append(). + """ + if self.write_obj_stream is not None or not self._is_stream_open: + return + expected_offset = self.offset + self._is_stream_open = False + await self.open(retry_policy=retry_policy) + try: + if (self.persisted_size or 0) > (expected_offset or 0): + raise exceptions.DataLoss( + f"The server persisted {self.persisted_size} bytes, more than " + f"the {expected_offset} bytes acknowledged before append() " + f"failed." + ) + await self._replay_lost_tail(expected_offset, retry_policy) + except exceptions.DataLoss: + await self._abort_stream() + raise + def _raise_if_offset_lost(self, expected_offset: Optional[int]) -> None: """Raises DataLoss if a reconnect reports fewer bytes than were sent. @@ -678,6 +736,7 @@ async def append( if retry_policy is None: retry_policy = AsyncRetry(predicate=_is_write_retryable) + await self._reconnect_if_dropped(retry_policy) strategy = _WriteResumptionStrategy() start_offset = self.offset or 0 buffer = io.BytesIO(data) @@ -766,7 +825,14 @@ async def generator(): strategy, lambda r, s: send_and_recv_generator(r, s, metadata), ) - await retry_manager.execute({"write_state": write_state}, retry_policy) + try: + await retry_manager.execute({"write_state": write_state}, retry_policy) + except exceptions.DataLoss: + raise + except BaseException: + # A retry may have reopened the stream and moved self.offset. + await self._drop_stream_after_failed_append(start_offset) + raise # Sync local markers self.bytes_appended_since_last_flush = write_state.bytes_since_last_flush @@ -785,6 +851,7 @@ async def simple_flush(self) -> None: if not self._is_stream_open: raise ValueError("Stream is not open. Call open() before simple_flush().") + await self._reconnect_if_dropped() async with self._trace_span("Storage.AsyncAppendableObjectWriter.simpleFlush"): await self.write_obj_stream.send( _storage_v2.BidiWriteObjectRequest( @@ -805,6 +872,7 @@ async def flush(self) -> int: if not self._is_stream_open: raise ValueError("Stream is not open. Call open() before flush().") + await self._reconnect_if_dropped() async with self._trace_span("Storage.AsyncAppendableObjectWriter.flush"): await self.write_obj_stream.send( _storage_v2.BidiWriteObjectRequest( @@ -885,10 +953,18 @@ async def close( retry_policy=retry_policy, ) + caller_retry_policy = retry_policy retry_policy = self._merge_retry_policy(retry_policy) + deadline_at = ( + time.monotonic() + retry_policy.timeout + if retry_policy.timeout is not None + else None + ) + + def remaining_retry_policy(): + return self._remaining_retry_policy(caller_retry_policy, deadline_at) attempt_count = 0 - expected_offset = self.offset async def _do_close(): nonlocal attempt_count @@ -899,18 +975,22 @@ async def _do_close(): f"Re-opening the stream for close retry attempt: {attempt_count}" ) self._is_stream_open = False - await self.open() - await self._replay_lost_tail(expected_offset) + await self.open(retry_policy=remaining_retry_policy()) + await self._replay_lost_tail( + expected_offset, remaining_retry_policy() + ) await self.write_obj_stream.close() - self._tail.clear() return self.persisted_size try: + await self._reconnect_if_dropped(remaining_retry_policy()) + expected_offset = self.offset return await retry_policy(_do_close)() finally: # Closes a stream reopened by a retry that then failed. await self._abort_stream() + self._tail.clear() async def finalize( self, @@ -975,10 +1055,18 @@ async def finalize( ) async with self._trace_span("Storage.AsyncAppendableObjectWriter.finalize"): + caller_retry_policy = retry_policy retry_policy = self._merge_retry_policy(retry_policy) + deadline_at = ( + time.monotonic() + retry_policy.timeout + if retry_policy.timeout is not None + else None + ) + + def remaining_retry_policy(): + return self._remaining_retry_policy(caller_retry_policy, deadline_at) attempt_count = 0 - expected_offset = self.offset async def _do_finalize(): nonlocal attempt_count @@ -989,19 +1077,23 @@ async def _do_finalize(): f"Re-opening the stream for finalize retry attempt: {attempt_count}" ) self._is_stream_open = False - await self.open() - await self._replay_lost_tail(expected_offset) + await self.open(retry_policy=remaining_retry_policy()) + await self._replay_lost_tail( + expected_offset, remaining_retry_policy() + ) await self.write_obj_stream.send(finalize_req) response = await self.write_obj_stream.recv() self.object_resource = response.resource self.persisted_size = self.object_resource.size - self._tail.clear() return self.object_resource try: + await self._reconnect_if_dropped(remaining_retry_policy()) + expected_offset = self.offset return await retry_policy(_do_finalize)() finally: + self._tail.clear() if self.write_obj_stream: try: await self.write_obj_stream.close() 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 564bf7e050e4..9afc8c7169dd 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 @@ -806,6 +806,7 @@ def _attach_in_memory_server(mock_stream, fail_at_offset, failure): server_bytes = bytearray() persisted_bytes = 0 failed_once = False + finished = False open_metadata = [] async def fake_open(metadata=None): @@ -817,26 +818,41 @@ async def fake_open(metadata=None): del server_bytes[persisted_bytes:] async def fake_send(request): - nonlocal persisted_bytes, failed_once + nonlocal persisted_bytes, failed_once, finished chunk_content = request.checksummed_data.content if chunk_content: if not failed_once and request.write_offset >= fail_at_offset: failed_once = True + # The broken stream can't be closed gracefully. + mock_stream.is_stream_open = False raise failure assert request.write_offset == len(server_bytes) server_bytes.extend(chunk_content) - if request.flush: + if request.flush or request.finish_write: persisted_bytes = len(server_bytes) + finished = finished or request.finish_write async def fake_recv(): + if finished: + return storage_type.BidiWriteObjectResponse( + resource=storage_type.Object(size=persisted_bytes) + ) return storage_type.BidiWriteObjectResponse( persisted_size=persisted_bytes, write_handle=storage_type.BidiWriteHandle(handle=WRITE_HANDLE), ) + async def fake_close(): + # A graceful close persists everything sent on the stream. + nonlocal persisted_bytes + persisted_bytes = len(server_bytes) + mock_stream.is_stream_open = False + mock_stream.open.side_effect = fake_open mock_stream.send.side_effect = fake_send mock_stream.recv.side_effect = fake_recv + mock_stream.close.side_effect = fake_close + mock_stream.socket_like_rpc.close = AsyncMock() return server_bytes, open_metadata @staticmethod @@ -971,26 +987,38 @@ def _fast_retry(): ) @pytest.mark.parametrize( - "flush_interval, payloads, fail_at_offset", + "flush_interval, payload_segments, fail_at_offset", [ # Unflushed 1 MiB from the first append is lost when the stream # resets at 6 MiB, before the next flush at 9 MiB. - (4 * MIB, [b"P" * (5 * MIB), b"Q" * (5 * MIB)], 6 * MIB), + pytest.param( + 4 * MIB, + [[(b"P", 5 * MIB)], [(b"Q", 5 * MIB)]], + 6 * MIB, + id="2x5MiB-reset-at-6MiB", + ), # 1 MiB appends: the reset at 5 MiB loses the 5th append. - (4 * MIB, [bytes([65 + i]) * MIB for i in range(10)], 5 * MIB), + pytest.param( + 4 * MIB, + [[(bytes([65 + i]), MIB)] for i in range(10)], + 5 * MIB, + id="10x1MiB-reset-at-5MiB", + ), # Many small appends share one flush window (gcsfs ZonalFile.write). - ( + pytest.param( _MAX_CHUNK_SIZE_BYTES, - [bytes([i % 251]) * (64 * 1024) for i in range(100)], + [[(bytes([i % 251]), 64 * 1024)] for i in range(100)], 3 * MIB, + id="100x64KiB-reset-at-3MiB", ), ], ) @pytest.mark.asyncio async def test_append_multi_call_replays_lost_tail_from_prior_appends( - self, mock_appendable_writer, flush_interval, payloads, fail_at_offset + self, mock_appendable_writer, flush_interval, payload_segments, fail_at_offset ): """Verify a reset that drops unflushed bytes of earlier calls recovers.""" + payloads = [self._payload(segments) for segments in payload_segments] writer = self._make_one( mock_appendable_writer["mock_client"], writer_options={"FLUSH_INTERVAL_BYTES": flush_interval}, @@ -1086,10 +1114,10 @@ async def test_flush_and_state_lookup_trim_tail(self, mock_appendable_writer): assert (writer._tail_offset, len(writer._tail)) == (2 * MIB, 0) @pytest.mark.asyncio - async def test_state_lookup_inside_tail_drops_whole_segments( + async def test_state_lookup_inside_tail_trims_confirmed_bytes( self, mock_appendable_writer ): - """Verify a confirmation inside the tail drops only fully persisted segments.""" + """Verify a confirmation inside the tail drops only the confirmed bytes.""" writer = self._make_one( mock_appendable_writer["mock_client"], writer_options={"FLUSH_INTERVAL_BYTES": 4 * MIB}, @@ -1166,21 +1194,25 @@ async def fail_first_finish_write(request): if request.finish_write: finish_write_attempts.append(request) if len(finish_write_attempts) == 1: + mock_stream.is_stream_open = False raise stream_reset await server_send(request) mock_stream.send.side_effect = fail_first_finish_write else: + server_close = mock_stream.close.side_effect close_attempts = [] async def fail_first_close(): close_attempts.append(None) if len(close_attempts) == 1: + mock_stream.is_stream_open = False raise stream_reset + await server_close() mock_stream.close.side_effect = fail_first_close - await writer.close( + result = await writer.close( finalize_on_close=finalize_on_close, retry_policy=self._fast_retry() ) @@ -1189,6 +1221,202 @@ async def fail_first_close(): assert len(writer._tail) == 0 if finalize_on_close: assert len(finish_write_attempts) == 2 + assert result.size == 7 * MIB + assert writer.persisted_size == 7 * MIB + else: + # close() returns the last confirmed size (see its docstring). + assert result == 4 * MIB + + @pytest.mark.parametrize("next_step", ["finalize", "retry-append"]) + @pytest.mark.asyncio + async def test_failed_append_after_reopen_recovers_on_next_call( + self, mock_appendable_writer, next_step + ): + """Verify a failed append after a mid-retry reopen can't truncate the object.""" + writer = self._make_one( + mock_appendable_writer["mock_client"], + writer_options={"FLUSH_INTERVAL_BYTES": 4 * MIB}, + ) + mock_stream = mock_appendable_writer["mock_stream"] + server_bytes, _ = self._attach_in_memory_server( + mock_stream, 6 * MIB, exceptions.ServiceUnavailable("stream reset") + ) + server_send = mock_stream.send.side_effect + fail_after_reopen = [True] + + async def send(request): + # The retry reopens the stream, then fails for good. + if ( + mock_stream.open.await_count == 2 + and fail_after_reopen[0] + and request.checksummed_data.content + ): + fail_after_reopen[0] = False + # The stream is still open, so the writer must cancel it. + raise exceptions.BadRequest("fails after reopen") + await server_send(request) + + mock_stream.send.side_effect = send + first = self._payload([(b"A", 4 * MIB), (b"a", MIB)]) + second = self._payload([(b"B", 3 * MIB), (b"b", 2 * MIB)]) + + await writer.open() + await writer.append(first, retry_policy=self._fast_retry()) + with pytest.raises(exceptions.BadRequest): + await writer.append(second, retry_policy=self._fast_retry()) + + # The writer forgets the stream and goes back to the acknowledged size. + assert writer.offset == len(first) + assert writer.write_obj_stream is None + assert writer.is_stream_open + mock_stream.socket_like_rpc.close.assert_awaited_once() + + expected = first + if next_step == "retry-append": + await writer.append(second, retry_policy=self._fast_retry()) + expected = first + second + result = await writer.close( + finalize_on_close=True, retry_policy=self._fast_retry() + ) + + assert bytes(server_bytes) == expected + assert result.size == len(expected) + + @pytest.mark.asyncio + async def test_failed_append_partly_persisted_raises_data_loss_on_next_call( + self, mock_appendable_writer + ): + """Verify the next call fails if the server kept part of a failed append.""" + writer = self._make_one( + mock_appendable_writer["mock_client"], + writer_options={"FLUSH_INTERVAL_BYTES": _MAX_CHUNK_SIZE_BYTES}, + ) + self._attach_in_memory_server( + mock_appendable_writer["mock_stream"], + 3 * MIB, + exceptions.BadRequest("fails after a flush"), + ) + await writer.open() + await writer.append(b"a" * MIB) + # The flush at 3 MiB persists part of this call before it fails. + with pytest.raises(exceptions.BadRequest): + await writer.append(b"b" * (4 * MIB)) + assert writer.offset == MIB + + with pytest.raises(exceptions.DataLoss, match="more than the 1048576 bytes"): + await writer.append(b"c" * MIB) + 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_close_passes_remaining_retry_policy_to_replay( + self, mock_appendable_writer + ): + """Verify the close() replay keeps the caller's deadline and on_error.""" + from google.api_core.retry_async import AsyncRetry + + writer = self._make_one( + mock_appendable_writer["mock_client"], + writer_options={"FLUSH_INTERVAL_BYTES": 4 * MIB}, + ) + mock_stream = mock_appendable_writer["mock_stream"] + self._attach_in_memory_server( + mock_stream, 100 * MIB, exceptions.ServiceUnavailable("unused") + ) + await writer.open() + await writer.append(b"c" * (7 * MIB)) + + server_close = mock_stream.close.side_effect + close_attempts = [] + + async def fail_first_close(): + close_attempts.append(None) + if len(close_attempts) == 1: + mock_stream.is_stream_open = False + raise exceptions.ServiceUnavailable("stream reset") + await server_close() + + mock_stream.close.side_effect = fail_first_close + replay_policies = [] + original_append = writer.append + + async def recording_append(data, retry_policy=None, **kwargs): + replay_policies.append(retry_policy) + await original_append(data, retry_policy=retry_policy, **kwargs) + + writer.append = recording_append + errors = [] + + def on_error(exc): + errors.append(exc) + + caller_policy = AsyncRetry( + predicate=_is_write_retryable, + initial=0.0, + maximum=0.0, + multiplier=1.0, + timeout=5.0, + on_error=on_error, + ) + + await writer.close(retry_policy=caller_policy) + + [replay_policy] = replay_policies + assert 0 < replay_policy.timeout <= 5.0 + assert replay_policy._on_error is on_error + assert len(errors) == 1 + + def test_remaining_retry_policy_without_deadline_keeps_policy(self): + """Verify a policy without a timeout is passed through unchanged.""" + from google.api_core.retry_async import AsyncRetry + + caller_policy = AsyncRetry(predicate=_is_write_retryable, timeout=None) + assert ( + AsyncAppendableObjectWriter._remaining_retry_policy(caller_policy, None) + is caller_policy + ) + default_policy = AsyncAppendableObjectWriter._remaining_retry_policy(None, None) + assert default_policy._predicate is _is_write_retryable + + @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.""" + 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) + + 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=self._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) @pytest.mark.asyncio async def test_append_from_file_multi_block_retry_preserves_data( @@ -1591,47 +1819,3 @@ 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)