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..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 @@ -729,23 +729,19 @@ 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 strategy.verify_pending_checksums(initial_state) + await retry_manager.execute(initial_state, retry_policy) except DataCorruption: - if self.is_stream_open: - await self.close() 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. strategy.discard_pending_checksums(initial_state) @@ -855,7 +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. + :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`. """ @@ -887,62 +887,82 @@ 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: + 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: + ( + 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: + # 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=True, + allow_scale_up=False, persisted_size=persisted_size, ) for s, b in extra_assignments.items(): @@ -950,46 +970,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..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 @@ -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,151 @@ 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() + + @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 + + @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 (