From 0a6ac7e2c84583cc0b0606236691ef80e0b10a12 Mon Sep 17 00:00:00 2001 From: yuxin00j Date: Fri, 20 Nov 2026 03:52:26 +0000 Subject: [PATCH 1/3] fix(storage): surface DataCorruption from multi-stream downloads With a MultiStreamConfig pool, a checksum mismatch on one stream closed the MRD from inside that stream's download. Closing the pool failed the other streams with Exception("Multiplexer closed"), and download_ranges often raised that error instead of DataCorruption. When the stream close took a while, as a real one does, the corrupt stream's task was cancelled during close(), which left the MRD reporting open with its pool closed and some streams never closed. download_ranges now closes the MRD on DataCorruption after every stream task has stopped, for both the pool and the single-stream path. The other streams are cancelled instead of failing on a closed pool. --- .../asyncio/async_multi_range_downloader.py | 196 +++++++++--------- .../test_async_multi_range_downloader.py | 59 +++++- 2 files changed, 159 insertions(+), 96 deletions(-) diff --git a/packages/google-cloud-storage/google/cloud/storage/asyncio/async_multi_range_downloader.py b/packages/google-cloud-storage/google/cloud/storage/asyncio/async_multi_range_downloader.py index 654759f4aa57..0d359245a418 100644 --- a/packages/google-cloud-storage/google/cloud/storage/asyncio/async_multi_range_downloader.py +++ b/packages/google-cloud-storage/google/cloud/storage/asyncio/async_multi_range_downloader.py @@ -742,10 +742,6 @@ async def generator(): await strategy.verify_pending_checksums(initial_state) raise await strategy.verify_pending_checksums(initial_state) - except DataCorruption: - if self.is_stream_open: - await self.close() - raise finally: # Drop chunks still held, e.g. after cancellation. strategy.discard_pending_checksums(initial_state) @@ -887,62 +883,74 @@ async def download_ranges( self.read_obj_str, self._multiplexer ) - if self._pool is not None: - pool = self._pool - persisted_size = self.persisted_size - - async def _run_concurrently(awaitables) -> None: - running = [asyncio.ensure_future(t) for t in awaitables] - try: - await asyncio.gather(*running) - except BaseException: - for t in running: - t.cancel() - await asyncio.gather(*running, return_exceptions=True) - raise - - async def _download_batch( - stream: _PooledStream, - batch: List[ - Tuple[int, int, Union[IO[bytes], bytearray, memoryview]] - ], - ) -> None: - batch_bytes = sum( - pool.effective_range_bytes(offset, length, persisted_size) - for offset, length, _ in batch - ) - try: - await self._download_ranges_on_stream( - stream, - batch, - retry_policy, - metadata, - enable_checksum, - accepts_memoryview=accepts_memoryview, + try: + if self._pool is not None: + pool = self._pool + persisted_size = self.persisted_size + + async def _run_concurrently(awaitables) -> None: + running = [asyncio.ensure_future(t) for t in awaitables] + try: + await asyncio.gather(*running) + except BaseException: + for t in running: + t.cancel() + await asyncio.gather(*running, return_exceptions=True) + raise + + async def _download_batch( + stream: _PooledStream, + batch: List[ + Tuple[int, int, Union[IO[bytes], bytearray, memoryview]] + ], + ) -> None: + batch_bytes = sum( + pool.effective_range_bytes(offset, length, persisted_size) + for offset, length, _ in batch ) - finally: - pool.release_stream(stream, len(batch), batch_bytes) - - async def _download_overflow() -> None: - remaining_overflow = list(overflow) - pending_scale_tasks = set(scale_tasks) - overflow_tasks: List[asyncio.Task] = [] - try: - while remaining_overflow and pending_scale_tasks: - _, pending_scale_tasks = await asyncio.wait( - pending_scale_tasks, - return_when=asyncio.FIRST_COMPLETED, + try: + await self._download_ranges_on_stream( + stream, + batch, + retry_policy, + metadata, + enable_checksum, + accepts_memoryview=accepts_memoryview, ) - if pool._closed: - break - if pending_scale_tasks: - ( - extra_assignments, - remaining_overflow, - _, - ) = await pool.distribute_ranges( + finally: + pool.release_stream(stream, len(batch), batch_bytes) + + async def _download_overflow() -> None: + remaining_overflow = list(overflow) + pending_scale_tasks = set(scale_tasks) + overflow_tasks: List[asyncio.Task] = [] + try: + while remaining_overflow and pending_scale_tasks: + _, pending_scale_tasks = await asyncio.wait( + pending_scale_tasks, + return_when=asyncio.FIRST_COMPLETED, + ) + if pool._closed: + break + if pending_scale_tasks: + ( + extra_assignments, + remaining_overflow, + _, + ) = await pool.distribute_ranges( + remaining_overflow, + allow_scale_up=True, + persisted_size=persisted_size, + ) + for s, b in extra_assignments.items(): + overflow_tasks.append( + asyncio.create_task(_download_batch(s, b)) + ) + + if remaining_overflow and not pool._closed: + extra_assignments, _, _ = await pool.distribute_ranges( remaining_overflow, - allow_scale_up=True, + allow_scale_up=False, persisted_size=persisted_size, ) for s, b in extra_assignments.items(): @@ -950,46 +958,44 @@ async def _download_overflow() -> None: asyncio.create_task(_download_batch(s, b)) ) - if remaining_overflow and not pool._closed: - extra_assignments, _, _ = await pool.distribute_ranges( - remaining_overflow, - allow_scale_up=False, - persisted_size=persisted_size, + await asyncio.gather(*overflow_tasks) + except BaseException: + for t in overflow_tasks: + t.cancel() + await asyncio.gather( + *overflow_tasks, return_exceptions=True ) - for s, b in extra_assignments.items(): - overflow_tasks.append( - asyncio.create_task(_download_batch(s, b)) - ) - - await asyncio.gather(*overflow_tasks) - except BaseException: - for t in overflow_tasks: - t.cancel() - await asyncio.gather(*overflow_tasks, return_exceptions=True) - raise + raise - assignments, overflow, scale_tasks = await pool.distribute_ranges( - read_ranges, persisted_size=persisted_size - ) - tasks = [_download_batch(s, b) for s, b in assignments.items()] - if overflow: - tasks.append(_download_overflow()) - - # Fast path: await directly to avoid asyncio.gather() Task wrapper overhead - # when all ranges fit onto a single stream without overflow. - if len(tasks) == 1: - await tasks[0] - elif tasks: - await _run_concurrently(tasks) - else: - await self._download_ranges_on_stream( - self._primary_stream, - read_ranges, - retry_policy, - metadata, - enable_checksum, - accepts_memoryview=accepts_memoryview, - ) + assignments, overflow, scale_tasks = await pool.distribute_ranges( + read_ranges, persisted_size=persisted_size + ) + tasks = [_download_batch(s, b) for s, b in assignments.items()] + if overflow: + tasks.append(_download_overflow()) + + # Fast path: await directly to avoid asyncio.gather() Task wrapper overhead + # when all ranges fit onto a single stream without overflow. + if len(tasks) == 1: + await tasks[0] + elif tasks: + await _run_concurrently(tasks) + else: + await self._download_ranges_on_stream( + self._primary_stream, + read_ranges, + retry_policy, + metadata, + enable_checksum, + accepts_memoryview=accepts_memoryview, + ) + except DataCorruption: + # Close only after every stream has stopped, so streams still + # reading are cancelled instead of failing on the closed pool + # and masking the DataCorruption. + if self.is_stream_open: + await self.close() + raise async def close(self): """ diff --git a/packages/google-cloud-storage/tests/unit/asyncio/test_async_multi_range_downloader.py b/packages/google-cloud-storage/tests/unit/asyncio/test_async_multi_range_downloader.py index 74befb8eda2e..df7851d9a209 100644 --- a/packages/google-cloud-storage/tests/unit/asyncio/test_async_multi_range_downloader.py +++ b/packages/google-cloud-storage/tests/unit/asyncio/test_async_multi_range_downloader.py @@ -2397,7 +2397,6 @@ async def slow_s3_open(*args, **kwargs): async def side_effect_dl(pooled_stream, batch, *args, **kwargs): if pooled_stream.stream is s1: await s2_overflow_started.wait() - await mrd.close() raise DataCorruption(None, "checksum mismatch") else: s2_overflow_started.set() @@ -2419,6 +2418,64 @@ async def side_effect_dl(pooled_stream, batch, *args, **kwargs): assert mrd.is_stream_open is False assert mrd._pool is None + @mock.patch( + "google.cloud.storage.asyncio.async_multi_range_downloader._AsyncReadObjectStream" + ) + @pytest.mark.asyncio + async def test_download_ranges_reports_data_corruption_on_one_of_many_streams( + self, mock_cls_stream + ): + from google.cloud.storage.asyncio.async_multi_range_downloader import ( + MultiStreamConfig, + ) + + def make_stream(corrupt): + s = self._make_mock_stream() + requests = asyncio.Queue() + + async def recv(): + request = await requests.get() + if not corrupt: + await asyncio.Event().wait() + read_range = request.read_ranges[0] + content = b"x" * read_range.read_length + return _storage_v2.BidiReadObjectResponse( + object_data_ranges=[ + _storage_v2.ObjectRangeData( + checksummed_data=_storage_v2.ChecksummedData( + content=content, + crc32c=google_crc32c.value(content) ^ 1, + ), + range_end=True, + read_range=read_range, + ) + ] + ) + + async def close(): + await asyncio.sleep(0) # A real close waits for the server. + + s.send = AsyncMock(side_effect=requests.put) + s.recv = AsyncMock(side_effect=recv) + s.close = AsyncMock(side_effect=close) + return s + + streams = [make_stream(corrupt=False), make_stream(corrupt=True)] + mock_cls_stream.side_effect = streams + config = MultiStreamConfig( + min_streams=2, max_streams=2, target_io_depth=1, target_bytes=10 + ) + mrd = await AsyncMultiRangeDownloader.create_mrd( + self._make_mock_client(), "b", "o", multi_stream_config=config + ) + + with pytest.raises(DataCorruption, match="Checksum mismatch"): + await mrd.download_ranges([(0, 10, BytesIO()), (10, 10, BytesIO())]) + + assert mrd.is_stream_open is False + for s in streams: + s.close.assert_awaited() + @pytest.mark.asyncio async def test_stream_pool_contiguous_distribution_when_saturated(self): from google.cloud.storage.asyncio._stream_pool import ( From f4d885674e638305995dfa366d4539073920805a Mon Sep 17 00:00:00 2001 From: yuxin00j Date: Mon, 23 Nov 2026 09:04:22 +0000 Subject: [PATCH 2/3] fix(storage): raise when the MRD closes while ranges wait for a stream download_ranges returned without downloading the ranges that were still waiting for a scale-up stream when the pool was closed in the meantime. It now lets distribute_ranges raise ValueError("Pool is closed"). Also flatten the nested try in _download_ranges_on_stream and document that the downloader is closed before DataCorruption is raised. --- .../asyncio/async_multi_range_downloader.py | 32 ++++++++------- .../test_async_multi_range_downloader.py | 39 +++++++++++++++++++ 2 files changed, 57 insertions(+), 14 deletions(-) diff --git a/packages/google-cloud-storage/google/cloud/storage/asyncio/async_multi_range_downloader.py b/packages/google-cloud-storage/google/cloud/storage/asyncio/async_multi_range_downloader.py index 0d359245a418..7f225f0b0f15 100644 --- a/packages/google-cloud-storage/google/cloud/storage/asyncio/async_multi_range_downloader.py +++ b/packages/google-cloud-storage/google/cloud/storage/asyncio/async_multi_range_downloader.py @@ -729,18 +729,18 @@ async def generator(): ) try: - try: - await retry_manager.execute(initial_state, retry_policy) - except DataCorruption: - raise - except Exception: - # Chunks received before the stream error still have - # in-flight checksum futures in initial_state. Verify them - # before raising the stream error so an earlier corrupt - # chunk raises DataCorruption (matching inline verification) - # and valid chunks already received are written. - await strategy.verify_pending_checksums(initial_state) - raise + await retry_manager.execute(initial_state, retry_policy) + except DataCorruption: + raise + except Exception: + # Chunks received before the stream error still have + # in-flight checksum futures in initial_state. Verify them + # before raising the stream error so an earlier corrupt + # chunk raises DataCorruption (matching inline verification) + # and valid chunks already received are written. + await strategy.verify_pending_checksums(initial_state) + raise + else: await strategy.verify_pending_checksums(initial_state) finally: # Drop chunks still held, e.g. after cancellation. @@ -851,7 +851,9 @@ async def download_ranges( ``bytes_to_read <= 0``. :raises BufferError: if fewer than ``bytes_to_read`` bytes are returned for a buffer destination. - :raises DataCorruption: if a checksum mismatch is detected while reading data. + :raises DataCorruption: if a checksum mismatch is detected while reading + data. The downloader is closed before this is raised, so calling + :meth:`close` afterwards raises :exc:`ValueError`. """ @@ -947,7 +949,9 @@ async def _download_overflow() -> None: asyncio.create_task(_download_batch(s, b)) ) - if remaining_overflow and not pool._closed: + if remaining_overflow: + # Raises if the pool was closed while these + # ranges were waiting for a stream. extra_assignments, _, _ = await pool.distribute_ranges( remaining_overflow, allow_scale_up=False, diff --git a/packages/google-cloud-storage/tests/unit/asyncio/test_async_multi_range_downloader.py b/packages/google-cloud-storage/tests/unit/asyncio/test_async_multi_range_downloader.py index df7851d9a209..97badb965b81 100644 --- a/packages/google-cloud-storage/tests/unit/asyncio/test_async_multi_range_downloader.py +++ b/packages/google-cloud-storage/tests/unit/asyncio/test_async_multi_range_downloader.py @@ -2476,6 +2476,45 @@ async def close(): for s in streams: s.close.assert_awaited() + @mock.patch( + "google.cloud.storage.asyncio.async_multi_range_downloader._AsyncReadObjectStream" + ) + @pytest.mark.asyncio + async def test_download_ranges_raises_when_closed_while_ranges_wait_for_a_stream( + self, mock_cls_stream + ): + from google.cloud.storage.asyncio.async_multi_range_downloader import ( + MultiStreamConfig, + ) + + s1 = self._make_mock_stream(read_handle=b"h1") + s2 = self._make_mock_stream(read_handle=b"h2") + s2_opening = asyncio.Event() + + async def slow_s2_open(*args, **kwargs): + s2_opening.set() + await asyncio.Event().wait() + + s2.open = AsyncMock(side_effect=slow_s2_open) + mock_cls_stream.side_effect = [s1, s2] + config = MultiStreamConfig( + min_streams=1, max_streams=2, target_io_depth=1, target_bytes=50 + ) + mrd = await AsyncMultiRangeDownloader.create_mrd( + self._make_mock_client(), "b", "o", multi_stream_config=config + ) + + with mock.patch.object(mrd, "_download_ranges_on_stream", AsyncMock()): + # The first range fills s1. The second waits for s2 to open. + task = asyncio.create_task( + mrd.download_ranges([(0, 50, BytesIO()), (50, 50, BytesIO())]) + ) + await s2_opening.wait() + await mrd.close() + + with pytest.raises(ValueError, match="Pool is closed"): + await task + @pytest.mark.asyncio async def test_stream_pool_contiguous_distribution_when_saturated(self): from google.cloud.storage.asyncio._stream_pool import ( From e2a677a1b2995e190dc0c0d3903196608e4377da Mon Sep 17 00:00:00 2001 From: yuxin00j Date: Fri, 27 Nov 2026 02:41:18 +0000 Subject: [PATCH 3/3] fix(storage): report a failed overflow batch without waiting for stream opens When ranges overflowed the open streams, download_ranges waited only on the pending stream opens, so a batch that failed on an already opened stream was not raised until every open had finished. The wait now also covers the batches that are already running. Also name offset and byte-count mismatches in the DataCorruption docs. --- .../asyncio/async_multi_range_downloader.py | 18 +++++-- .../test_async_multi_range_downloader.py | 48 +++++++++++++++++++ 2 files changed, 61 insertions(+), 5 deletions(-) diff --git a/packages/google-cloud-storage/google/cloud/storage/asyncio/async_multi_range_downloader.py b/packages/google-cloud-storage/google/cloud/storage/asyncio/async_multi_range_downloader.py index 7f225f0b0f15..7908ccb0ab53 100644 --- a/packages/google-cloud-storage/google/cloud/storage/asyncio/async_multi_range_downloader.py +++ b/packages/google-cloud-storage/google/cloud/storage/asyncio/async_multi_range_downloader.py @@ -851,9 +851,11 @@ async def download_ranges( ``bytes_to_read <= 0``. :raises BufferError: if fewer than ``bytes_to_read`` bytes are returned for a buffer destination. - :raises DataCorruption: if a checksum mismatch is detected while reading - data. The downloader is closed before this is raised, so calling - :meth:`close` afterwards raises :exc:`ValueError`. + :raises DataCorruption: if a checksum, offset, or byte-count mismatch is + detected while reading data (offset and byte-count are checked even + when ``enable_checksum=False``). The downloader is closed before + this is raised, so calling :meth:`close` afterwards raises + :exc:`ValueError`. """ @@ -928,10 +930,16 @@ async def _download_overflow() -> None: overflow_tasks: List[asyncio.Task] = [] try: while remaining_overflow and pending_scale_tasks: - _, pending_scale_tasks = await asyncio.wait( - pending_scale_tasks, + running = {t for t in overflow_tasks if not t.done()} + done, _ = await asyncio.wait( + pending_scale_tasks | running, return_when=asyncio.FIRST_COMPLETED, ) + for t in done & running: + t.result() # Raise a failed overflow batch now. + if not done & pending_scale_tasks: + continue + pending_scale_tasks -= done if pool._closed: break if pending_scale_tasks: diff --git a/packages/google-cloud-storage/tests/unit/asyncio/test_async_multi_range_downloader.py b/packages/google-cloud-storage/tests/unit/asyncio/test_async_multi_range_downloader.py index 97badb965b81..82e98023f649 100644 --- a/packages/google-cloud-storage/tests/unit/asyncio/test_async_multi_range_downloader.py +++ b/packages/google-cloud-storage/tests/unit/asyncio/test_async_multi_range_downloader.py @@ -2515,6 +2515,54 @@ async def slow_s2_open(*args, **kwargs): with pytest.raises(ValueError, match="Pool is closed"): await task + @mock.patch( + "google.cloud.storage.asyncio.async_multi_range_downloader._AsyncReadObjectStream" + ) + @pytest.mark.asyncio + async def test_download_ranges_raises_overflow_failure_while_a_stream_is_opening( + self, mock_cls_stream + ): + from google.cloud.storage.asyncio.async_multi_range_downloader import ( + MultiStreamConfig, + ) + + s1 = self._make_mock_stream(read_handle=b"h1") + s2 = self._make_mock_stream(read_handle=b"h2") + s3 = self._make_mock_stream(read_handle=b"h3") + s3_open_cancelled = asyncio.Event() + + async def s3_open(*args, **kwargs): + try: + await asyncio.Event().wait() + except asyncio.CancelledError: + s3_open_cancelled.set() + raise + + s3.open = AsyncMock(side_effect=s3_open) + mock_cls_stream.side_effect = [s1, s2, s3] + config = MultiStreamConfig( + min_streams=1, max_streams=3, target_io_depth=1, target_bytes=50 + ) + mrd = await AsyncMultiRangeDownloader.create_mrd( + self._make_mock_client(), "b", "o", multi_stream_config=config + ) + + async def side_effect_dl(pooled_stream, batch, *args, **kwargs): + if pooled_stream.stream is s2: + raise DataCorruption(None, "checksum mismatch") + await asyncio.Event().wait() + + with mock.patch.object( + mrd, "_download_ranges_on_stream", side_effect=side_effect_dl + ): + # The first range fills s1, the second fails on s2, and the third + # waits for s3, whose open() never returns. + ranges = [(i * 50, 50, BytesIO()) for i in range(3)] + with pytest.raises(DataCorruption, match="checksum mismatch"): + await asyncio.wait_for(mrd.download_ranges(ranges), timeout=5) + + assert s3_open_cancelled.is_set() + @pytest.mark.asyncio async def test_stream_pool_contiguous_distribution_when_saturated(self): from google.cloud.storage.asyncio._stream_pool import (