Skip to content

feat(google-api-core): add reactive UNAUTHENTICATED recovery to _RotatingGrpcChannel - #19180

Open
nbayati wants to merge 1 commit into
grpc_phase1_pr4afrom
grpc_phase1_pr4b
Open

nbayati wants to merge 1 commit into
grpc_phase1_pr4afrom
grpc_phase1_pr4b

Conversation

@nbayati

@nbayati nbayati commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Adds reactive UNAUTHENTICATED recovery and the _RotatingCall wrapper to _RotatingGrpcChannel, stacked on PR 4a.

When an RPC fails with UNAUTHENTICATED, the channel checks whether the client certificate rotated (refreshing through cert_manager if needed). If the certificate did not change, or if refreshing or rebuilding the channel fails, the original grpc.RpcError is re-raised unchanged. When the certificate did rotate, the wrapper swaps to a fresh inner channel once under a lock:

  • Synchronous unary-unary calls retry once on the new channel with the remaining per-call timeout, or re-raise without retrying if the timeout is already used up.
  • Unary-unary futures and all streaming calls (unary-stream, stream-unary, and stream-stream) swap the channel for subsequent calls and re-raise without retrying, avoiding replaying consumed request streams or managing multi-attempt callback state (reopening unary-stream calls before the first response is deferred to a follow-up).

_RotatingCall holds a reference to its inner channel for the lifetime of the call so retired channels stay alive until active streams finish (closing PR 4a's single-threaded unary-stream gap), and passes grpcio's raw future to done callbacks so streaming recovery helpers continue seeing a grpc.RpcError. Nothing is retried or swapped on UNAVAILABLE, and _RotatingGrpcChannel is not wired into create_channel() yet.

@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 _RotatingCall, a proxy class for gRPC Call and Future objects, to handle certificate rotation reactively. It enables automatic retries with timeout deduction for unary-unary and unary-stream calls when an UNAUTHENTICATED error is encountered, supported by comprehensive unit tests. The review feedback correctly identifies a critical issue where callbacks registered on the original call are not transferred to the new call during a stream reopen, leading to premature failure notifications. Implementing the suggested tracking and re-registration of callbacks is highly recommended to ensure correct behavior.

Comment on lines +898 to +914
def __init__(
self,
rotating_channel: "_RotatingGrpcChannel",
channel: grpc.Channel,
call: Any,
attempt_gen: int,
reopen_fn: Optional[Callable[[], Tuple[grpc.Channel, Any, int]]] = None,
) -> None:
self._rotating_channel = rotating_channel
# Keep the inner channel alive for the lifetime of this call. With
# grpcio's single-threaded unary-stream option, nothing else holds a
# reference to it, and a garbage-collected channel cancels its calls.
self._channel = channel
self._call = call
self._attempt_gen = attempt_gen
self._reopen_fn = reopen_fn
self._rotated: Optional[bool] = None

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

Initialize lists to track registered callbacks so that they can be re-registered on the new call if a unary-stream reopen occurs.

Suggested change
def __init__(
self,
rotating_channel: "_RotatingGrpcChannel",
channel: grpc.Channel,
call: Any,
attempt_gen: int,
reopen_fn: Optional[Callable[[], Tuple[grpc.Channel, Any, int]]] = None,
) -> None:
self._rotating_channel = rotating_channel
# Keep the inner channel alive for the lifetime of this call. With
# grpcio's single-threaded unary-stream option, nothing else holds a
# reference to it, and a garbage-collected channel cancels its calls.
self._channel = channel
self._call = call
self._attempt_gen = attempt_gen
self._reopen_fn = reopen_fn
self._rotated: Optional[bool] = None
def __init__(
self,
rotating_channel: "_RotatingGrpcChannel",
channel: grpc.Channel,
call: Any,
attempt_gen: int,
reopen_fn: Optional[Callable[[], Tuple[grpc.Channel, Any, int]]] = None,
) -> None:
self._rotating_channel = rotating_channel
# Keep the inner channel alive for the lifetime of this call. With
# grpcio's single-threaded unary-stream option, nothing else holds a
# reference to it, and a garbage-collected channel cancels its calls.
self._channel = channel
self._call = call
self._attempt_gen = attempt_gen
self._reopen_fn = reopen_fn
self._rotated: Optional[bool] = None
self._done_callbacks: list = []
self._callbacks: list = []

Comment on lines +930 to +942
def __next__(self) -> Any:
try:
item = next(self._call)
self._reopen_fn = None
return item
except grpc.RpcError as exc:
reopen_fn = self._reopen_fn
self._reopen_fn = None
if self._check_rotation(exc.code()) and reopen_fn is not None:
self._channel, self._call, self._attempt_gen = reopen_fn()
self._rotated = None
return next(self._call)
raise

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 the stream is reopened, re-register all previously registered callbacks on the new call instance.

Suggested change
def __next__(self) -> Any:
try:
item = next(self._call)
self._reopen_fn = None
return item
except grpc.RpcError as exc:
reopen_fn = self._reopen_fn
self._reopen_fn = None
if self._check_rotation(exc.code()) and reopen_fn is not None:
self._channel, self._call, self._attempt_gen = reopen_fn()
self._rotated = None
return next(self._call)
raise
def __next__(self) -> Any:
try:
item = next(self._call)
self._reopen_fn = None
return item
except grpc.RpcError as exc:
reopen_fn = self._reopen_fn
self._reopen_fn = None
if self._check_rotation(exc.code()) and reopen_fn is not None:
self._channel, self._call, self._attempt_gen = reopen_fn()
self._rotated = None
for fn in self._done_callbacks:
self._register_done_callback(self._call, fn)
for cb in self._callbacks:
self._register_callback(self._call, cb)
return next(self._call)
raise

Comment on lines +972 to +1000
def _check_rotation_from_callback(self, call: Any) -> None:
# A unary-stream reopen replaces self._call only after checking the old
# attempt, so skip callbacks from the replaced call.
if call is not self._call:
return
# Callbacks run on grpcio's channel thread, where an exception would
# skip the caller's callback (and, for add_callback, stop the thread).
# A failed swap is retried by the next RPC's pre-call check.
with contextlib.suppress(Exception):
self._check_rotation(call.code())

def add_done_callback(self, fn: Callable[[Any], None]) -> Any:
def _done_callback(future: Any) -> None:
self._check_rotation_from_callback(future)
# Pass grpcio's future, not self: bidi recovery needs a grpc.RpcError.
fn(future)

return self._call.add_done_callback(_done_callback)

def add_callback(self, callback: Callable[[], None]) -> Any:
call = self._call

def _callback() -> None:
self._check_rotation_from_callback(call)
callback()

# grpcio logs callbacks that raise via their .func attribute, so wrap
# in a partial to keep that working.
return call.add_callback(functools.partial(_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.

high

When a unary-stream call is reopened, self._call is replaced with the new call. However, any callbacks registered via add_done_callback or add_callback on the original call will still fire when the original call fails (since they were registered on the old self._call).

In _done_callback, self._check_rotation_from_callback(future) returns early if future is not self._call, but the user's callback fn(future) is still invoked with the failed old call. This means the user is prematurely notified of a failure while the stream is actually being retried/reopened. Furthermore, the callbacks are never registered on the new self._call, so the user will not be notified when the retried stream actually completes.

To fix this, we should track registered callbacks in _RotatingCall and, if a reopen occurs, register them on the new call while ignoring the callback triggers from the old/replaced call.

    def _check_rotation_from_callback(self, call: Any) -> None:
        # Callbacks run on grpcio's channel thread, where an exception would
        # skip the caller's callback (and, for add_callback, stop the thread).
        # A failed swap is retried by the next RPC's pre-call check.
        with contextlib.suppress(Exception):
            self._check_rotation(call.code())

    def _register_done_callback(self, call: Any, fn: Callable[[Any], None]) -> Any:
        def _done_callback(future: Any) -> None:
            if call is not self._call:
                return
            self._check_rotation_from_callback(future)
            # Pass grpcio's future, not self: bidi recovery needs a grpc.RpcError.
            fn(future)

        return call.add_done_callback(_done_callback)

    def add_done_callback(self, fn: Callable[[Any], None]) -> Any:
        self._done_callbacks.append(fn)
        return self._register_done_callback(self._call, fn)

    def _register_callback(self, call: Any, callback: Callable[[], None]) -> Any:
        def _callback() -> None:
            if call is not self._call:
                return
            self._check_rotation_from_callback(call)
            callback()

        # grpcio logs callbacks that raise via their .func attribute, so wrap
        # in a partial to keep that working.
        return call.add_callback(functools.partial(_callback))

    def add_callback(self, callback: Callable[[], None]) -> Any:
        self._callbacks.append(callback)
        return self._register_callback(self._call, callback)

Comment on lines +987 to +994
def add_callback(self, callback: Callable[[], None]) -> Any:
def _callback() -> None:
self._check_rotation_from_callback()
callback()

# grpcio logs callbacks that raise via their .func attribute, so wrap
# in a partial to keep that working.
return self._call.add_callback(functools.partial(_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.

Capturing a strong self inside add_callback() breaks grpcio's garbage-collection cancellation semantics and can pin retired channels indefinitely.

In grpcio, Channel's channel_spin thread roots _RPCState.callbacks for the lifetime of an active call. On a raw grpc.Call, registering a non-capturing callback via add_callback() does not keep _MultiThreadedRendezvous alive, so dropping the call object (e.g., breaking out of a streaming loop or raising mid-iteration) still triggers _Rendezvous.__del__(), which cancels the RPC on the server and releases the channel.

Here, _callback closes over strong self (_RotatingCall), which holds self._call (_MultiThreadedRendezvous) and self._channel (the retired grpc.Channel), creating a strong reference path from channel_spin back to _RotatingCall (and a strong cycle through _call._state.callbacks). As a result, dropping an active stream after add_callback() never cancels the RPC and keeps the retired channel pinned until the server terminates the stream or the channel is closed.

Using a weakref.ref(self) in add_callback() restores GC-cancellation while still rotating whenever the call is alive and fails with UNAUTHENTICATED (add_done_callback() should keep strong self, matching grpcio's own functools.partial(fn, self) so fire-and-forget stub.future(req).add_done_callback(cb) continues to work):

    def add_callback(self, callback: Callable[[], None]) -> Any:
        self_ref = weakref.ref(self)

        def _callback() -> None:
            rotating_call = self_ref()
            if rotating_call is not None:
                rotating_call._check_rotation_from_callback()
            callback()

        # grpcio logs callbacks that raise via their .func attribute, so wrap
        # in a partial to keep that working.
        return self._call.add_callback(functools.partial(_callback))

Comment on lines +957 to +971
def result(self, timeout: Optional[float] = None) -> Any:
try:
return self._call.result(timeout=timeout)
except grpc.RpcError as exc:
self._check_rotation(_rpc_error_code(exc))
raise

def exception(self, timeout: Optional[float] = None) -> Any:
exc = self._call.exception(timeout=timeout)
if isinstance(exc, grpc.RpcError):
self._check_rotation(_rpc_error_code(exc))
return exc

def traceback(self, timeout: Optional[float] = None) -> Any:
return self._call.traceback(timeout=timeout)

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.

Passing timeout=timeout as a keyword argument breaks when channel_factory returns an intercepted channel (e.g., BigtableDataClient._build_grpc_channel wraps channels with grpc.intercept_channel() inside the factory).

In grpc._interceptor, both _FailureOutcome (returned by future() when an interceptor raises) and _UnaryOutcome define the parameter as ignored_timeout, not timeout:

def result(self, ignored_timeout=None): ...
def exception(self, ignored_timeout=None): ...
def traceback(self, ignored_timeout=None): ...

Because _RotatingCall always passes timeout=timeout by keyword, even calling fut.result(), fut.exception(), or fut.traceback() with no arguments raises TypeError: _FailureOutcome.result() got an unexpected keyword argument 'timeout', masking the interceptor error or response.

Passing timeout positionally works across _FailureOutcome, _UnaryOutcome, _MultiThreadedRendezvous, _SingleThreadedRendezvous, and _InactiveRpcError:

    def result(self, timeout: Optional[float] = None) -> Any:
        try:
            return self._call.result(timeout)
        except grpc.RpcError as exc:
            self._check_rotation(_rpc_error_code(exc))
            raise

    def exception(self, timeout: Optional[float] = None) -> Any:
        exc = self._call.exception(timeout)
        if isinstance(exc, grpc.RpcError):
            self._check_rotation(_rpc_error_code(exc))
        return exc

    def traceback(self, timeout: Optional[float] = None) -> Any:
        return self._call.traceback(timeout)

Comment on lines +1121 to +1138
except grpc.RpcError as exc:
if not self._rotating_channel._rotate_on_unauthenticated(
_rpc_error_code(exc), attempt_gen
):
raise
if timeout is not None:
timeout -= time.monotonic() - start_time
if timeout <= 0:
raise
_, _, retry_inner = self._resolve_callable()
return retry_inner.with_call(
request,
timeout=timeout,
metadata=metadata,
credentials=credentials,
wait_for_ready=wait_for_ready,
compression=compression,
)

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.

Because Attempt 2 runs inside the except grpc.RpcError as exc: block, any exception raised on the retry (e.g., PERMISSION_DENIED, UNAVAILABLE, or a second UNAUTHENTICATED) gets implicitly chained with exc.__context__ = <attempt 1 UNAUTHENTICATED> and prints "During handling of the above exception, another exception occurred:" in tracebacks/logs even though Attempt 1 was successfully recovered.

Since the try block returns on success and both non-retry paths in except re-raise, unindenting lines 1130–1138 out of the except block avoids polluting __context__:

        try:
            return inner.with_call(
                request,
                timeout=timeout,
                metadata=metadata,
                credentials=credentials,
                wait_for_ready=wait_for_ready,
                compression=compression,
            )
        except grpc.RpcError as exc:
            if not self._rotating_channel._rotate_on_unauthenticated(
                _rpc_error_code(exc), attempt_gen
            ):
                raise
            if timeout is not None:
                timeout -= time.monotonic() - start_time
                if timeout <= 0:
                    raise
        _, _, retry_inner = self._resolve_callable()
        return retry_inner.with_call(
            request,
            timeout=timeout,
            metadata=metadata,
            credentials=credentials,
            wait_for_ready=wait_for_ready,
            compression=compression,
        )

Comment on lines +2233 to +2249
def test_call_keeps_its_channel_alive_after_swap(self):
rotating = grpc_helpers._RotatingGrpcChannel(_make_real_channel)
old_channel = rotating.channel
# Replace the multicallable factory so no RPC is sent.
old_channel.unary_stream = mock.Mock()
call = rotating.unary_stream("/svc/ServerStream")("req")
old_channel_ref = weakref.ref(old_channel)
del old_channel

rotating.swap_channel()
gc.collect()
assert old_channel_ref() is not None

del call
gc.collect()
assert old_channel_ref() is None
rotating.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.

Nit: tied to the GRPC_ENABLE_FORK_SUPPORT=1 note on #19181 — this test fails deterministically if run with GRPC_ENABLE_FORK_SUPPORT=1 because cygrpc._fork_state.channels holds a strong reference to every unclosed real grpc.Channel (so old_channel_ref() stays non-None after del call). Wrapping rotating in with grpc_helpers._RotatingGrpcChannel(...) as rotating: also avoids leaking the active channel if an assertion fails.

If the goal here is purely to verify _RotatingCall holds a reference to old_channel until del call, using a mock channel (or keeping _make_real_channel if we end up closing retired channels deterministically) would keep the test independent of GRPC_ENABLE_FORK_SUPPORT.

Comment on lines +1838 to +1861
def test_concurrent_unauthenticated_failures_build_one_channel(self):
num_threads = 8
ch1 = _make_mock_channel("ch1")
ch2 = _make_mock_channel("ch2")
factory = mock.Mock(side_effect=[ch1, ch2])
cert_manager = _FakeCertManager(generation_id=1, advance_on_refresh=True)
rotating = grpc_helpers._RotatingGrpcChannel(factory, cert_manager=cert_manager)
stub = rotating.unary_unary("/svc/UU")
barrier = threading.Barrier(num_threads)

def fail_together(*args, **kwargs):
barrier.wait()
raise RpcErrorImpl(grpc.StatusCode.UNAUTHENTICATED)

ch1.unary_unary.return_value.with_call.side_effect = fail_together
ch2.unary_unary.return_value.with_call.return_value = ("ok", None)

with futures.ThreadPoolExecutor(num_threads) as executor:
results = [executor.submit(stub, "req") for _ in range(num_threads)]
assert [f.result() for f in results] == ["ok"] * num_threads

assert factory.call_count == 2
assert cert_manager.generation_id == 2
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: two small hardening tweaks for test_concurrent_unauthenticated_failures_build_one_channel:

  • Pass a timeout to threading.Barrier(num_threads, timeout=5) (and f.result(timeout=5)). Because barrier.wait() is inside ch1's fail_together side effect, a regression where only a subset of threads hit ch1 (or retry on ch1) would hang the test runner indefinitely instead of failing fast.
  • Adding a small delay inside factory (like test_concurrent_pre_rpc_checks_build_one_channel above) makes it much more likely to actually exercise lock contention when multiple threads race into _replace_stale_channel_locked().

Comment on lines +1805 to +1836
@pytest.mark.parametrize(
"cert_manager,status_code",
[
(
_FakeCertManager(generation_id=1, advance_on_refresh=False),
grpc.StatusCode.UNAUTHENTICATED,
),
(None, grpc.StatusCode.UNAUTHENTICATED),
(
_FakeCertManager(generation_id=1, advance_on_refresh=True),
grpc.StatusCode.PERMISSION_DENIED,
),
],
)
def test_unary_unary_no_retry_when_not_rotated_or_non_unauthenticated(
self, cert_manager, status_code
):
ch1 = _make_mock_channel("ch1")
rotating = grpc_helpers._RotatingGrpcChannel(
lambda: ch1, cert_manager=cert_manager
)
stub = rotating.unary_unary("/svc/UU")

rpc_err = RpcErrorImpl(status_code)
ch1.unary_unary.return_value.with_call.side_effect = rpc_err

with pytest.raises(grpc.RpcError) as exc_info:
stub("req")

assert exc_info.value is rpc_err
assert rotating.channel is ch1
assert ch1.unary_unary.return_value.with_call.call_count == 1

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: _FakeCertManager(...) is instantiated at collection time inside @pytest.mark.parametrize, so refresh_calls carries state across repeated runs (e.g., pytest --count=N). Also, factory is lambda: ch1 and refresh_calls isn't asserted, so the test wouldn't catch a regression that calls refresh() on PERMISSION_DENIED, skips refresh() on UNAUTHENTICATED, or invokes factory() unnecessarily.

Parametrizing advance_on_refresh (False / None / True) + expected_refresh_calls ([1] / None / []), constructing _FakeCertManager inside the test, and asserting factory.call_count == 1 and cert_manager.refresh_calls == expected_refresh_calls would tighten this up.

Comment on lines +2294 to +2312
def test_unauthenticated_after_close_does_not_rebuild(self):
ch1 = _make_mock_channel("ch1")
factory = mock.Mock(return_value=ch1)
cert_manager = _FakeCertManager(generation_id=1, advance_on_refresh=True)
rotating = grpc_helpers._RotatingGrpcChannel(factory, cert_manager=cert_manager)
unauth_err = RpcErrorImpl(grpc.StatusCode.UNAUTHENTICATED)
raw_future = mock.MagicMock()
raw_future.result.side_effect = unauth_err
ch1.unary_unary.return_value.future.return_value = raw_future

fut = rotating.unary_unary("/svc/UU").future("req")
rotating.close()

with pytest.raises(grpc.RpcError) as exc_info:
fut.result()
assert exc_info.value is unauth_err
assert cert_manager.refresh_calls == []
assert factory.call_count == 1
ch1.close.assert_called_once_with()

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: a few edge cases added in this PR don't have direct test coverage yet:

  1. close() racing during cert_manager.refresh() (grpc_helpers.py L1411–1412 / L1446–1447): test_unauthenticated_after_close_does_not_rebuild closes before fut.result(), so it only hits the pre-refresh fast-path (or self._closed on L1438). Testing rotating.close() triggered inside cert_manager.refresh() on a synchronous unary_unary call would cover _replace_stale_channel_locked() returning False and confirm no retry is attempted on the closed channel.
  2. Attempt 2 also raising UNAUTHENTICATED: verifying the single-retry bound (even when cert_manager would rotate again) and — if moving Attempt 2 outside except — asserting exc.__context__ is None.
  3. _check_rotation_from_callback() suppressing self._call.code() exceptions (grpc_helpers.py L976–977): verifying that if raw_call.code() raises during add_done_callback / add_callback, the exception is suppressed and the caller's callback still runs.

Comment on lines +903 to +904
class _RotatingCall(grpc.Call, grpc.Future):
"""Call and Future proxy that runs the rotation check when the call fails."""

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): forwarding __repr__ / __str__ to self._call (or including self._call!r) preserves grpcio's status/details/debug string when a _RotatingCall is logged or inspected in debugging output.

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