From e747797370361bdae6c27beee63f5f4bab36057c Mon Sep 17 00:00:00 2001 From: Li Yonghui Date: Sun, 15 Nov 2026 14:35:14 +0000 Subject: [PATCH 1/4] 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/4] 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/4] 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/4] 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)