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)

@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

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.

1 participant