Skip to content

feat(google-api-core): add _RotatingGrpcChannel for swappable gRPC channels - #19181

Open
nbayati wants to merge 1 commit into
mainfrom
grpc_phase1_pr4a
Open

nbayati wants to merge 1 commit into
mainfrom
grpc_phase1_pr4a

Conversation

@nbayati

@nbayati nbayati commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Adds _RotatingGrpcChannel and its proxy multicallables to google.api_core.grpc_helpers. The wrapper resolves the active inner grpc.Channel on each RPC so the underlying channel can be swapped without replacing cached client stubs or interceptors.

When a duck-typed cert_manager is 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 with create_channel() and swap_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 UNAUTHENTICATED recovery and the _RotatingCall wrapper are split into a follow-up PR stacked on this one, and _RotatingGrpcChannel is not wired into grpc_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's SwappableChannel). The follow-up PR closes that gap.

@nbayati
nbayati added this pull request to stack #19182 November 23, 2026 00:06

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +1163 to +1169
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

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

Comment on lines +1211 to +1215
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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

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.

Suggested change
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)

Comment on lines +1293 to +1305
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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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)

@nbayati
nbayati force-pushed the grpc_phase1_pr4a branch 2 times, most recently from 00c2695 to 9db0463 Compare November 23, 2026 20:15
@nbayati
nbayati marked this pull request as ready for review November 23, 2026 20:53
@nbayati
nbayati requested a review from a team as a code owner November 23, 2026 20:53
Comment on lines +1335 to +1338
with self._lock:
self._closed = True
self._subscribers.clear()
self._channel.close()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_callback calling unsubscribe(), subscribe(), close(), swap_channel(), create_channel(), or a _registered_method=True RPC deadlocks against close().
  • 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) if close() runs while _rotate_on_unauthenticated() is inside cert_manager.refresh() before acquiring self._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)

Comment on lines +1332 to +1333
Calls still running on channels that were replaced by a swap are not
cancelled. They finish on their own.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Comment on lines +1223 to +1231
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()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment on lines +1347 to +1353
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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Comment on lines +1242 to +1245
gen = self._channel_generation_id
channel = self._channel
if self._current_generation() <= gen:
return channel, gen

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +1485 to +1506
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,
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +1670 to +1690
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit / test coverage: two load-bearing rotation paths in this PR don't have direct test coverage yet:

  1. Mid-rotation generation tagging (_build_channel): advancing cert_manager.generation_id inside channel_factory() and verifying the resulting channel is tagged with the pre-build generation and replaced on the next RPC.
  2. _registered_method=True stale-channel swap (grpc_helpers.py line 929): advancing cert_manager.generation_id and invoking a _registered_method=True stub to verify it swaps to the new channel before registering the call handle.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants