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..30fc1216ff4a 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,12 @@ 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. The downloader stays open; the + caller may retry the range or close it. Data from the failed call + may already have been written to its destinations, so reset or + replace ``write()`` destinations (e.g. ``seek(0)`` and + ``truncate()``) before retrying. """ @@ -901,7 +902,7 @@ async def _run_concurrently(awaitables) -> None: await asyncio.gather(*running, return_exceptions=True) raise - async def _download_batch( + def _release_batch( stream: _PooledStream, batch: List[ Tuple[int, int, Union[IO[bytes], bytearray, memoryview]] @@ -911,17 +912,36 @@ async def _download_batch( 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, - ) - finally: - pool.release_stream(stream, len(batch), batch_bytes) + pool.release_stream(stream, len(batch), batch_bytes) + + async def _download_batch( + stream: _PooledStream, + batch: List[ + Tuple[int, int, Union[IO[bytes], bytearray, memoryview]] + ], + ) -> None: + await self._download_ranges_on_stream( + stream, + batch, + retry_policy, + metadata, + enable_checksum, + accepts_memoryview=accepts_memoryview, + ) + + def _start_batch( + stream: _PooledStream, + batch: List[ + Tuple[int, int, Union[IO[bytes], bytearray, memoryview]] + ], + ) -> asyncio.Task: + # distribute_ranges() already recorded this batch's load on + # the stream. Release it from a done callback, which also + # runs if the task is cancelled before it starts (e.g. when + # a sibling batch raises DataCorruption). + task = asyncio.ensure_future(_download_batch(stream, batch)) + task.add_done_callback(lambda _: _release_batch(stream, batch)) + return task async def _download_overflow() -> None: remaining_overflow = list(overflow) @@ -946,9 +966,7 @@ async def _download_overflow() -> None: persisted_size=persisted_size, ) for s, b in extra_assignments.items(): - overflow_tasks.append( - asyncio.create_task(_download_batch(s, b)) - ) + overflow_tasks.append(_start_batch(s, b)) if remaining_overflow and not pool._closed: extra_assignments, _, _ = await pool.distribute_ranges( @@ -957,9 +975,7 @@ async def _download_overflow() -> None: persisted_size=persisted_size, ) for s, b in extra_assignments.items(): - overflow_tasks.append( - asyncio.create_task(_download_batch(s, b)) - ) + overflow_tasks.append(_start_batch(s, b)) await asyncio.gather(*overflow_tasks) except BaseException: @@ -971,15 +987,19 @@ async def _download_overflow() -> None: 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: + + if len(assignments) == 1 and not overflow: + # Fast path: await directly to avoid the Task wrapper + # overhead when all ranges fit onto a single stream. + ((stream, batch),) = assignments.items() + try: + await _download_batch(stream, batch) + finally: + _release_batch(stream, batch) + elif assignments or overflow: + tasks = [_start_batch(s, b) for s, b in assignments.items()] + if overflow: + tasks.append(_download_overflow()) await _run_concurrently(tasks) else: await self._download_ranges_on_stream( 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..2308a8a12690 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 @@ -392,7 +392,9 @@ async def test_download_ranges_rejects_chunk_past_bytes_to_read( await mock_mrd.download_ranges([(0, 10, buffer)]) assert bytes(buffer) == initial - assert not mock_mrd.is_stream_open + assert mock_mrd.is_stream_open + mock_mrd.read_obj_str.close.assert_not_awaited() + await mock_mrd.close() @mock.patch( "google.cloud.storage.asyncio.async_multi_range_downloader.generate_random_56_bit_integer" @@ -500,10 +502,12 @@ async def test_download_ranges_checksum_mismatch_into_buffer( with pytest.raises(DataCorruption) as exc_info: await mock_mrd.download_ranges([(0, 18, buffer)]) assert bytes(buffer) == bytes(18) - assert not mock_mrd.is_stream_open + assert mock_mrd.is_stream_open + mock_mrd.read_obj_str.close.assert_not_awaited() # exc_info.tb still references download_ranges' frame here. assert exc_info.tb is not None buffer.clear() + await mock_mrd.close() @mock.patch( "google.cloud.storage.asyncio.async_multi_range_downloader.generate_random_56_bit_integer" @@ -1424,7 +1428,7 @@ async def test_download_ranges_configures_full_object_read_state( "google.cloud.storage.asyncio.async_multi_range_downloader._AsyncReadObjectStream" ) @pytest.mark.asyncio - async def test_download_ranges_closes_on_datacorruption( + async def test_download_ranges_stays_open_on_datacorruption( self, mock_cls_async_read_object_stream, mock_retry_manager_cls, @@ -1448,7 +1452,8 @@ async def test_download_ranges_closes_on_datacorruption( with pytest.raises(DataCorruption): await mrd.download_ranges([(0, 0, BytesIO())]) - mrd.close.assert_called_once() + mrd.close.assert_not_called() + assert mrd.is_stream_open @mock.patch( "google.cloud.storage.asyncio.async_multi_range_downloader.generate_random_56_bit_integer" @@ -2397,7 +2402,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() @@ -2408,16 +2412,94 @@ async def side_effect_dl(pooled_stream, batch, *args, **kwargs): raise # Act & Assert - with mock.patch.object( - mrd, "_download_ranges_on_stream", side_effect=side_effect_dl - ): - ranges = [(i * 50, 50, BytesIO()) for i in range(3)] - with pytest.raises(DataCorruption, match="checksum mismatch"): - await mrd.download_ranges(ranges) + try: + with mock.patch.object( + mrd, "_download_ranges_on_stream", side_effect=side_effect_dl + ): + ranges = [(i * 50, 50, BytesIO()) for i in range(3)] + with pytest.raises(DataCorruption, match="checksum mismatch"): + await mrd.download_ranges(ranges) - assert overflow_batch_cancelled.is_set() - assert mrd.is_stream_open is False - assert mrd._pool is None + assert overflow_batch_cancelled.is_set() + assert mrd.is_stream_open + assert mrd._pool is not None + for ps in mrd._pool.streams: + assert ps.pending_ranges == 0 + assert ps.pending_bytes == 0 + finally: + await mrd.close() + + @mock.patch( + "google.cloud.storage.asyncio.async_multi_range_downloader._AsyncReadObjectStream" + ) + @pytest.mark.asyncio + async def test_download_ranges_releases_load_of_overflow_batch_cancelled_before_start( + self, mock_cls_stream + ): + from google.cloud.storage.asyncio.async_multi_range_downloader import ( + MultiStreamConfig, + ) + + loop = asyncio.get_running_loop() + s1 = self._make_mock_stream(read_handle=b"h1") + s2 = self._make_mock_stream(read_handle=b"h2") + s2_open_entered = asyncio.Event() + s2_open_gate = loop.create_future() + + async def s2_open(*args, **kwargs): + s2_open_entered.set() + await s2_open_gate + + s2.open = AsyncMock(side_effect=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 + ) + + s1_entered = asyncio.Event() + s1_fail_gate = loop.create_future() + downloaded_on = [] + + async def side_effect_dl(pooled_stream, batch, *args, **kwargs): + downloaded_on.append(pooled_stream.stream) + s1_entered.set() + await s1_fail_gate + raise DataCorruption(None, "checksum mismatch") + + distribute = mock.AsyncMock(wraps=mrd._pool.distribute_ranges) + try: + with ( + mock.patch.object( + mrd, "_download_ranges_on_stream", side_effect=side_effect_dl + ), + mock.patch.object(mrd._pool, "distribute_ranges", distribute), + ): + # r0 fills s1; r1 overflows and waits for s2 to finish opening. + task = asyncio.create_task( + mrd.download_ranges([(0, 50, BytesIO()), (50, 50, BytesIO())]) + ) + await s1_entered.wait() + await s2_open_entered.wait() + + # s1's batch fails right as s2 opens: the overflow batch is + # assigned to a stream, then cancelled before it starts. + loop.call_soon(s1_fail_gate.set_result, None) + s2_open_gate.set_result(None) + with pytest.raises(DataCorruption, match="checksum mismatch"): + await task + + assert distribute.await_count == 2 # the overflow batch was assigned + assert downloaded_on == [s1] # ...but never started + assert len(mrd._pool.streams) == 2 + for ps in mrd._pool.streams: + assert ps.pending_ranges == 0 + assert ps.pending_bytes == 0 + finally: + await mrd.close() @pytest.mark.asyncio async def test_stream_pool_contiguous_distribution_when_saturated(self): @@ -2631,3 +2713,68 @@ async def simulated_dl(pooled_stream, batch, *args, **kwargs): assert ps.pending_bytes == 0 await mrd.close() + + @mock.patch( + "google.cloud.storage.asyncio.async_multi_range_downloader.generate_random_56_bit_integer" + ) + @mock.patch( + "google.cloud.storage.asyncio.async_multi_range_downloader._AsyncReadObjectStream" + ) + @pytest.mark.asyncio + async def test_download_ranges_after_datacorruption_reuses_mrd( + self, mock_cls_stream, mock_random_int, monkeypatch + ): + _accept_memoryview_in_crc32c(monkeypatch) + corrupt_id, sibling_id, retry_id = 101, 201, 301 + mock_random_int.side_effect = [corrupt_id, sibling_id, retry_id] + + stream = self._make_mock_stream() + responses: asyncio.Queue = asyncio.Queue() + sent_read_ids = [] + + async def _send(req): + sent_read_ids.extend(rr.read_id for rr in req.read_ranges) + + stream.send = AsyncMock(side_effect=_send) + stream.recv = AsyncMock(side_effect=responses.get) + mock_cls_stream.side_effect = [stream] + + mrd = await AsyncMultiRangeDownloader.create_mrd( + self._make_mock_client(), _TEST_BUCKET_NAME, _TEST_OBJECT_NAME + ) + try: + corrupt_buf, sibling_buf = bytearray(8), bytearray(4) + corrupt = asyncio.create_task(mrd.download_ranges([(0, 8, corrupt_buf)])) + sibling = asyncio.create_task(mrd.download_ranges([(8, 4, sibling_buf)])) + while len(sent_read_ids) < 2: + await asyncio.sleep(0) + + # The first chunk of one read fails its checksum while a sibling + # read on the same stream is still in flight. + responses.put_nowait( + _zero_copy_response(b"abcd", 0, corrupt_id, False, crc32c=0) + ) + with pytest.raises(DataCorruption): + await corrupt + assert not sibling.done() + + # The failed read's remaining chunk still arrives and is dropped. + responses.put_nowait(_zero_copy_response(b"efgh", 4, corrupt_id, True)) + responses.put_nowait(_zero_copy_response(b"ijkl", 8, sibling_id, True)) + await sibling + assert bytes(sibling_buf) == b"ijkl" + assert bytes(corrupt_buf) == bytes(8) + + # The same stream serves a retry of the failed range. + retry_buf = bytearray(8) + retry = asyncio.create_task(mrd.download_ranges([(0, 8, retry_buf)])) + while len(sent_read_ids) < 3: + await asyncio.sleep(0) + responses.put_nowait(_zero_copy_response(b"abcdefgh", 0, retry_id, True)) + await retry + assert bytes(retry_buf) == b"abcdefgh" + assert sent_read_ids == [corrupt_id, sibling_id, retry_id] + assert mock_cls_stream.call_count == 1 + finally: + await mrd.close() + assert not mrd.is_stream_open diff --git a/packages/google-cloud-storage/tests/unit/asyncio/test_rapid_observability.py b/packages/google-cloud-storage/tests/unit/asyncio/test_rapid_observability.py index 0d0dfcd57a99..8e4fbae229c7 100644 --- a/packages/google-cloud-storage/tests/unit/asyncio/test_rapid_observability.py +++ b/packages/google-cloud-storage/tests/unit/asyncio/test_rapid_observability.py @@ -531,11 +531,14 @@ async def test_async_multi_range_downloader_data_corruption_marks_span_error( with pytest.raises(DataCorruption): await mrd.download_ranges([(0, 100, BytesIO())], enable_checksum=False) - assert not mrd.is_stream_open + assert mrd.is_stream_open + await mrd.close() + spans = exporter.get_finished_spans() assert [s.name for s in spans] == [ "Storage.AsyncMultiRangeDownloader.open", "Storage.AsyncMultiRangeDownloader.downloadRanges", + "Storage.AsyncMultiRangeDownloader.close", ] download_span = spans[1]