Repository navigation
Description
Summary of the issue
Context:
Calling AsyncAppendableObjectWriter.append(data) multiple times on the same open writer (or calling append_from_file(), which calls append() in a loop) when a transient gRPC stream error (503 ServiceUnavailable, 500 InternalServerError, 504 DeadlineExceeded, 429 TooManyRequests, or BidiWriteObjectRedirectedError) triggers automatic stream recovery on the second or later append() call.
Expected Behavior:
Stream recovery rewinds only to the unpersisted position within the current append(data) call (persisted_size - initial_offset) and uploads all remaining bytes of data at their exact object offsets, or raises google.api_core.exceptions.DataLoss if reconnecting reveals that unpersisted bytes from an earlier append() call were lost on the server.
Actual Behavior:
AsyncAppendableObjectWriter.append(data) wraps only the current call's payload in io.BytesIO(data) (positions 0..len(data)), while persisted_size tracks the global persisted size of the entire object on GCS. On retry or redirect, both _WriteResumptionStrategy.recover_state_on_failure() and the stream reopen handler call write_state.user_buffer.seek(write_state.persisted_size) instead of seeking to persisted_size - initial_offset:
- When
persisted_size >= len(data),BytesIO.seek(persisted_size)seeks past EOF without raising an error,generate_requests()returns[], and the unpersisted tail ofdatais silently dropped whilewriter.offsetmoves backward topersisted_size. - When
0 < initial_offset <= persisted_size < len(data),BytesIO.seek(persisted_size)skipsinitial_offsetbytes insidedataand writes shifted bytes atpersisted_size. - When
persisted_size < initial_offsetafter reconnect (an earlierappend()sent< flush_intervalbytes without flushing and the server discarded them when the stream broke), recovery overwrites the lost range with bytes from the currentdatabuffer instead of raisingDataLoss.
API client name and version
google-cloud-storage v3.17.1
Reproduction steps: code
file: reproduce.py
import asyncio
from unittest import mock
from google.api_core import exceptions
from google.cloud import _storage_v2
from google.cloud.storage.asyncio.async_appendable_object_writer import (
_MAX_CHUNK_SIZE_BYTES,
AsyncAppendableObjectWriter,
)
class FakeAppendableServer:
def __init__(self, fail_once_after_bytes: int):
self.persisted_data = bytearray()
self.fail_once_after_bytes = fail_once_after_bytes
self.failed_once = False
def make_stream(self, **kwargs):
server = self
class FakeStream:
is_stream_open = False
generation_number = 1
write_handle = _storage_v2.BidiWriteHandle(handle=b"wh")
persisted_size = len(server.persisted_data)
async def open(self, metadata=None):
self.is_stream_open = True
self.persisted_size = len(server.persisted_data)
async def send(self, request):
if (
not server.failed_once
and len(server.persisted_data) >= server.fail_once_after_bytes
):
server.failed_once = True
raise exceptions.ServiceUnavailable("503 transient stream reset")
if request.checksummed_data and request.checksummed_data.content:
assert request.write_offset == len(server.persisted_data)
server.persisted_data.extend(request.checksummed_data.content)
async def recv(self):
return _storage_v2.BidiWriteObjectResponse(
persisted_size=len(server.persisted_data),
write_handle=_storage_v2.BidiWriteHandle(handle=b"wh"),
)
async def close(self):
self.is_stream_open = False
return FakeStream()
async def main():
first_chunk = b"A" * (2 * _MAX_CHUNK_SIZE_BYTES) # 4 MiB
second_chunk = (
b"B" * _MAX_CHUNK_SIZE_BYTES + b"C" * _MAX_CHUNK_SIZE_BYTES
) # 4 MiB
server = FakeAppendableServer(fail_once_after_bytes=3 * _MAX_CHUNK_SIZE_BYTES)
with mock.patch(
"google.cloud.storage.asyncio.async_appendable_object_writer._AsyncWriteObjectStream",
side_effect=server.make_stream,
):
writer = AsyncAppendableObjectWriter(
mock.Mock(),
"test-bucket",
"test-object",
writer_options={"FLUSH_INTERVAL_BYTES": _MAX_CHUNK_SIZE_BYTES},
)
await writer.open()
await writer.append(first_chunk)
print(
f"After first append: persisted={len(server.persisted_data)}, "
f"writer.offset={writer.offset}"
)
await writer.append(second_chunk)
print(
f"After second append: persisted={len(server.persisted_data)}, "
f"writer.offset={writer.offset}"
)
expected_bytes = first_chunk + second_chunk
print(
f"Expected {len(expected_bytes)} bytes, "
f"got {len(server.persisted_data)} bytes, "
f"match={bytes(server.persisted_data) == expected_bytes}"
)
asyncio.run(main())Reproduction steps: actual results
After first append: persisted=4194304, writer.offset=4194304
After second append: persisted=6291456, writer.offset=6291456
Expected 8388608 bytes, got 6291456 bytes, match=False
Reproduction steps: expected results
After first append: persisted=4194304, writer.offset=4194304
After second append: persisted=8388608, writer.offset=8388608
Expected 8388608 bytes, got 8388608 bytes, match=True
OS & version + platform
Linux x86_64
Python environment
Python 3.14.3
Python dependencies
google-api-core 2.43.0
google-auth 2.62.0
google-cloud-storage 3.17.1
google-crc32c 1.9.0
grpcio 1.84.0
protobuf 7.36.2
Additional context
We hit this while uploading multi-GiB PyTorch distributed checkpoint (.distcp ZIP) shards to Zonal buckets in 64 MiB append() chunks, where a transient 503 during stream upload silently dropped the unpersisted tail of a middle chunk and corrupted the archive's central directory. append_from_file() is affected in the same way because it calls await self.append(block) in a loop.
Activity