From 0defa0804e0ff0827981a11f5d124d75246ddbfc Mon Sep 17 00:00:00 2001 From: zhixiangli Date: Fri, 20 Nov 2026 14:14:25 +0000 Subject: [PATCH 1/5] fix(storage): send gRPC keepalive pings on AsyncGrpcClient channels --- .../storage/asyncio/async_grpc_client.py | 22 +++++++- .../unit/asyncio/test_async_grpc_client.py | 54 ++++++++++++++++--- 2 files changed, 68 insertions(+), 8 deletions(-) diff --git a/packages/google-cloud-storage/google/cloud/storage/asyncio/async_grpc_client.py b/packages/google-cloud-storage/google/cloud/storage/asyncio/async_grpc_client.py index 67d8136f1163..0281294f6e04 100644 --- a/packages/google-cloud-storage/google/cloud/storage/asyncio/async_grpc_client.py +++ b/packages/google-cloud-storage/google/cloud/storage/asyncio/async_grpc_client.py @@ -29,6 +29,22 @@ _validate_universe_domain, ) +# Detect a dead connection while an RPC or bidi stream is open. Without HTTP/2 +# keepalive, a pending recv() on a bidi stream can block indefinitely when the +# path to the server silently drops traffic or the peer stops responding while +# its kernel still ACKs TCP keepalives. Ping every 30 s while an RPC is open and +# drop the connection if a ping is not ACKed within 20 s, so the stream fails +# with a retryable error instead of hanging. grpc.http2.ping_timeout_ms is set +# alongside keepalive_timeout_ms because grpc-python otherwise waits its 60 s +# default for the ping ACK. keepalive_permit_without_calls is intentionally left +# unset so idle channels send no pings (more frequent or idle pings can trigger +# GOAWAY too_many_pings from GCS frontends). +_KEEPALIVE_CHANNEL_OPTIONS: tuple[tuple[str, int], ...] = ( + ("grpc.keepalive_time_ms", 30000), + ("grpc.keepalive_timeout_ms", 20000), + ("grpc.http2.ping_timeout_ms", 20000), +) + def _validate_metadata(metadata): """Validates that metadata is a sequence of (key, value) pairs.""" @@ -149,12 +165,16 @@ def _create_async_grpc_client( primary_user_agent = client_info.to_user_agent() + channel_options = ( + ("grpc.primary_user_agent", primary_user_agent), + ) + _KEEPALIVE_CHANNEL_OPTIONS + channel = transport_cls.create_channel( host=host, quota_project_id=quota_project_id, attempt_direct_path=attempt_direct_path, credentials=credentials, - options=(("grpc.primary_user_agent", primary_user_agent),), + options=channel_options, ) transport = transport_cls(host=host, channel=channel) diff --git a/packages/google-cloud-storage/tests/unit/asyncio/test_async_grpc_client.py b/packages/google-cloud-storage/tests/unit/asyncio/test_async_grpc_client.py index adec70654e57..e5fed9a84377 100644 --- a/packages/google-cloud-storage/tests/unit/asyncio/test_async_grpc_client.py +++ b/packages/google-cloud-storage/tests/unit/asyncio/test_async_grpc_client.py @@ -24,6 +24,13 @@ from google.cloud.storage.asyncio import async_grpc_client +_EXPECTED_KEEPALIVE_OPTIONS = ( + ("grpc.keepalive_time_ms", 30000), + ("grpc.keepalive_timeout_ms", 20000), + ("grpc.http2.ping_timeout_ms", 20000), +) + + @pytest.fixture(autouse=True) def _hermetic_env(monkeypatch): """Keeps the runner's environment from changing host or DirectPath resolution.""" @@ -56,7 +63,9 @@ def test_constructor_default_options(self, mock_async_storage_client): agent_version = f"gcloud-python/{__version__}" assert agent_version in client_info.user_agent primary_user_agent = client_info.to_user_agent() - expected_options = (("grpc.primary_user_agent", primary_user_agent),) + expected_options = ( + ("grpc.primary_user_agent", primary_user_agent), + ) + _EXPECTED_KEEPALIVE_OPTIONS mock_transport_cls.create_channel.assert_called_once_with( host="storage.googleapis.com", @@ -89,7 +98,9 @@ def test_constructor_with_client_info(self, mock_async_storage_client): agent_version = f"gcloud-python/{__version__}" assert agent_version in client_info.user_agent primary_user_agent = client_info.to_user_agent() - expected_options = (("grpc.primary_user_agent", primary_user_agent),) + expected_options = ( + ("grpc.primary_user_agent", primary_user_agent), + ) + _EXPECTED_KEEPALIVE_OPTIONS mock_transport_cls.create_channel.assert_called_once_with( host="storage.googleapis.com", @@ -120,7 +131,9 @@ def test_constructor_with_quota_project_and_endpoint( kwargs = mock_async_storage_client.call_args.kwargs client_info = kwargs["client_info"] primary_user_agent = client_info.to_user_agent() - expected_options = (("grpc.primary_user_agent", primary_user_agent),) + expected_options = ( + ("grpc.primary_user_agent", primary_user_agent), + ) + _EXPECTED_KEEPALIVE_OPTIONS mock_transport_cls.create_channel.assert_called_once_with( host="custom-endpoint.com", @@ -145,7 +158,9 @@ def test_constructor_disables_directpath(self, mock_async_storage_client): agent_version = f"gcloud-python/{__version__}" assert agent_version in client_info.user_agent primary_user_agent = client_info.to_user_agent() - expected_options = (("grpc.primary_user_agent", primary_user_agent),) + expected_options = ( + ("grpc.primary_user_agent", primary_user_agent), + ) + _EXPECTED_KEEPALIVE_OPTIONS mock_transport_cls.create_channel.assert_called_once_with( host="storage.googleapis.com", @@ -191,7 +206,9 @@ def test_grpc_client_property(self, mock_grpc_gapic_client): assert "test-user-agent" in client_info.user_agent primary_user_agent = client_info.to_user_agent() - expected_options = (("grpc.primary_user_agent", primary_user_agent),) + expected_options = ( + ("grpc.primary_user_agent", primary_user_agent), + ) + _EXPECTED_KEEPALIVE_OPTIONS mock_transport_cls.create_channel.assert_called_once_with( host="storage.googleapis.com", @@ -486,12 +503,15 @@ def test_universe_domain_routing_and_direct_path_disabled( primary_ua = mock_async_storage_client.call_args.kwargs[ "client_info" ].to_user_agent() + expected_options = ( + ("grpc.primary_user_agent", primary_ua), + ) + _EXPECTED_KEEPALIVE_OPTIONS mock_transport_cls.create_channel.assert_called_once_with( host=expected_host, quota_project_id=None, attempt_direct_path=False, credentials=mock_creds, - options=(("grpc.primary_user_agent", primary_ua),), + options=expected_options, ) mock_transport_cls.assert_called_once_with( host=expected_host, @@ -567,12 +587,15 @@ def test_unconfigured_mock_credentials_allowed( primary_ua = mock_async_storage_client.call_args.kwargs[ "client_info" ].to_user_agent() + expected_options = ( + ("grpc.primary_user_agent", primary_ua), + ) + _EXPECTED_KEEPALIVE_OPTIONS mock_transport_cls.create_channel.assert_called_once_with( host="storage.googleapis.com", quota_project_id=None, attempt_direct_path=True, credentials=mock_creds, - options=(("grpc.primary_user_agent", primary_ua),), + options=expected_options, ) @pytest.mark.parametrize( @@ -626,3 +649,20 @@ def test_real_gapic_client_integration_non_default_universe( assert client.grpc_client.api_endpoint == "storage.example.com:443" assert mock_create_channel.call_args.args[0] == "storage.example.com" assert mock_create_channel.call_args.kwargs["attempt_direct_path"] is False + + @mock.patch("google.cloud._storage_v2.StorageAsyncClient") + def test_channel_options_send_keepalive_pings( + self, + mock_async_storage_client, + ): + mock_transport_cls = mock.MagicMock() + mock_async_storage_client.get_transport_class.return_value = mock_transport_cls + mock_creds = _make_credentials() + + async_grpc_client.AsyncGrpcClient(credentials=mock_creds) + + options = dict(mock_transport_cls.create_channel.call_args.kwargs["options"]) + assert options["grpc.keepalive_time_ms"] == 30000 + assert options["grpc.keepalive_timeout_ms"] == 20000 + assert options["grpc.http2.ping_timeout_ms"] == 20000 + assert "grpc.keepalive_permit_without_calls" not in options From d449c02e032f0aa32c4fa6ea4f222799ce42173c Mon Sep 17 00:00:00 2001 From: zhixiangli Date: Fri, 20 Nov 2026 14:44:03 +0000 Subject: [PATCH 2/5] style(storage): fix import spacing in test_async_grpc_client --- .../tests/unit/asyncio/test_async_grpc_client.py | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/google-cloud-storage/tests/unit/asyncio/test_async_grpc_client.py b/packages/google-cloud-storage/tests/unit/asyncio/test_async_grpc_client.py index e5fed9a84377..0801d76ceb90 100644 --- a/packages/google-cloud-storage/tests/unit/asyncio/test_async_grpc_client.py +++ b/packages/google-cloud-storage/tests/unit/asyncio/test_async_grpc_client.py @@ -23,7 +23,6 @@ from google.cloud.storage import __version__ from google.cloud.storage.asyncio import async_grpc_client - _EXPECTED_KEEPALIVE_OPTIONS = ( ("grpc.keepalive_time_ms", 30000), ("grpc.keepalive_timeout_ms", 20000), From 51efa64e91460811a77cf4d7281b3fea1fe19767 Mon Sep 17 00:00:00 2001 From: zhixiangli Date: Mon, 23 Nov 2026 00:09:35 +0000 Subject: [PATCH 3/5] docs(storage): clarify keepalive ping behavior on idle streams On a stream with no outgoing data, gRPC limits keepalive pings to one per minute, so the comment no longer says pings are sent every 30 s. Also say that keepalive_permit_without_calls only suppresses pings on channels with no open RPC. --- .../cloud/storage/asyncio/async_grpc_client.py | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/packages/google-cloud-storage/google/cloud/storage/asyncio/async_grpc_client.py b/packages/google-cloud-storage/google/cloud/storage/asyncio/async_grpc_client.py index 0281294f6e04..404ac7da3ab6 100644 --- a/packages/google-cloud-storage/google/cloud/storage/asyncio/async_grpc_client.py +++ b/packages/google-cloud-storage/google/cloud/storage/asyncio/async_grpc_client.py @@ -32,13 +32,15 @@ # Detect a dead connection while an RPC or bidi stream is open. Without HTTP/2 # keepalive, a pending recv() on a bidi stream can block indefinitely when the # path to the server silently drops traffic or the peer stops responding while -# its kernel still ACKs TCP keepalives. Ping every 30 s while an RPC is open and -# drop the connection if a ping is not ACKed within 20 s, so the stream fails -# with a retryable error instead of hanging. grpc.http2.ping_timeout_ms is set -# alongside keepalive_timeout_ms because grpc-python otherwise waits its 60 s -# default for the ping ACK. keepalive_permit_without_calls is intentionally left -# unset so idle channels send no pings (more frequent or idle pings can trigger -# GOAWAY too_many_pings from GCS frontends). +# its kernel still ACKs TCP keepalives. While an RPC is open, send a ping after +# 30 s without activity and drop the connection if it is not ACKed within 20 s, +# so the stream fails with a retryable error instead of hanging. On a stream +# with no outgoing data, gRPC limits these pings to one per minute. +# grpc.http2.ping_timeout_ms is set alongside keepalive_timeout_ms because +# grpc-python otherwise waits its 60 s default for the ping ACK. +# keepalive_permit_without_calls is intentionally left unset so channels with no +# open RPC send no pings (more frequent or idle pings can trigger GOAWAY +# too_many_pings from GCS frontends). _KEEPALIVE_CHANNEL_OPTIONS: tuple[tuple[str, int], ...] = ( ("grpc.keepalive_time_ms", 30000), ("grpc.keepalive_timeout_ms", 20000), From 27fcdce4ecf7734b3d0cf9914d56b60e9621ca93 Mon Sep 17 00:00:00 2001 From: zhixiangli Date: Mon, 23 Nov 2026 00:09:36 +0000 Subject: [PATCH 4/5] test(storage): check keepalive with a real gRPC channel gRPC ignores unknown channel option keys, so the mocked create_channel test cannot catch a misspelled keepalive option. Add a test that runs a real channel through a local TCP relay, drops the traffic, and expects recv() to raise ServiceUnavailable. Also rename the mocked test and make it reject duplicate option keys. --- .../unit/asyncio/test_async_grpc_client.py | 120 +++++++++++++++++- 1 file changed, 117 insertions(+), 3 deletions(-) diff --git a/packages/google-cloud-storage/tests/unit/asyncio/test_async_grpc_client.py b/packages/google-cloud-storage/tests/unit/asyncio/test_async_grpc_client.py index 0801d76ceb90..a7478f9255de 100644 --- a/packages/google-cloud-storage/tests/unit/asyncio/test_async_grpc_client.py +++ b/packages/google-cloud-storage/tests/unit/asyncio/test_async_grpc_client.py @@ -12,16 +12,22 @@ # See the License for the specific language governing permissions and # limitations under the License. +import asyncio from unittest import mock +import grpc import pytest from google.api_core import client_info as client_info_lib -from google.api_core import client_options +from google.api_core import client_options, exceptions from google.auth import credentials as auth_credentials from google.auth.credentials import AnonymousCredentials +from google.cloud import _storage_v2 from google.cloud.storage import __version__ from google.cloud.storage.asyncio import async_grpc_client +from google.cloud.storage.asyncio.async_read_object_stream import ( + _AsyncReadObjectStream, +) _EXPECTED_KEEPALIVE_OPTIONS = ( ("grpc.keepalive_time_ms", 30000), @@ -650,7 +656,7 @@ def test_real_gapic_client_integration_non_default_universe( assert mock_create_channel.call_args.kwargs["attempt_direct_path"] is False @mock.patch("google.cloud._storage_v2.StorageAsyncClient") - def test_channel_options_send_keepalive_pings( + def test_channel_options_include_keepalive( self, mock_async_storage_client, ): @@ -660,8 +666,116 @@ def test_channel_options_send_keepalive_pings( async_grpc_client.AsyncGrpcClient(credentials=mock_creds) - options = dict(mock_transport_cls.create_channel.call_args.kwargs["options"]) + raw_options = mock_transport_cls.create_channel.call_args.kwargs["options"] + # gRPC uses the first occurrence of a duplicated key; dict() keeps the last. + assert len({key for key, _ in raw_options}) == len(raw_options) + options = dict(raw_options) assert options["grpc.keepalive_time_ms"] == 30000 assert options["grpc.keepalive_timeout_ms"] == 20000 assert options["grpc.http2.ping_timeout_ms"] == 20000 assert "grpc.keepalive_permit_without_calls" not in options + + @pytest.mark.asyncio + async def test_keepalive_fails_blackholed_bidi_stream(self): + """A real gRPC channel fails a silently dropped bidi stream instead of hanging. + + gRPC ignores unknown channel option keys, so this catches misspelled + keepalive options that a mocked ``create_channel`` cannot. + """ + + async def bidi_read(request_iterator, context): + await request_iterator.__anext__() + yield _storage_v2.BidiReadObjectResponse( + metadata=_storage_v2.Object( + bucket="projects/_/buckets/b", name="o", generation=1 + ) + ) + await asyncio.Event().wait() # Keep the stream open. + + server = grpc.aio.server() + server.add_generic_rpc_handlers( + [ + grpc.method_handlers_generic_handler( + "google.storage.v2.Storage", + { + "BidiReadObject": grpc.stream_stream_rpc_method_handler( + bidi_read, + request_deserializer=_storage_v2.BidiReadObjectRequest.deserialize, + response_serializer=_storage_v2.BidiReadObjectResponse.serialize, + ) + }, + ) + ] + ) + backend_port = server.add_insecure_port("127.0.0.1:0") + await server.start() + + # TCP relay that keeps both sockets open but drops all bytes once + # `blackhole` is set, like a path that silently stops forwarding. + blackhole = asyncio.Event() + writers = [] + + async def pipe(reader, writer): + try: + while data := await reader.read(65536): + if not blackhole.is_set(): + writer.write(data) + await writer.drain() + except OSError: + pass + + async def on_connect(client_reader, client_writer): + backend_reader, backend_writer = await asyncio.open_connection( + "127.0.0.1", backend_port + ) + writers.extend([client_writer, backend_writer]) + await asyncio.gather( + pipe(client_reader, backend_writer), + pipe(backend_reader, client_writer), + ) + + relay = await asyncio.start_server(on_connect, "127.0.0.1", 0) + relay_port = relay.sockets[0].getsockname()[1] + fast_keepalive = ( + ("grpc.keepalive_time_ms", 100), + ("grpc.keepalive_timeout_ms", 100), + ("grpc.http2.ping_timeout_ms", 100), + ) + + def insecure_channel(target, credentials=None, **kwargs): + return grpc.aio.insecure_channel(target, options=kwargs.get("options")) + + try: + with ( + mock.patch.object( + async_grpc_client, "_KEEPALIVE_CHANNEL_OPTIONS", fast_keepalive + ), + mock.patch( + "google.api_core.grpc_helpers_async.create_channel", + side_effect=insecure_channel, + ), + ): + client = async_grpc_client.AsyncGrpcClient( + credentials=_make_credentials(), + client_options=client_options.ClientOptions( + api_endpoint=f"127.0.0.1:{relay_port}" + ), + attempt_direct_path=False, + ) + try: + stream = _AsyncReadObjectStream( + client=client.grpc_client, bucket_name="b", object_name="o" + ) + await stream.open() + blackhole.set() + # Usually fails in ~0.1 s. If a ping was ACKed just before the + # blackhole, gRPC waits 1 s before the next ping, so allow ~5x. + with pytest.raises(exceptions.ServiceUnavailable): + await asyncio.wait_for(stream.recv(), timeout=5) + finally: + await client.grpc_client.transport.close() + finally: + relay.close() + for writer in writers: + writer.close() + await server.stop(0) From 107160df44a6fbbf0c0cb14878bb1ea312e3b4e6 Mon Sep 17 00:00:00 2001 From: zhixiangli Date: Mon, 30 Nov 2026 11:33:57 +0000 Subject: [PATCH 5/5] test(storage): derive keepalive keys and await relay cleanup Take the fast keepalive option keys from _KEEPALIVE_CHANNEL_OPTIONS so the real-channel test catches a typo in the production keys, and wait for the relay and its sockets to close before stopping the server. --- .../tests/unit/asyncio/test_async_grpc_client.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/packages/google-cloud-storage/tests/unit/asyncio/test_async_grpc_client.py b/packages/google-cloud-storage/tests/unit/asyncio/test_async_grpc_client.py index a7478f9255de..9ab45e635c39 100644 --- a/packages/google-cloud-storage/tests/unit/asyncio/test_async_grpc_client.py +++ b/packages/google-cloud-storage/tests/unit/asyncio/test_async_grpc_client.py @@ -736,10 +736,9 @@ async def on_connect(client_reader, client_writer): relay = await asyncio.start_server(on_connect, "127.0.0.1", 0) relay_port = relay.sockets[0].getsockname()[1] - fast_keepalive = ( - ("grpc.keepalive_time_ms", 100), - ("grpc.keepalive_timeout_ms", 100), - ("grpc.http2.ping_timeout_ms", 100), + # Reuse the production keys so a typo there is caught; only shrink values. + fast_keepalive = tuple( + (key, 100) for key, _ in async_grpc_client._KEEPALIVE_CHANNEL_OPTIONS ) def insecure_channel(target, credentials=None, **kwargs): @@ -778,4 +777,9 @@ def insecure_channel(target, credentials=None, **kwargs): relay.close() for writer in writers: writer.close() + await asyncio.gather( + relay.wait_closed(), + *(writer.wait_closed() for writer in writers), + return_exceptions=True, + ) await server.stop(0)