From b7e891d76ada124e68d91994bdcbdf45bbaf4be6 Mon Sep 17 00:00:00 2001 From: yuxin00j Date: Wed, 4 Nov 2026 10:27:35 +0000 Subject: [PATCH 1/3] test(storage): cover zero-copy BidiReadObject reads in the read microbenchmarks --- .../cloudbuild/display_benchmark_results.py | 48 +++- .../tests/perf/microbenchmarks/_utils.py | 25 ++ .../perf/microbenchmarks/reads/config.py | 21 +- .../perf/microbenchmarks/reads/config.yaml | 8 +- .../perf/microbenchmarks/reads/parameters.py | 2 + .../perf/microbenchmarks/reads/test_reads.py | 248 +++++++++--------- .../time_based/reads/config.py | 46 +++- .../time_based/reads/config.yaml | 8 +- .../time_based/reads/parameters.py | 2 + .../time_based/reads/test_reads.py | 88 ++++--- 10 files changed, 326 insertions(+), 170 deletions(-) diff --git a/packages/google-cloud-storage/cloudbuild/display_benchmark_results.py b/packages/google-cloud-storage/cloudbuild/display_benchmark_results.py index d22b3f44cbb9..b0f02c0c3923 100644 --- a/packages/google-cloud-storage/cloudbuild/display_benchmark_results.py +++ b/packages/google-cloud-storage/cloudbuild/display_benchmark_results.py @@ -41,12 +41,7 @@ def display_results(result_path: str) -> None: print("No benchmarks found in result file.") sys.exit(0) - print("\n" + "=" * 88) - print(" GCS DIRECTPATH READ BENCHMARK PERFORMANCE RESULTS") - print("=" * 88) - header = f"| {'Workload Pattern':<36} | {'Avg Throughput':<17} | {'Network Bandwidth':<22} | {'CPU Usage':<9} |" - print(header) - print("|" + "-" * 38 + "|" + "-" * 19 + "|" + "-" * 24 + "|" + "-" * 11 + "|") + rows = [] for b in benchmarks: if not isinstance(b, dict): continue @@ -70,10 +65,47 @@ def display_results(result_path: str) -> None: else: net_str = "N/A" cpu = extra.get("cpu_max_global", "N/A") + rows.append((name, f"{avg_mib} MiB/s", net_str, str(cpu))) + + if not rows: + print("No benchmarks found in result file.") + sys.exit(0) + + name_width = max([36] + [len(row[0]) for row in rows]) + avg_width = max([17] + [len(row[1]) for row in rows]) + net_width = max([22] + [len(row[2]) for row in rows]) + cpu_width = max([9] + [len(row[3]) for row in rows]) + table_width = name_width + avg_width + net_width + cpu_width + 13 + + print("\n" + "=" * table_width) + print("GCS DIRECTPATH READ BENCHMARK PERFORMANCE RESULTS".center(table_width)) + print("=" * table_width) + header = ( + f"| {'Workload Pattern':<{name_width}} " + f"| {'Avg Throughput':<{avg_width}} " + f"| {'Network Bandwidth':<{net_width}} " + f"| {'CPU Usage':<{cpu_width}} |" + ) + print(header) + print( + "|" + + "-" * (name_width + 2) + + "|" + + "-" * (avg_width + 2) + + "|" + + "-" * (net_width + 2) + + "|" + + "-" * (cpu_width + 2) + + "|" + ) + for name, avg_str, net_str, cpu_str in rows: print( - f"| {name:<36} | {str(avg_mib) + ' MiB/s':<17} | {net_str:<22} | {str(cpu):<9} |" + f"| {name:<{name_width}} " + f"| {avg_str:<{avg_width}} " + f"| {net_str:<{net_width}} " + f"| {cpu_str:<{cpu_width}} |" ) - print("=" * 88 + "\n") + print("=" * table_width + "\n") if __name__ == "__main__": diff --git a/packages/google-cloud-storage/tests/perf/microbenchmarks/_utils.py b/packages/google-cloud-storage/tests/perf/microbenchmarks/_utils.py index a6f02bad3580..045de2bc9181 100644 --- a/packages/google-cloud-storage/tests/perf/microbenchmarks/_utils.py +++ b/packages/google-cloud-storage/tests/perf/microbenchmarks/_utils.py @@ -11,6 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +import contextlib import io import os import socket @@ -19,7 +20,24 @@ import psutil +from google.cloud.storage.asyncio import _zero_copy_bidi_read + _C4_STANDARD_192_NIC = "ens3" # can be fetched via ip link show +_ZERO_COPY_ENV_VAR = "GCS_PYTHON_CLIENT_ZERO_COPY_BIDI_READ" + + +@contextlib.contextmanager +def zero_copy_env(enabled: bool): + """Sets GCS_PYTHON_CLIENT_ZERO_COPY_BIDI_READ for the duration of a block.""" + previous = os.environ.get(_ZERO_COPY_ENV_VAR) + os.environ[_ZERO_COPY_ENV_VAR] = "1" if enabled else "0" + try: + yield + finally: + if previous is None: + os.environ.pop(_ZERO_COPY_ENV_VAR, None) + else: + os.environ[_ZERO_COPY_ENV_VAR] = previous def publish_benchmark_extra_info( @@ -41,6 +59,13 @@ def publish_benchmark_extra_info( benchmark.extra_info["pattern"] = "seq" else: benchmark.extra_info["pattern"] = params.pattern + benchmark.extra_info["zero_copy"] = getattr(params, "zero_copy", False) + benchmark.extra_info["accepts_memoryview"] = getattr( + params, "accepts_memoryview", False + ) + benchmark.extra_info["crc32c_memoryview_supported"] = ( + _zero_copy_bidi_read.is_supported() + ) benchmark.extra_info["coros"] = params.num_coros benchmark.extra_info["rounds"] = params.rounds benchmark.extra_info["bucket_name"] = params.bucket_name diff --git a/packages/google-cloud-storage/tests/perf/microbenchmarks/reads/config.py b/packages/google-cloud-storage/tests/perf/microbenchmarks/reads/config.py index 7f4ddfc94970..06def5d89d1c 100644 --- a/packages/google-cloud-storage/tests/perf/microbenchmarks/reads/config.py +++ b/packages/google-cloud-storage/tests/perf/microbenchmarks/reads/config.py @@ -49,6 +49,8 @@ def _get_params() -> Dict[str, List[ReadParameters]]: common_params = config["common"] bucket_types = common_params["bucket_types"] + zero_copy_options = common_params.get("zero_copy", [False]) + accepts_memoryview_options = common_params.get("accepts_memoryview", [False]) file_sizes_mib = common_params["file_sizes_mib"] chunk_sizes_mib = common_params["chunk_sizes_mib"] rounds = common_params["rounds"] @@ -77,6 +79,8 @@ def _get_params() -> Dict[str, List[ReadParameters]]: chunk_sizes_mib, processes, coros, + zero_copy_options, + accepts_memoryview_options, ) for ( @@ -85,7 +89,14 @@ def _get_params() -> Dict[str, List[ReadParameters]]: chunk_size_mib, num_processes, num_coros, + zero_copy, + accepts_memoryview, ) in product: + if (zero_copy or accepts_memoryview) and bucket_type != "rapid": + continue + if accepts_memoryview and not zero_copy: + continue + file_size_bytes = file_size_mib * 1024 * 1024 chunk_size_bytes = chunk_size_mib * 1024 * 1024 bucket_name = bucket_map[bucket_type] @@ -93,7 +104,13 @@ def _get_params() -> Dict[str, List[ReadParameters]]: num_files = num_processes * num_coros # Create a descriptive name for the parameter set - name = f"{pattern}_{bucket_type}_{num_processes}p_{num_coros}c" + if zero_copy and accepts_memoryview: + suffix = "_zero_copy_memoryview" + elif zero_copy: + suffix = "_zero_copy" + else: + suffix = "" + name = f"{pattern}_{bucket_type}_{num_processes}p_{num_coros}c{suffix}" params[workload_name].append( ReadParameters( @@ -108,6 +125,8 @@ def _get_params() -> Dict[str, List[ReadParameters]]: rounds=rounds, chunk_size_bytes=chunk_size_bytes, file_size_bytes=file_size_bytes, + zero_copy=zero_copy, + accepts_memoryview=accepts_memoryview, ) ) return params diff --git a/packages/google-cloud-storage/tests/perf/microbenchmarks/reads/config.yaml b/packages/google-cloud-storage/tests/perf/microbenchmarks/reads/config.yaml index b6671e8a01c1..39659b11051b 100644 --- a/packages/google-cloud-storage/tests/perf/microbenchmarks/reads/config.yaml +++ b/packages/google-cloud-storage/tests/perf/microbenchmarks/reads/config.yaml @@ -2,6 +2,12 @@ common: bucket_types: - "regional" - "rapid" + zero_copy: + - false + - true + accepts_memoryview: + - false + - true file_sizes_mib: - 1024 # 1GiB chunk_sizes_mib: [100] @@ -46,4 +52,4 @@ workload: defaults: DEFAULT_RAPID_BUCKET: "chandrasiri-benchmarks-zb" - DEFAULT_STANDARD_BUCKET: "chandrasiri-benchmarks-rb" + DEFAULT_STANDARD_BUCKET: "chandrasiri-benchmarks-rb" diff --git a/packages/google-cloud-storage/tests/perf/microbenchmarks/reads/parameters.py b/packages/google-cloud-storage/tests/perf/microbenchmarks/reads/parameters.py index ae9d0bbc0321..a029989f2008 100644 --- a/packages/google-cloud-storage/tests/perf/microbenchmarks/reads/parameters.py +++ b/packages/google-cloud-storage/tests/perf/microbenchmarks/reads/parameters.py @@ -19,3 +19,5 @@ @dataclass class ReadParameters(IOBenchmarkParameters): pattern: str + zero_copy: bool = False + accepts_memoryview: bool = False diff --git a/packages/google-cloud-storage/tests/perf/microbenchmarks/reads/test_reads.py b/packages/google-cloud-storage/tests/perf/microbenchmarks/reads/test_reads.py index 2b4989b6fed0..bb38299c0266 100644 --- a/packages/google-cloud-storage/tests/perf/microbenchmarks/reads/test_reads.py +++ b/packages/google-cloud-storage/tests/perf/microbenchmarks/reads/test_reads.py @@ -25,6 +25,7 @@ import asyncio import logging import multiprocessing +import os import random import time from concurrent.futures import ThreadPoolExecutor @@ -37,7 +38,11 @@ from google.cloud.storage.asyncio.async_multi_range_downloader import ( AsyncMultiRangeDownloader, ) -from tests.perf.microbenchmarks._utils import publish_benchmark_extra_info +from tests.perf.microbenchmarks._utils import ( + _ZERO_COPY_ENV_VAR, + publish_benchmark_extra_info, + zero_copy_env, +) from tests.perf.microbenchmarks.conftest import ( publish_resource_metrics, ) @@ -57,11 +62,16 @@ async def download_chunks_using_mrd_async(client, filename, other_params, chunks total_bytes_downloaded = 0 mrd = AsyncMultiRangeDownloader(client, other_params.bucket_name, filename) await mrd.open() - for offset, size in chunks: - buffer = BytesIO() - await mrd.download_ranges([(offset, size, buffer)]) - total_bytes_downloaded += buffer.tell() - await mrd.close() + try: + for offset, size in chunks: + buffer = BytesIO() + await mrd.download_ranges( + [(offset, size, buffer)], + accepts_memoryview=other_params.accepts_memoryview, + ) + total_bytes_downloaded += buffer.tell() + finally: + await mrd.close() assert total_bytes_downloaded == other_params.file_size_bytes @@ -114,46 +124,47 @@ def test_downloads_single_proc_single_coro( logging.info("randomizing chunks") random.shuffle(chunks) - if params.bucket_type == "rapid": - logging.info("bucket type rapid") - target_func = download_chunks_using_mrd - loop = asyncio.new_event_loop() - asyncio.set_event_loop(loop) - client = loop.run_until_complete(create_client()) - else: - logging.info("bucket type regional") - target_func = download_chunks_using_json - loop = None - client = storage_client - - output_times = [] - - def target_wrapper(*args, **kwargs): - result = target_func(*args, **kwargs) - output_times.append(result) - return output_times - - try: - with monitor() as m: - output_times = benchmark.pedantic( - target=target_wrapper, - iterations=1, - rounds=params.rounds, - args=( - loop, - client, - files_names[0], - params, - chunks, - ), - ) - finally: - if loop is not None: - tasks = asyncio.all_tasks(loop=loop) - for task in tasks: - task.cancel() - loop.run_until_complete(asyncio.gather(*tasks, return_exceptions=True)) - loop.close() + with zero_copy_env(params.zero_copy): + if params.bucket_type == "rapid": + logging.info("bucket type rapid") + target_func = download_chunks_using_mrd + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + client = loop.run_until_complete(create_client()) + else: + logging.info("bucket type regional") + target_func = download_chunks_using_json + loop = None + client = storage_client + + output_times = [] + + def target_wrapper(*args, **kwargs): + result = target_func(*args, **kwargs) + output_times.append(result) + return output_times + + try: + with monitor() as m: + output_times = benchmark.pedantic( + target=target_wrapper, + iterations=1, + rounds=params.rounds, + args=( + loop, + client, + files_names[0], + params, + chunks, + ), + ) + finally: + if loop is not None: + tasks = asyncio.all_tasks(loop=loop) + for task in tasks: + task.cancel() + loop.run_until_complete(asyncio.gather(*tasks, return_exceptions=True)) + loop.close() publish_benchmark_extra_info(benchmark, params, true_times=output_times) publish_resource_metrics(benchmark, m) @@ -252,46 +263,47 @@ def test_downloads_single_proc_multi_coro( logging.info("randomizing chunks") random.shuffle(chunks) - if params.bucket_type == "rapid": - logging.info("bucket type rapid") - target_func = download_files_using_mrd_multi_coro - loop = asyncio.new_event_loop() - asyncio.set_event_loop(loop) - client = loop.run_until_complete(create_client()) - else: - logging.info("bucket type regional") - target_func = download_files_using_json_multi_threaded - loop = None - client = storage_client - - output_times = [] - - def target_wrapper(*args, **kwargs): - result = target_func(*args, **kwargs) - output_times.append(result) - return output_times - - try: - with monitor() as m: - output_times = benchmark.pedantic( - target=target_wrapper, - iterations=1, - rounds=params.rounds, - args=( - loop, - client, - files_names, - params, - chunks, - ), - ) - finally: - if loop is not None: - tasks = asyncio.all_tasks(loop=loop) - for task in tasks: - task.cancel() - loop.run_until_complete(asyncio.gather(*tasks, return_exceptions=True)) - loop.close() + with zero_copy_env(params.zero_copy): + if params.bucket_type == "rapid": + logging.info("bucket type rapid") + target_func = download_files_using_mrd_multi_coro + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + client = loop.run_until_complete(create_client()) + else: + logging.info("bucket type regional") + target_func = download_files_using_json_multi_threaded + loop = None + client = storage_client + + output_times = [] + + def target_wrapper(*args, **kwargs): + result = target_func(*args, **kwargs) + output_times.append(result) + return output_times + + try: + with monitor() as m: + output_times = benchmark.pedantic( + target=target_wrapper, + iterations=1, + rounds=params.rounds, + args=( + loop, + client, + files_names, + params, + chunks, + ), + ) + finally: + if loop is not None: + tasks = asyncio.all_tasks(loop=loop) + for task in tasks: + task.cancel() + loop.run_until_complete(asyncio.gather(*tasks, return_exceptions=True)) + loop.close() publish_benchmark_extra_info(benchmark, params, true_times=output_times) publish_resource_metrics(benchmark, m) @@ -306,10 +318,11 @@ def target_wrapper(*args, **kwargs): worker_json_client = None -def _worker_init(bucket_type): +def _worker_init(bucket_type, zero_copy=False): """Initializes a persistent event loop and client for each worker process.""" global worker_loop, worker_client, worker_json_client if bucket_type == "rapid": + os.environ[_ZERO_COPY_ENV_VAR] = "1" if zero_copy else "0" worker_loop = asyncio.new_event_loop() asyncio.set_event_loop(worker_loop) worker_client = worker_loop.run_until_complete(create_client()) @@ -386,36 +399,37 @@ def test_downloads_multi_proc_multi_coro( random.shuffle(chunks) ctx = multiprocessing.get_context("spawn") - pool = ctx.Pool( - processes=params.num_processes, - initializer=_worker_init, - initargs=(params.bucket_type,), - ) - output_times = [] - - def target_wrapper(*args, **kwargs): - result = download_files_mp_mc_wrapper(pool, *args, **kwargs) - output_times.append(result) - return output_times - - try: - with monitor() as m: - output_times = benchmark.pedantic( - target=target_wrapper, - iterations=1, - rounds=params.rounds, - args=( - files_names, - params, - chunks, - params.bucket_type, - ), - ) - finally: - pool.close() - pool.join() - publish_benchmark_extra_info(benchmark, params, true_times=output_times) - publish_resource_metrics(benchmark, m) + with zero_copy_env(params.zero_copy): + pool = ctx.Pool( + processes=params.num_processes, + initializer=_worker_init, + initargs=(params.bucket_type, params.zero_copy), + ) + output_times = [] + + def target_wrapper(*args, **kwargs): + result = download_files_mp_mc_wrapper(pool, *args, **kwargs) + output_times.append(result) + return output_times + + try: + with monitor() as m: + output_times = benchmark.pedantic( + target=target_wrapper, + iterations=1, + rounds=params.rounds, + args=( + files_names, + params, + chunks, + params.bucket_type, + ), + ) + finally: + pool.close() + pool.join() + publish_benchmark_extra_info(benchmark, params, true_times=output_times) + publish_resource_metrics(benchmark, m) blobs_to_delete.extend( storage_client.bucket(params.bucket_name).blob(f) for f in files_names diff --git a/packages/google-cloud-storage/tests/perf/microbenchmarks/time_based/reads/config.py b/packages/google-cloud-storage/tests/perf/microbenchmarks/time_based/reads/config.py index 1da66f38c08d..9302ab46caac 100644 --- a/packages/google-cloud-storage/tests/perf/microbenchmarks/time_based/reads/config.py +++ b/packages/google-cloud-storage/tests/perf/microbenchmarks/time_based/reads/config.py @@ -25,6 +25,15 @@ from reads.parameters import TimeBasedReadParameters +def _parse_bool(value: str, var_name: str = "ZERO_COPY") -> bool: + lowered = value.strip().lower() + if lowered in ("1", "true", "yes", "on"): + return True + if lowered in ("0", "false", "no", "off"): + return False + raise ValueError(f"Invalid boolean value for {var_name}: {value!r}") + + def _get_params() -> Dict[str, List[TimeBasedReadParameters]]: """Generates a dictionary of benchmark parameters for time based read operations.""" params: Dict[str, List[TimeBasedReadParameters]] = {} @@ -38,6 +47,24 @@ def _get_params() -> Dict[str, List[TimeBasedReadParameters]]: if "BUCKET_TYPE" in os.environ else common_params["bucket_types"] ) + zero_copy_options = ( + [ + _parse_bool(z, "ZERO_COPY") + for z in os.environ["ZERO_COPY"].split(",") + if z.strip() + ] + if os.environ.get("ZERO_COPY", "").strip() + else common_params.get("zero_copy", [False]) + ) + accepts_memoryview_options = ( + [ + _parse_bool(v, "ACCEPTS_MEMORYVIEW") + for v in os.environ["ACCEPTS_MEMORYVIEW"].split(",") + if v.strip() + ] + if os.environ.get("ACCEPTS_MEMORYVIEW", "").strip() + else common_params.get("accepts_memoryview", [False]) + ) file_sizes_mib = ( [int(s.strip()) for s in os.environ["FILE_SIZE_MIB"].split(",") if s.strip()] if "FILE_SIZE_MIB" in os.environ @@ -105,6 +132,8 @@ def _get_params() -> Dict[str, List[TimeBasedReadParameters]]: num_ranges, processes, coros, + zero_copy_options, + accepts_memoryview_options, ) for ( @@ -114,7 +143,14 @@ def _get_params() -> Dict[str, List[TimeBasedReadParameters]]: num_ranges_val, num_processes, num_coros, + zero_copy, + accepts_memoryview, ) in product: + if (zero_copy or accepts_memoryview) and bucket_type != "rapid": + continue + if accepts_memoryview and not zero_copy: + continue + file_size_bytes = file_size_mib * 1024 * 1024 chunk_size_bytes = chunk_size_kib * 1024 bucket_name = bucket_map[bucket_type] @@ -122,7 +158,13 @@ def _get_params() -> Dict[str, List[TimeBasedReadParameters]]: num_files = num_processes # Create a descriptive name for the parameter set - name = f"{pattern}_{bucket_type}_{num_processes}p_{num_coros}c_{file_size_mib}MiB_{chunk_size_kib}KiB_{num_ranges_val}ranges" + if zero_copy and accepts_memoryview: + suffix = "_zero_copy_memoryview" + elif zero_copy: + suffix = "_zero_copy" + else: + suffix = "" + name = f"{pattern}_{bucket_type}_{num_processes}p_{num_coros}c_{file_size_mib}MiB_{chunk_size_kib}KiB_{num_ranges_val}ranges{suffix}" params[workload_name].append( TimeBasedReadParameters( @@ -140,6 +182,8 @@ def _get_params() -> Dict[str, List[TimeBasedReadParameters]]: duration=duration, warmup_duration=warmup_duration, num_ranges=num_ranges_val, + zero_copy=zero_copy, + accepts_memoryview=accepts_memoryview, ) ) return params diff --git a/packages/google-cloud-storage/tests/perf/microbenchmarks/time_based/reads/config.yaml b/packages/google-cloud-storage/tests/perf/microbenchmarks/time_based/reads/config.yaml index e5867b8a2552..3deb04160831 100644 --- a/packages/google-cloud-storage/tests/perf/microbenchmarks/time_based/reads/config.yaml +++ b/packages/google-cloud-storage/tests/perf/microbenchmarks/time_based/reads/config.yaml @@ -2,6 +2,12 @@ common: bucket_types: - "regional" - "rapid" + zero_copy: + - false + - true + accepts_memoryview: + - false + - true file_sizes_mib: - 10240 # 10GiB chunk_sizes_kib: [64] # 16KiB @@ -26,4 +32,4 @@ workload: defaults: DEFAULT_RAPID_BUCKET: "chandrasiri-benchmarks-zb" - DEFAULT_STANDARD_BUCKET: "chandrasiri-benchmarks-rb" \ No newline at end of file + DEFAULT_STANDARD_BUCKET: "chandrasiri-benchmarks-rb" diff --git a/packages/google-cloud-storage/tests/perf/microbenchmarks/time_based/reads/parameters.py b/packages/google-cloud-storage/tests/perf/microbenchmarks/time_based/reads/parameters.py index ea26210c0657..488a7544fe4d 100644 --- a/packages/google-cloud-storage/tests/perf/microbenchmarks/time_based/reads/parameters.py +++ b/packages/google-cloud-storage/tests/perf/microbenchmarks/time_based/reads/parameters.py @@ -22,3 +22,5 @@ class TimeBasedReadParameters(IOBenchmarkParameters): duration: int warmup_duration: int num_ranges: int + zero_copy: bool = False + accepts_memoryview: bool = False diff --git a/packages/google-cloud-storage/tests/perf/microbenchmarks/time_based/reads/test_reads.py b/packages/google-cloud-storage/tests/perf/microbenchmarks/time_based/reads/test_reads.py index 4db477b69702..d80e0e140035 100644 --- a/packages/google-cloud-storage/tests/perf/microbenchmarks/time_based/reads/test_reads.py +++ b/packages/google-cloud-storage/tests/perf/microbenchmarks/time_based/reads/test_reads.py @@ -29,8 +29,10 @@ AsyncMultiRangeDownloader, ) from tests.perf.microbenchmarks._utils import ( + _ZERO_COPY_ENV_VAR, get_irq_affinity, publish_benchmark_extra_info, + zero_copy_env, ) from tests.perf.microbenchmarks.conftest import ( publish_resource_metrics, @@ -100,7 +102,7 @@ def _build_download_result( # TODO: b/479135274 close clients properly. -def _worker_init(bucket_type): +def _worker_init(bucket_type, zero_copy=False): """Initializes a persistent event loop and client for each worker process.""" cpu_affinity = get_irq_affinity() if cpu_affinity: @@ -110,6 +112,7 @@ def _worker_init(bucket_type): global worker_loop, worker_client, worker_json_client if bucket_type == "rapid": + os.environ[_ZERO_COPY_ENV_VAR] = "1" if zero_copy else "0" worker_loop = asyncio.new_event_loop() asyncio.set_event_loop(worker_loop) worker_client = worker_loop.run_until_complete(create_client()) @@ -224,7 +227,9 @@ async def _worker_coro(): if offset + params.chunk_size_bytes > params.file_size_bytes: offset = 0 # Reset offset if end of file is reached - await mrd.download_ranges(ranges) + await mrd.download_ranges( + ranges, accepts_memoryview=params.accepts_memoryview + ) bytes_in_buffers = sum(r[2].size for r in ranges) assert bytes_in_buffers == params.chunk_size_bytes * params.num_ranges @@ -273,45 +278,46 @@ def test_downloads_multi_proc_multi_coro( logging.info(f"num files: {len(files_names)}") ctx = multiprocessing.get_context("spawn") - pool = ctx.Pool( - processes=params.num_processes, - initializer=_worker_init, - initargs=(params.bucket_type,), - ) + with zero_copy_env(params.zero_copy): + pool = ctx.Pool( + processes=params.num_processes, + initializer=_worker_init, + initargs=(params.bucket_type, params.zero_copy), + ) - download_bytes_list = [] - download_elapsed_times = [] + download_bytes_list = [] + download_elapsed_times = [] - def target_wrapper(*args, **kwargs): - total_bytes, measured_elapsed_time = download_files_mp_mc_wrapper( - pool, *args, **kwargs - ) - download_bytes_list.append(total_bytes) - download_elapsed_times.append(measured_elapsed_time) - return - - try: - with monitor() as m: - benchmark.pedantic( - target=target_wrapper, - iterations=1, - rounds=params.rounds, - args=(files_names, params, params.bucket_type), + def target_wrapper(*args, **kwargs): + total_bytes, measured_elapsed_time = download_files_mp_mc_wrapper( + pool, *args, **kwargs ) - finally: - pool.close() - pool.join() - throughput_mib_s = _calculate_average_throughput_mib_s( - download_bytes_list, download_elapsed_times - ) - benchmark.extra_info["avg_throughput_mib_s"] = f"{throughput_mib_s:.2f}" - print( - f"Avg Throughput of {params.rounds} round(s): {throughput_mib_s:.2f} MiB/s" - ) - publish_benchmark_extra_info( - benchmark, - params, - download_bytes_list=download_bytes_list, - duration=download_elapsed_times, - ) - publish_resource_metrics(benchmark, m) + download_bytes_list.append(total_bytes) + download_elapsed_times.append(measured_elapsed_time) + return + + try: + with monitor() as m: + benchmark.pedantic( + target=target_wrapper, + iterations=1, + rounds=params.rounds, + args=(files_names, params, params.bucket_type), + ) + finally: + pool.close() + pool.join() + throughput_mib_s = _calculate_average_throughput_mib_s( + download_bytes_list, download_elapsed_times + ) + benchmark.extra_info["avg_throughput_mib_s"] = f"{throughput_mib_s:.2f}" + print( + f"Avg Throughput of {params.rounds} round(s): {throughput_mib_s:.2f} MiB/s" + ) + publish_benchmark_extra_info( + benchmark, + params, + download_bytes_list=download_bytes_list, + duration=download_elapsed_times, + ) + publish_resource_metrics(benchmark, m) From 0d5055f29c1bfef9b84281cfe18b894422e6d687 Mon Sep 17 00:00:00 2001 From: yuxin00j Date: Fri, 20 Nov 2026 03:47:16 +0000 Subject: [PATCH 2/3] test(storage): keep the read microbenchmarks from masking errors - Open the MRD with async with in the fixed-size reads, so a DataCorruption is not replaced by the error from closing a stream that is already closed. - Terminate the worker pool when a round fails and publish results only after a successful run, so the original error reaches the report. - Skip CPU pinning when the NIC IRQ CPUs cover every available CPU. - Fail collection when the time-based env overrides leave no case, and drop duplicate override values. - Mark rows that ran the bytes-slice fallback in the results table. - Upgrade google-crc32c and reinstall the package on every benchmark run, because the runner VM reuses its virtual environment. --- .../cloudbuild/display_benchmark_results.py | 14 +++++- .../cloudbuild/run_benchmark_tests.sh | 11 +++-- .../tests/perf/microbenchmarks/_utils.py | 2 +- .../perf/microbenchmarks/reads/test_reads.py | 18 ++++---- .../time_based/reads/config.py | 26 ++++++----- .../time_based/reads/test_reads.py | 43 +++++++++++-------- 6 files changed, 69 insertions(+), 45 deletions(-) diff --git a/packages/google-cloud-storage/cloudbuild/display_benchmark_results.py b/packages/google-cloud-storage/cloudbuild/display_benchmark_results.py index b0f02c0c3923..b078ea290869 100644 --- a/packages/google-cloud-storage/cloudbuild/display_benchmark_results.py +++ b/packages/google-cloud-storage/cloudbuild/display_benchmark_results.py @@ -65,6 +65,11 @@ def display_results(result_path: str) -> None: else: net_str = "N/A" cpu = extra.get("cpu_max_global", "N/A") + if ( + extra.get("accepts_memoryview") + and extra.get("crc32c_memoryview_supported") is False + ): + name = f"{name} (bytes fallback)" rows.append((name, f"{avg_mib} MiB/s", net_str, str(cpu))) if not rows: @@ -105,7 +110,14 @@ def display_results(result_path: str) -> None: f"| {net_str:<{net_width}} " f"| {cpu_str:<{cpu_width}} |" ) - print("=" * table_width + "\n") + print("=" * table_width) + if any(row[0].endswith(" (bytes fallback)") for row in rows): + print( + "NOTE: Installed google-crc32c does not support memoryview " + "(crc32c_memoryview_supported=False); *_zero_copy_memoryview rows " + "ran using the bytes-slice fallback." + ) + print() if __name__ == "__main__": diff --git a/packages/google-cloud-storage/cloudbuild/run_benchmark_tests.sh b/packages/google-cloud-storage/cloudbuild/run_benchmark_tests.sh index 7e1da89d5317..7b5ad5116188 100755 --- a/packages/google-cloud-storage/cloudbuild/run_benchmark_tests.sh +++ b/packages/google-cloud-storage/cloudbuild/run_benchmark_tests.sh @@ -78,12 +78,11 @@ if [ ! -d "${BENCH_VENV}" ]; then fi source "${BENCH_VENV}/bin/activate" -# Check and install all dependencies into virtual environment -if ! python3 -c "import pytest, psutil, yaml, google.cloud.storage" 2>/dev/null; then - echo "Installing dependencies into virtual environment..." - pip install --upgrade pip - pip install -e ".[grpc,testing]" -fi +# Install dependencies on every run: the standing VM reuses ${BENCH_VENV}, so +# new releases (e.g. google-crc32c) are only picked up through an upgrade. +echo "Installing dependencies into virtual environment..." +pip install --upgrade pip +pip install --upgrade -e ".[grpc,testing]" google-crc32c echo "--- 2. Executing pytest benchmark suite (${ROUNDS} rounds) ---" set +e diff --git a/packages/google-cloud-storage/tests/perf/microbenchmarks/_utils.py b/packages/google-cloud-storage/tests/perf/microbenchmarks/_utils.py index 045de2bc9181..f0f76f7161d0 100644 --- a/packages/google-cloud-storage/tests/perf/microbenchmarks/_utils.py +++ b/packages/google-cloud-storage/tests/perf/microbenchmarks/_utils.py @@ -23,7 +23,7 @@ from google.cloud.storage.asyncio import _zero_copy_bidi_read _C4_STANDARD_192_NIC = "ens3" # can be fetched via ip link show -_ZERO_COPY_ENV_VAR = "GCS_PYTHON_CLIENT_ZERO_COPY_BIDI_READ" +_ZERO_COPY_ENV_VAR = _zero_copy_bidi_read._ENV_VAR @contextlib.contextmanager diff --git a/packages/google-cloud-storage/tests/perf/microbenchmarks/reads/test_reads.py b/packages/google-cloud-storage/tests/perf/microbenchmarks/reads/test_reads.py index bb38299c0266..78c58bf358da 100644 --- a/packages/google-cloud-storage/tests/perf/microbenchmarks/reads/test_reads.py +++ b/packages/google-cloud-storage/tests/perf/microbenchmarks/reads/test_reads.py @@ -60,9 +60,9 @@ async def download_chunks_using_mrd_async(client, filename, other_params, chunks start_time = time.monotonic_ns() total_bytes_downloaded = 0 - mrd = AsyncMultiRangeDownloader(client, other_params.bucket_name, filename) - await mrd.open() - try: + async with AsyncMultiRangeDownloader( + client, other_params.bucket_name, filename + ) as mrd: for offset, size in chunks: buffer = BytesIO() await mrd.download_ranges( @@ -70,8 +70,6 @@ async def download_chunks_using_mrd_async(client, filename, other_params, chunks accepts_memoryview=other_params.accepts_memoryview, ) total_bytes_downloaded += buffer.tell() - finally: - await mrd.close() assert total_bytes_downloaded == other_params.file_size_bytes @@ -425,11 +423,15 @@ def target_wrapper(*args, **kwargs): params.bucket_type, ), ) - finally: + except BaseException: + pool.terminate() + raise + else: pool.close() + finally: pool.join() - publish_benchmark_extra_info(benchmark, params, true_times=output_times) - publish_resource_metrics(benchmark, m) + publish_benchmark_extra_info(benchmark, params, true_times=output_times) + publish_resource_metrics(benchmark, m) blobs_to_delete.extend( storage_client.bucket(params.bucket_name).blob(f) for f in files_names diff --git a/packages/google-cloud-storage/tests/perf/microbenchmarks/time_based/reads/config.py b/packages/google-cloud-storage/tests/perf/microbenchmarks/time_based/reads/config.py index 9302ab46caac..947455b3b6a0 100644 --- a/packages/google-cloud-storage/tests/perf/microbenchmarks/time_based/reads/config.py +++ b/packages/google-cloud-storage/tests/perf/microbenchmarks/time_based/reads/config.py @@ -48,20 +48,24 @@ def _get_params() -> Dict[str, List[TimeBasedReadParameters]]: else common_params["bucket_types"] ) zero_copy_options = ( - [ - _parse_bool(z, "ZERO_COPY") - for z in os.environ["ZERO_COPY"].split(",") - if z.strip() - ] + list( + dict.fromkeys( + _parse_bool(z, "ZERO_COPY") + for z in os.environ["ZERO_COPY"].split(",") + if z.strip() + ) + ) if os.environ.get("ZERO_COPY", "").strip() else common_params.get("zero_copy", [False]) ) accepts_memoryview_options = ( - [ - _parse_bool(v, "ACCEPTS_MEMORYVIEW") - for v in os.environ["ACCEPTS_MEMORYVIEW"].split(",") - if v.strip() - ] + list( + dict.fromkeys( + _parse_bool(v, "ACCEPTS_MEMORYVIEW") + for v in os.environ["ACCEPTS_MEMORYVIEW"].split(",") + if v.strip() + ) + ) if os.environ.get("ACCEPTS_MEMORYVIEW", "").strip() else common_params.get("accepts_memoryview", [False]) ) @@ -186,4 +190,6 @@ def _get_params() -> Dict[str, List[TimeBasedReadParameters]]: accepts_memoryview=accepts_memoryview, ) ) + if not any(params.values()): + raise ValueError("No time-based read benchmark cases match the env overrides.") return params diff --git a/packages/google-cloud-storage/tests/perf/microbenchmarks/time_based/reads/test_reads.py b/packages/google-cloud-storage/tests/perf/microbenchmarks/time_based/reads/test_reads.py index d80e0e140035..4cef8e71a1fb 100644 --- a/packages/google-cloud-storage/tests/perf/microbenchmarks/time_based/reads/test_reads.py +++ b/packages/google-cloud-storage/tests/perf/microbenchmarks/time_based/reads/test_reads.py @@ -105,10 +105,10 @@ def _build_download_result( def _worker_init(bucket_type, zero_copy=False): """Initializes a persistent event loop and client for each worker process.""" cpu_affinity = get_irq_affinity() - if cpu_affinity: - os.sched_setaffinity( - 0, {i for i in range(0, os.cpu_count()) if i not in cpu_affinity} - ) + if cpu_affinity and hasattr(os, "sched_getaffinity"): + available_cpus = os.sched_getaffinity(0) - cpu_affinity + if available_cpus: + os.sched_setaffinity(0, available_cpus) global worker_loop, worker_client, worker_json_client if bucket_type == "rapid": @@ -304,20 +304,25 @@ def target_wrapper(*args, **kwargs): rounds=params.rounds, args=(files_names, params, params.bucket_type), ) - finally: + except BaseException: + pool.terminate() + raise + else: pool.close() + finally: pool.join() - throughput_mib_s = _calculate_average_throughput_mib_s( - download_bytes_list, download_elapsed_times - ) - benchmark.extra_info["avg_throughput_mib_s"] = f"{throughput_mib_s:.2f}" - print( - f"Avg Throughput of {params.rounds} round(s): {throughput_mib_s:.2f} MiB/s" - ) - publish_benchmark_extra_info( - benchmark, - params, - download_bytes_list=download_bytes_list, - duration=download_elapsed_times, - ) - publish_resource_metrics(benchmark, m) + + throughput_mib_s = _calculate_average_throughput_mib_s( + download_bytes_list, download_elapsed_times + ) + benchmark.extra_info["avg_throughput_mib_s"] = f"{throughput_mib_s:.2f}" + print( + f"Avg Throughput of {params.rounds} round(s): {throughput_mib_s:.2f} MiB/s" + ) + publish_benchmark_extra_info( + benchmark, + params, + download_bytes_list=download_bytes_list, + duration=download_elapsed_times, + ) + publish_resource_metrics(benchmark, m) From 35947bb2d3267737293b8da3af9e3ff2ee0de389 Mon Sep 17 00:00:00 2001 From: yuxin00j Date: Mon, 23 Nov 2026 03:11:39 +0000 Subject: [PATCH 3/3] test(storage): report unpicklable worker errors in the read microbenchmarks A multiprocessing pool pickles a worker's exception to send it to the parent. A DataCorruption raised in a zero-copy case holds the zero-copy response, which cannot be pickled, so the parent only saw MaybeEncodingError with no message or traceback. The pool workers of both read suites now raise RuntimeError with the formatted traceback. --- .../perf/microbenchmarks/reads/test_reads.py | 29 ++++++++++++------- .../time_based/reads/test_reads.py | 19 ++++++++---- 2 files changed, 31 insertions(+), 17 deletions(-) diff --git a/packages/google-cloud-storage/tests/perf/microbenchmarks/reads/test_reads.py b/packages/google-cloud-storage/tests/perf/microbenchmarks/reads/test_reads.py index 78c58bf358da..e4e897c64aca 100644 --- a/packages/google-cloud-storage/tests/perf/microbenchmarks/reads/test_reads.py +++ b/packages/google-cloud-storage/tests/perf/microbenchmarks/reads/test_reads.py @@ -28,6 +28,7 @@ import os import random import time +import traceback from concurrent.futures import ThreadPoolExecutor from io import BytesIO @@ -331,17 +332,23 @@ def _worker_init(bucket_type, zero_copy=False): def _download_files_worker(files_to_download, other_params, chunks, bucket_type): - if bucket_type == "rapid": - # The loop and client are already initialized in _worker_init. - # download_files_using_mrd_multi_coro returns max latency of coros - return download_files_using_mrd_multi_coro( - worker_loop, worker_client, files_to_download, other_params, chunks - ) - else: # regional - # download_files_using_json_multi_threaded returns max latency of threads - return download_files_using_json_multi_threaded( - None, worker_json_client, files_to_download, other_params, chunks - ) + try: + if bucket_type == "rapid": + # The loop and client are already initialized in _worker_init. + # download_files_using_mrd_multi_coro returns max latency of coros + return download_files_using_mrd_multi_coro( + worker_loop, worker_client, files_to_download, other_params, chunks + ) + else: # regional + # download_files_using_json_multi_threaded returns max latency of threads + return download_files_using_json_multi_threaded( + None, worker_json_client, files_to_download, other_params, chunks + ) + except Exception: + # The pool pickles a worker's exception to send it to the parent. A + # DataCorruption holding a zero-copy response cannot be pickled, so + # send the formatted traceback instead. + raise RuntimeError(traceback.format_exc()) from None def download_files_mp_mc_wrapper(pool, files_names, params, chunks, bucket_type): diff --git a/packages/google-cloud-storage/tests/perf/microbenchmarks/time_based/reads/test_reads.py b/packages/google-cloud-storage/tests/perf/microbenchmarks/time_based/reads/test_reads.py index 4cef8e71a1fb..97095d478f1d 100644 --- a/packages/google-cloud-storage/tests/perf/microbenchmarks/time_based/reads/test_reads.py +++ b/packages/google-cloud-storage/tests/perf/microbenchmarks/time_based/reads/test_reads.py @@ -19,6 +19,7 @@ import os import random import time +import traceback from typing import List, NamedTuple, Optional import pytest @@ -249,12 +250,18 @@ async def _worker_coro(): def _download_files_worker(process_idx, filename, params, bucket_type): - if bucket_type == "rapid": - return worker_loop.run_until_complete( - _download_time_based_async(worker_client, filename, params) - ) - else: # regional - return _download_time_based_json(worker_json_client, filename, params) + try: + if bucket_type == "rapid": + return worker_loop.run_until_complete( + _download_time_based_async(worker_client, filename, params) + ) + else: # regional + return _download_time_based_json(worker_json_client, filename, params) + except Exception: + # The pool pickles a worker's exception to send it to the parent. A + # DataCorruption holding a zero-copy response cannot be pickled, so + # send the formatted traceback instead. + raise RuntimeError(traceback.format_exc()) from None def download_files_mp_mc_wrapper(pool, files_names, params, bucket_type):