Repository navigation
Conversation
There was a problem hiding this comment.
Code Review
This pull request introduces _RotatingGrpcChannel along with corresponding rotating multicallable proxies to support dynamic swapping of underlying gRPC channels, such as during mTLS client certificate rotation. It also adds comprehensive unit tests to verify channel swapping, subscriber migration, and concurrency behaviors. The review feedback identifies critical improvement opportunities regarding resource management and concurrency safety, specifically: a potential channel leak due to a race condition between create_channel() and close(), a resource leak where stale channels discarded during swap_channel() are not closed, and missing checks for the closed state when subscribing or unsubscribing.
| with self._lock: | ||
| if self._closed: | ||
| raise ValueError("Cannot create an inner channel after close().") | ||
| channel, generation = self._build_channel() | ||
| with self._lock: | ||
| self._created_generations[channel] = generation | ||
| return channel |
There was a problem hiding this comment.
There is a race condition if close() is called concurrently with create_channel(). Since _build_channel() is called outside of the lock, close() can run and set self._closed = True before the newly created channel is stored in self._created_generations. If this happens, the newly created channel will be leaked and never closed. Re-checking self._closed under the lock after building the channel, closing it, and raising ValueError prevents this leak.
with self._lock:
if self._closed:
raise ValueError("Cannot create an inner channel after close().")
channel, generation = self._build_channel()
with self._lock:
if self._closed:
channel.close()
raise ValueError("Cannot create an inner channel after close().")
self._created_generations[channel] = generation
return channel| else: | ||
| generation = self._created_generations.get(new_channel, current) | ||
| if generation < current: | ||
| new_channel, generation = self._build_channel() | ||
| return self._install_channel_locked(new_channel, generation) |
There was a problem hiding this comment.
When new_channel is passed to swap_channel but its generation is stale (generation < current), it is discarded and a new channel is built instead. However, the discarded new_channel is never closed, which causes a resource leak of the gRPC channel (holding file descriptors, TCP connections, etc.). Closing new_channel before building the replacement channel prevents this leak.
| else: | |
| generation = self._created_generations.get(new_channel, current) | |
| if generation < current: | |
| new_channel, generation = self._build_channel() | |
| return self._install_channel_locked(new_channel, generation) | |
| else: | |
| generation = self._created_generations.get(new_channel, current) | |
| if generation < current: | |
| new_channel.close() | |
| new_channel, generation = self._build_channel() | |
| return self._install_channel_locked(new_channel, generation) |
| def subscribe( | ||
| self, | ||
| callback: Callable[[grpc.ChannelConnectivity], None], | ||
| try_to_connect: bool = False, | ||
| ) -> None: | ||
| with self._lock: | ||
| self._subscribers[callback] = try_to_connect | ||
| self._channel.subscribe(callback, try_to_connect=try_to_connect) | ||
|
|
||
| def unsubscribe(self, callback: Callable[[grpc.ChannelConnectivity], None]) -> None: | ||
| with self._lock: | ||
| self._subscribers.pop(callback, None) | ||
| self._channel.unsubscribe(callback) |
There was a problem hiding this comment.
If subscribe or unsubscribe is called after the channel wrapper has been closed, it may attempt to interact with the closed underlying channel or lead to inconsistent state. Checking self._closed and raising ValueError on subscribe, and avoiding calling unsubscribe on the closed channel, ensures robust and safe behavior.
def subscribe(
self,
callback: Callable[[grpc.ChannelConnectivity], None],
try_to_connect: bool = False,
) -> None:
with self._lock:
if self._closed:
raise ValueError("Cannot subscribe after close().")
self._subscribers[callback] = try_to_connect
self._channel.subscribe(callback, try_to_connect=try_to_connect)
def unsubscribe(self, callback: Callable[[grpc.ChannelConnectivity], None]) -> None:
with self._lock:
self._subscribers.pop(callback, None)
if not self._closed:
self._channel.unsubscribe(callback)00c2695 to
9db0463
Compare
9db0463 to
9a8569b
Compare
| with self._lock: | ||
| self._closed = True | ||
| self._subscribers.clear() | ||
| self._channel.close() |
There was a problem hiding this comment.
self._channel.close() should be called outside self._lock (matching create_channel() and swap_channel()), with an early return when already closed.
In grpcio, Channel.close() cancels active calls and blocks until the channel's single channel_spin thread drains all pending completion-queue tags (integrated_call_states). Because grpcio runs add_done_callback and add_callback handlers synchronously on channel_spin, calling self._channel.close() while holding self._lock causes an AB-BA deadlock whenever a callback acquires self._lock while at least one other tag is still pending (e.g., 2+ active futures/streams, or a single unary_stream/stream_stream call whose ReceiveInitialMetadata and ReceiveStatusOnClient batches are both in flight):
- In this PR: any
add_done_callback/add_callbackcallingunsubscribe(),subscribe(),close(),swap_channel(),create_channel(), or a_registered_method=TrueRPC deadlocks againstclose(). - In feat(google-api-core): add reactive UNAUTHENTICATED recovery to _RotatingGrpcChannel #19180:
_RotatingCall's spin-thread callback hits this automatically (even with a no-op user callback) ifclose()runs while_rotate_on_unauthenticated()is insidecert_manager.refresh()before acquiringself._lock.
The if self._closed: return guard is also needed even after releasing self._lock: without it, a re-entrant rotating.close() from a spin-thread callback still deadlocks inside cygrpc._close() waiting for the first close() to complete. Releasing self._lock before channel.close() preserves the _registered_method=True closed-channel crash guard because _resolve_callable() completes factory(..., _registered_method=True) before releasing self._lock.
def close(self) -> None:
"""Close the active inner channel and stop building new ones.
Calls still running on channels that were replaced by a swap are not
cancelled. They finish on their own.
"""
with self._lock:
if self._closed:
return
self._closed = True
self._subscribers.clear()
channel = self._channel
channel.close()This can be covered deterministically in Test_RotatingGrpcChannel without a server using _make_real_channel():
def test_close_does_not_deadlock_with_spin_thread_callback(self):
rotating = grpc_helpers._RotatingGrpcChannel(_make_real_channel)
stub = rotating.unary_unary("/svc/UU")
fut1 = stub.future(b"req1", wait_for_ready=True)
fut2 = stub.future(b"req2", wait_for_ready=True)
done_count = 0
all_callbacks_finished = threading.Event()
def on_done(_future):
nonlocal done_count
rotating.unsubscribe(lambda _: None)
rotating.close()
done_count += 1
if done_count == 2:
all_callbacks_finished.set()
fut1.add_done_callback(on_done)
fut2.add_done_callback(on_done)
close_thread = threading.Thread(target=rotating.close, daemon=True)
close_thread.start()
close_thread.join(timeout=5)
assert not close_thread.is_alive()
assert all_callbacks_finished.wait(timeout=5)| Calls still running on channels that were replaced by a swap are not | ||
| cancelled. They finish on their own. |
There was a problem hiding this comment.
Architectural / follow-up question: relying on GC (_ChannelCallState.__del__) to close automatically retired channels works under default grpcio (GRPC_ENABLE_FORK_SUPPORT=0), but breaks when GRPC_ENABLE_FORK_SUPPORT=1 is enabled (common in Gunicorn/Celery/uWSGI/Airflow prefork workers, and upstream grpc/grpc recently considered enabling it by default in #41455).
When fork support is enabled, cygrpc.fork_register_channel(self) adds every grpc.Channel to _fork_state.channels (a strong set()), and only Channel.close() unregisters it (Channel.__del__ never does). Every automatic cert rotation therefore permanently leaks a grpc.Channel, its C-core channel, and its FDs for the lifetime of the process — even after rotating.close() is called, since close() only closes the active inner channel. (It also causes #19180's test_call_keeps_its_channel_alive_after_swap to fail if run with GRPC_ENABLE_FORK_SUPPORT=1.)
Not blocking this PR since #19181 doesn't wrap calls yet, but once #19180 wraps calls in _RotatingCall, tracking an in-flight call count per internally retired channel and calling old_channel.close() outside _lock once its count hits 0 (leaving swap_channel()'s returned channel owned by the caller) would close retired channels deterministically — mirroring the draining set planned for async _RotatingAsyncGrpcChannel. Should we address this in #19180 or track it as a Phase 1 follow-up?
| if generation < current: | ||
| stale_channel = new_channel | ||
| new_channel, generation = self._build_channel() | ||
| self._created_generations.pop(stale_channel, None) | ||
| else: | ||
| self._created_generations.pop(new_channel, None) | ||
| old_channel = self._install_channel_locked(new_channel, generation) | ||
| if stale_channel is not None: | ||
| stale_channel.close() |
There was a problem hiding this comment.
If new_channel came from create_channel() before a rotation (generation < current) and self._build_channel() raises on line 1225, both _created_generations.pop(stale_channel, None) and stale_channel.close() are skipped, leaking stale_channel even though it can never become current again.
Popping unconditionally and closing stale_channel in a finally: block closes the leak and simplifies the branches:
stale_channel: Optional[grpc.Channel] = None
try:
with self._lock:
if self._closed:
raise ValueError("Cannot swap the inner channel after close().")
current = self._current_generation()
if new_channel is None:
new_channel, generation = self._build_channel()
else:
generation = self._created_generations.pop(new_channel, current)
if generation < current:
stale_channel = new_channel
new_channel, generation = self._build_channel()
old_channel = self._install_channel_locked(new_channel, generation)
finally:
if stale_channel is not None:
stale_channel.close()
return old_channel| def __getattr__(self, name: str) -> Any: | ||
| # Only reached when normal lookup fails. If _channel itself is missing | ||
| # (copy.copy, unpickling, or a failed __init__), stop here instead of | ||
| # recursing. | ||
| if name == "_channel": | ||
| raise AttributeError(name) | ||
| return getattr(self._channel, name) |
There was a problem hiding this comment.
Nit: __getattr__ only guards name == "_channel", so explicit dunder probes via getattr() (such as copy.deepcopy() looking up __deepcopy__, or Python 3.10 pickle looking up __getstate__) forward to self._channel. Default copy.copy(rotating) also produces a second _RotatingGrpcChannel sharing _lock and _subscribers while diverging on _channel and _closed (closing the original leaves copied._closed == False pointing at the closed channel).
Guarding dunder names in __getattr__ — and optionally implementing __copy__/__deepcopy__ returning self and __reduce_ex__ raising TypeError (matching _MtlsCertManager) — keeps this safe:
def __copy__(self) -> "_RotatingGrpcChannel":
return self
def __deepcopy__(self, memo: Any) -> "_RotatingGrpcChannel":
return self
def __reduce_ex__(self, protocol: Any) -> Any:
raise TypeError(f"cannot pickle {type(self).__name__!r} object")
def __getattr__(self, name: str) -> Any:
if name == "_channel" or (name.startswith("__") and name.endswith("__")):
raise AttributeError(name)
return getattr(self._channel, name)| gen = self._channel_generation_id | ||
| channel = self._channel | ||
| if self._current_generation() <= gen: | ||
| return channel, gen |
There was a problem hiding this comment.
Nit (optional): packing (_channel, _channel_generation_id) into a single immutable 2-tuple self._active = (new_channel, generation) (matching _MtlsCertManager._snapshot) makes the lock-free read a single atomic reference load even under free-threaded Python (PEP 703) and removes the need to maintain opposite read/write ordering across two separate attributes.
| def test_wrap_errors_recognizes_rotating_multicallables(self): | ||
| ch1 = _make_mock_channel("ch1") | ||
| rotating = grpc_helpers._RotatingGrpcChannel(lambda: ch1) | ||
| intercepted = grpc.intercept_channel( | ||
| rotating, _UnaryUnaryPassthroughInterceptor() | ||
| ) | ||
|
|
||
| assert isinstance( | ||
| rotating.unary_unary("/svc/Unary"), grpc.UnaryUnaryMultiCallable | ||
| ) | ||
| assert isinstance( | ||
| intercepted.unary_stream("/svc/ServerStream"), | ||
| grpc.UnaryStreamMultiCallable, | ||
| ) | ||
| assert isinstance( | ||
| intercepted.stream_unary("/svc/ClientStream"), | ||
| grpc.StreamUnaryMultiCallable, | ||
| ) | ||
| assert isinstance( | ||
| intercepted.stream_stream("/svc/BidiStream"), | ||
| grpc.StreamStreamMultiCallable, | ||
| ) |
There was a problem hiding this comment.
Nit: this test checks isinstance(..., grpc.*MultiCallable) but never actually invokes grpc_helpers.wrap_errors(...). Calling wrap_errors() on each callable would also exercise _patch_callable_name() (__name__ assignment) and verify stream vs. unary wrapping end-to-end.
| def test_pre_rpc_generation_advance_swaps_before_call(self): | ||
| ch1 = _make_mock_channel("ch1") | ||
| ch2 = _make_mock_channel("ch2") | ||
| channels = iter([ch1, ch2]) | ||
| cert_manager = _FakeCertManager(generation_id=1) | ||
| rotating = grpc_helpers._RotatingGrpcChannel( | ||
| lambda: next(channels), cert_manager=cert_manager | ||
| ) | ||
|
|
||
| stub = rotating.unary_unary("/svc/UU") | ||
| ch2.unary_unary.return_value.with_call.return_value = ( | ||
| "ok_from_ch2", | ||
| mock.sentinel.call, | ||
| ) | ||
|
|
||
| # Simulate AuthMetadataPlugin advancing generation_id before next RPC | ||
| cert_manager.generation_id = 2 | ||
|
|
||
| assert stub("req") == "ok_from_ch2" | ||
| ch1.unary_unary.assert_not_called() | ||
| assert rotating.channel is ch2 |
There was a problem hiding this comment.
Nit / test coverage: two load-bearing rotation paths in this PR don't have direct test coverage yet:
- Mid-rotation generation tagging (
_build_channel): advancingcert_manager.generation_idinsidechannel_factory()and verifying the resulting channel is tagged with the pre-build generation and replaced on the next RPC. _registered_method=Truestale-channel swap (grpc_helpers.pyline 929): advancingcert_manager.generation_idand invoking a_registered_method=Truestub to verify it swaps to the new channel before registering the call handle.
Adds
_RotatingGrpcChanneland its proxy multicallables togoogle.api_core.grpc_helpers. The wrapper resolves the active innergrpc.Channelon each RPC so the underlying channel can be swapped without replacing cached client stubs or interceptors.When a duck-typed
cert_manageris passed, calls check its certificate generation before dispatching and swap to a fresh inner channel under a lock if the certificate rotated. Callers can also swap channels manually withcreate_channel()andswap_channel(), and connectivity subscribers are migrated to the new channel on swap.close()cancels calls only on the active inner channel; streams still running on channels replaced by a swap are not cancelled and finish on their own.This PR covers the swappable channel and pre-call rotation only. Reactive
UNAUTHENTICATEDrecovery and the_RotatingCallwrapper are split into a follow-up PR stacked on this one, and_RotatingGrpcChannelis not wired intogrpc_helpers.create_channel()yet. Without_RotatingCall, an in-flight call does not keep a reference to its retired inner channel, so under grpcio's single-threaded unary-stream option a swap can cancel an active stream on the replaced channel (the same behavior as Bigtable'sSwappableChannel). The follow-up PR closes that gap.