Skip to content

feat(storage): opt-in zero-copy BidiReadObjectResponse parsing for async reads - #18627

Open
yuxin00j wants to merge 10 commits into
googleapis:mainfrom
yuxin00j:storage-zero-copy-read
Open

yuxin00j wants to merge 10 commits into
googleapis:mainfrom
yuxin00j:storage-zero-copy-read

Conversation

@yuxin00j

Copy link
Copy Markdown
Contributor

Summary

An opt-in parser for BidiReadObjectResponse that reads the message in place over the bytes object gRPC hands to the deserializer, so _AsyncReadObjectStream passes each chunk's checksummed_data.content to the read path as a memoryview of the received message instead of the two copies the generated parser makes on the event-loop thread (the upb parse, then .content into a new bytes; 257 us per 2 MiB message, 5 us with this parser). Off by default. Requires a google-crc32c release that accepts memoryview (#18626); with an older release the generated parser is used automatically.

Changes

  • asyncio/_zero_copy_bidi_read.py (new): deserialize(buf) walks the wire format of data responses (object_data_ranges, read_handle) over memoryview(buf) and returns stand-ins with the attributes the read path uses. A response carrying metadata, bytes that do not parse cleanly, or a buffer that is not an immutable bytes object is handed to BidiReadObjectResponse.deserialize, which returns the real message or raises its usual DecodeError. Varint, int64 and tag handling match upb.
  • Opt-in per downloader: AsyncMultiRangeDownloader.create_mrd(..., zero_copy=None). True asks for the parser, False keeps the generated one, None (default) defers to GOOGLE_CLOUD_STORAGE_ZERO_COPY_BIDI_READ (1/true/yes/on). Either way the parser is used only when the installed google-crc32c can hash a memoryview (is_supported() probe). The flag reaches every stream the downloader opens, including on resumption.
  • wrapped_rpc(transport, zero_copy, client_info): the transport's BidiReadObject stub with the deserializer swapped in, wrapped like the generated _wrapped_methods entry (same error mapping and x-goog-api-client header, built from the client's ClientInfo), cached per transport.
  • download_ranges contract: with zero_copy on, writeable_buffer.write() receives a read-only memoryview of the received message, which is immutable and stays alive as long as the view does; a buffer may keep the view and copy from it after write() returns, and a buffer that needs bytes must call bytes(data). io.BytesIO and binary files work unchanged.

Tests

tests/unit/asyncio/test_zero_copy_bidi_read.py: field-by-field comparison with the generated parser on encoder-built and proto-plus-serialized messages (including unknown fields of every wire type at each nesting level), 16 malformed inputs on which both parsers raise DecodeError, fallback cases (metadata, non-bytes buffers), is_enabled() precedence (argument over environment, both gated by the probe), wrapped_rpc caching, and an in-process grpc.aio server driving _AsyncReadObjectStream with the parser on and off and a custom ClientInfo (user agent and gapic version reach the server). test_async_multi_range_downloader.py / test_async_read_object_stream.py cover the argument plumbing. 100% line and branch coverage of the new module, on the upb and the pure-Python protobuf backends.

nox -s unit lint cover

Benchmark

c4-standard-192 (us-central1-c), Rapid bucket in the same zone, 16 concurrent streams per process, 4 x 16 MiB per download_ranges call into preallocated buffers, CRC32C verification on, google-crc32c from the companion PR; median of 3 interleaved runs, aggregate GB/s:

Processes main this PR
1 1.55 2.62
8 9.76 11.29

The generated BidiReadObject stub parses every response with proto-plus
over upb, which copies each data chunk twice on the event-loop thread
before it reaches the caller's buffer. Add a wire-format parser for plain
data responses that exposes `checksummed_data.content` as a memoryview of
the received message, and let `_AsyncReadObjectStream` use a stub built
with it (wrapped like the generated method: error mapping, no default
retry or timeout, same client-info header). Responses carrying object
metadata, or anything that does not parse cleanly, are handed to the
generated parser, so callers keep seeing the real message or its usual
DecodeError.

CRC32C verification in the read path is unchanged: the memoryview flows
through google_crc32c.value(), the user buffer write and the rolling
checksum. Because google-crc32c releases up to 1.9.0 only accept bytes
there, the fast path is used only when the installed google-crc32c can
checksum a memoryview; GOOGLE_CLOUD_STORAGE_FAST_BIDI_READ=0 forces the
generated parser as well.
…sages and invalid tags

The zero-copy BidiReadObjectResponse parser is meant to be indistinguishable
from the generated one apart from the type of ``content``; a comparison
against upb found a few places where it was not:

- ReadRange.read_offset/read_length/read_id are int64, so a ten-byte
  two's-complement varint must come back negative, and bits above 64 in
  an over-long varint are dropped rather than kept.
- A singular embedded message that occurs twice in its parent is merged;
  the sub-message parsers now fill in the existing object, which also
  removes two throw-away allocations per ObjectRangeData.
- Field number 0, tags above 32 bits and tags encoded in more than five
  bytes are malformed and now reach the generated parser's DecodeError.

Tests cover each case against the generated parser.
…stants

Explain the opt-in switch's accepted spellings, the four protobuf wire types, the 64-bit varint mask and the 32-bit tag limit.
Until now the only way to opt a downloader into the zero-copy
BidiReadObjectResponse parser was the GOOGLE_CLOUD_STORAGE_ZERO_COPY_BIDI_READ
environment variable, which _AsyncReadObjectStream re-reads on every open.
A library such as gcsfs that wants memoryview chunks therefore had to set a
process-wide variable, which also switches every other downloader in the
process (and in its children) to memoryview payloads on their next reopen.

create_mrd() and the constructor now take zero_copy: True asks for the parser,
False keeps the generated one, None (the default) defers to the environment
variable as before. The flag is passed to every stream the downloader opens,
including the ones created on resumption. _zero_copy_bidi_read.is_supported()
is now only the google-crc32c memoryview probe; the new is_enabled(zero_copy)
combines it with the argument or the environment, and wrapped_rpc() takes the
flag.

download_ranges() documents what a buffer receives: bytes, or with zero_copy
a read-only memoryview of the received message, which is immutable and stays
alive for as long as the view does, so a buffer may keep the view and copy
from it after write() returns.

Test plan: from packages/google-cloud-storage, with the upb and the pure-Python
protobuf backends:

    PYTHONPATH=$PWD python -m pytest tests/unit/asyncio/test_zero_copy_bidi_read.py \
        tests/unit/asyncio/test_async_read_object_stream.py \
        tests/unit/asyncio/test_async_multi_range_downloader.py
    PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=python PYTHONPATH=$PWD python -m pytest \
        tests/unit/asyncio/test_zero_copy_bidi_read.py

102 and 55 tests pass; new tests cover is_enabled() precedence (argument over
environment, both gated by is_supported()), wrapped_rpc() with an explicit
flag, and the flag reaching _AsyncReadObjectStream from create_mrd().

Authored with an AI assistant.
…he zero-copy parser

wrapped_rpc built its BidiReadObject callable with DEFAULT_CLIENT_INFO, while
the generated method uses the ClientInfo the transport was created with. A
caller passing its own ClientInfo therefore sent a different x-goog-api-client
header on BidiReadObject only. AsyncGrpcClient now remembers the ClientInfo it
configures, AsyncMultiRangeDownloader hands it to each stream, and wrapped_rpc
uses it (the transport default when none is given).

deserialize() aliases chunk payloads to the buffer gRPC hands it, which is only
safe for an immutable bytes object. Anything else now goes to the generated
parser instead of being aliased.

Test plan: from packages/google-cloud-storage, upb and pure-Python protobuf:

    PYTHONPATH=$PWD python -m pytest tests/unit/asyncio/test_zero_copy_bidi_read.py \
        tests/unit/asyncio/test_async_read_object_stream.py \
        tests/unit/asyncio/test_async_multi_range_downloader.py \
        tests/unit/asyncio/test_async_grpc_client.py
    PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=python PYTHONPATH=$PWD python -m pytest \
        tests/unit/asyncio/test_zero_copy_bidi_read.py

126 and 57 pass. The fake-server test now runs both parser paths with a custom
ClientInfo and asserts its user agent and gapic version reach the server; a
new test feeds bytearray and memoryview buffers to deserialize().

Authored with an AI assistant.

@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 zero-copy deserializer for BidiReadObjectResponse messages in _zero_copy_bidi_read.py to optimize performance by avoiding extra data copies on the event-loop thread. It integrates this parser into the async read path (async_multi_range_downloader.py and async_read_object_stream.py) with a configurable zero_copy option, and adds comprehensive unit tests. Feedback on the changes highlights a potential IndexError in the _varint decoding loop when parsing truncated inputs, suggesting a robust bounds check at the start of each iteration.

# parser does, instead of replacing what the earlier occurrence set.


def _parse_read_range(rr, buf, i, end):

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.

I see, we are parsing all the fields by own, should we re-use the standard parser for few fields like parsing read_range, BidiReadHandle one?

_ReadRangePb = _storage_v2.ReadRange.pb()
_BidiReadHandlePb = _storage_v2.BidiReadHandle.pb()
elif tag == _TAG_RANGE_READ_RANGE and read_range is None:
    start, i = _length_prefixed(buf, i, end)
    read_range = _ReadRangePb.FromString(buf[start:i])

# proto type.
handle = _storage_v2.BidiReadHandle(handle=handle)
return _ZeroCopyBidiReadObjectResponse(ranges, handle)
except Exception:

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.

Should we narrow it down to not go with the slow path for all exception like (Attribute Error, TypeError...)?
Maybe (_Malformed, IndexError, DecodeError) should be sufficient

# --- deserialize ---------------------------------------------------------------


def test_deserialize_data_response_round_trip():

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.

Should we merge all the test_deserialize_... as a single parameterized test? Like, this?

@pytest.mark.parametrize(
    "buf",
    [
        pytest.param(_serialize(_range(crc32c=google_crc32c.value(PAYLOAD))), id="data"),
        pytest.param(_serialize(_range()), id="no_crc32c"),
        pytest.param(_serialize(_range(), handle=b"opaque"), id="read_handle"),
        pytest.param(
            _serialize(
                _range(b"first", offset=0, read_id=1, range_end=False),
                _range(b"second", offset=5, read_id=2),
            ),
            id="multiple_ranges",
        ),
        pytest.param(b"", id="empty_message"),
        pytest.param(_response(_range_data(_checksummed())), id="no_read_range"),
        pytest.param(_response(_range_data(read_range=_read_range())), id="no_checksummed"),
        pytest.param(_data_response() + _UNKNOWN_FIELDS, id="unknown_top_level_fields"),
        pytest.param(
            _response(
                _range_data(
                    _checksummed(extra=_UNKNOWN_FIELDS),
                    _read_range(extra=_UNKNOWN_FIELDS),
                    extra=_UNKNOWN_FIELDS,
                ),
                handle=_len_field(_HANDLE_HANDLE, b"opaque") + _UNKNOWN_FIELDS,
            ),
            id="unknown_nested_fields",
        ),
        pytest.param(_serialize(_range(offset=-1, read_id=-1)), id="int64_minus_one"),
        pytest.param(
            _serialize(_range(offset=-(1 << 63), read_id=(1 << 63) - 1)),
            id="int64_extremes",
        ),
        pytest.param(
            # A ten-byte varint may carry 70 bits; the generated parser keeps 64.
            _response(_range_data(read_range=_tag(_READ_RANGE_ID, 0) + b"\xff" * 9 + b"\x7f")),
            id="over_long_varint",
        ),
        pytest.param(_SPLIT_SUB_MESSAGES, id="split_sub_messages_are_merged"),
    ],
)
def test_deserialize_matches_generated_parser(buf):
    expected = _storage_v2.BidiReadObjectResponse.deserialize(buf)
    # The zero-copy parser skips unknown fields; the generated one keeps them.
    expected._pb.DiscardUnknownFields()

    actual = _zero_copy_bidi_read.deserialize(buf)

    assert isinstance(actual, _zero_copy_bidi_read._ZeroCopyBidiReadObjectResponse)
    assert all(
        isinstance(r.checksummed_data.content, memoryview)
        for r in actual.object_data_ranges
    )
    assert _as_generated(actual) == expected

@raj-prince

Copy link
Copy Markdown
Contributor

/gcbrun

@yuxin00j
yuxin00j requested a review from a team as a code owner October 20, 2026 09:04
… write() destinations

download_ranges(accepts_memoryview=True) passes each chunk to a write()
destination as the read-only memoryview the zero-copy parser produced
instead of materializing bytes first. The default stays False, so existing
callers keep receiving bytes. Buffer destinations are unaffected.

Also accept a plain google.api_core.client_info.ClientInfo in wrapped_rpc:
AsyncGrpcClient takes one (gcsfs passes it), but gapic_v1's wrap_method
needs the gapic_v1 subclass for its x-goog-api-client header, so the
zero-copy stream failed to open with AttributeError. Such an object now
falls back to the transport default, which is the header main sends.
When a read ends on a chunk boundary the server's last message carries
range_end and a crc32c but no content field, so the zero-copy parser left
_ChecksummedData.content at its memoryview(b"") default even in the mode
that slices bytes for google-crc32c releases that cannot hash views. The
inline checksum then raised TypeError on stock google-crc32c 1.9.0, which
is what failed the zonal system tests (test_basic_wrd for 10 and 20 MiB
objects) since the parser became the default. Empty content is now b"" in
both modes, as the generated parser returns it.

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.

3 participants