Skip to content

fix(storage): replay unflushed tail after reconnect in AsyncAppendableObjectWriter - #19102

Open
Yonghui-Lee wants to merge 6 commits into
googleapis:mainfrom
Yonghui-Lee:feat/storage-aaow-tail-replay
Open

Yonghui-Lee wants to merge 6 commits into
googleapis:mainfrom
Yonghui-Lee:feat/storage-aaow-tail-replay

Conversation

@Yonghui-Lee

@Yonghui-Lee Yonghui-Lee commented Nov 17, 2026 •

Copy link
Copy Markdown

Note

Stacked on #19092. The first two commits belong to #19092. Only the last commit (fix(storage): replay unflushed tail after reconnect in AsyncAppendableObjectWriter) is new here. I'll rebase once #19092 merges.

Fixes #19101

Problem

append() only requests persistence 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, for example during the next append(). The writer no longer held those bytes, so after #19092 such a reconnect raises DataLoss. Unaligned appends are the common case (gcsfs ZonalFile.write(), put_file with 50 MiB chunks and the 16 MiB default interval).

Changes

  • Unpersisted tail on the writer: a bytearray plus its starting offset. After each append(), the part of data the server hasn't confirmed is added, and bytes the server confirms are dropped (flush responses, flush(), state_lookup()). The tail normally stays below flush_interval and is capped at 2 * flush_interval.
  • Normal path unchanged: append() still reads from io.BytesIO(data). Only when a reconnect reports a persisted_size before the start of data does it swap in io.BytesIO(tail + data) and move _WriteState.initial_offset to the tail start. The existing reset_to_persisted() then rewinds into the tail.
  • close() and finalize() replay: after a reconnect, they resend the lost tail bytes with append(), then close, instead of raising DataLoss. Closing persists them.
  • DataLoss safety net: still raised when the server reports a persisted_size below the tail start.

Testing

Unit tests with the in-memory server (which drops unflushed bytes on reopen) cover the three real-GCS workloads from the #19092 review (2 x 5 MiB reset at 6 MiB, 10 x 1 MiB reset at 5 MiB, 100 x 64 KiB), caller buffer reuse, the tail cap, flush and state-lookup trimming, close/finalize replay, and the DataLoss path.

Real Zonal bucket (asia-southeast1-a). One abrupt stream break per case (the gRPC call is cancelled, not closed gracefully), then the object is read back and compared by size and SHA-256:

Workload (flush interval) main #19092 This PR
2 x 5 MiB, reset at 9 MiB (4 MiB) truncated, 9 of 10 MiB intact intact
2 x 5 MiB, reset at 6 MiB (4 MiB) truncated, 5 of 10 MiB DataLoss intact
10 x 1 MiB, reset at 5 MiB (4 MiB) truncated, 8 of 10 MiB DataLoss intact
200 x 64 KiB, reset at 6 MiB (4 MiB) truncated, 10.4 of 12.5 MiB DataLoss intact
2 x 50 MiB, reset at 52 MiB (16 MiB) truncated, 50 of 100 MiB DataLoss intact
7 MiB unflushed, reset during close() retried 30 s, then RetryError DataLoss intact
7 MiB unflushed, reset during finalize() retried 30 s, then RetryError DataLoss intact

Overhead without faults. Same bucket, two interleaved rounds:

  • 64 KiB appends: about 109 MiB/s with this PR vs 89 MiB/s with fix(storage): seek relative to initial_offset when retrying multi-call append #19092.
  • 50 MiB appends: about 209 vs 223 MiB/s.
  • The differences are within network noise. Copying appended bytes into the tail costs about 12 µs per 64 KiB append in a CPU-only microbenchmark, small next to the network time per append.
  • The tail holds at most flush_interval bytes. For 50 MiB appends with the 16 MiB default, that's the 2 MiB left after each append.

…l 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.
…match

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.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a mechanism to replay unpersisted tail bytes in AsyncAppendableObjectWriter upon stream reconnection, utilizing a new _ChainedReader class to read across multiple byte buffers without copying. The review feedback identifies a critical protocol desynchronization issue in _replay_tail_from where recv() should be called for both flush and state_lookup requests to prevent leaving unread responses on the stream. Additionally, a defensive programming improvement is suggested in _trim_tail to store self._tail_end() in a local variable to avoid potential bugs from future refactoring.

@Yonghui-Lee
Yonghui-Lee force-pushed the feat/storage-aaow-tail-replay branch from ee02b6c to f7ff5ac Compare November 17, 2026 06:34
…riter

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.
@Yonghui-Lee
Yonghui-Lee force-pushed the feat/storage-aaow-tail-replay branch 4 times, most recently from 4789b32 to 6097940 Compare November 17, 2026 08:02
@Yonghui-Lee
Yonghui-Lee marked this pull request as ready for review November 17, 2026 08:18
@Yonghui-Lee
Yonghui-Lee requested review from a team as code owners November 17, 2026 08:18

@zhixiangli zhixiangli left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tested on a real Zonal (RAPID) bucket with AsyncAppendableObjectWriter and gcsfs (ZonalFile.write/commit, put_file, and pipe_file with finalize_on_close=False and True) — all recover cleanly with matching SHA256, and the bytearray simplification is much cleaner than _ChainedReader.

Left a few inline comments below; please also sync the PR description with 609794089ac before squash-merging so the changelog doesn't mention _ChainedReader or REPLAY_UNPERSISTED_TAIL.

Address review feedback on PR googleapis#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.
…eObjectWriter

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 googleapis#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
…licy

Address review feedback on PR googleapis#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".
@Yonghui-Lee
Yonghui-Lee force-pushed the feat/storage-aaow-tail-replay branch from 6097940 to 508f3d1 Compare November 25, 2026 06:51
@Yonghui-Lee

Copy link
Copy Markdown
Author

@zhixiangli thanks for testing it on a real bucket. The PR description is now synced with the bytearray version (no _ChainedReader or REPLAY_UNPERSISTED_TAIL). This PR is rebased on the updated #19092. Both PRs will show conflicts until the storage commits rolled back in #19186 are restored on main. I'll rebase once they are.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

storage: replay unflushed tail after reconnect in AsyncAppendableObjectWriter

2 participants