Repository navigation
Conversation
There was a problem hiding this comment.
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.
| 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 |
There was a problem hiding this comment.
Initialize lists to track registered callbacks so that they can be re-registered on the new call if a unary-stream reopen occurs.
| 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 = [] |
| 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 |
There was a problem hiding this comment.
When the stream is reopened, re-register all previously registered callbacks on the new call instance.
| 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 |
| 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)) |
There was a problem hiding this comment.
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)219558c to
b85525c
Compare
b85525c to
b18e222
Compare
b18e222 to
f128d03
Compare
| 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)) |
There was a problem hiding this comment.
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))| 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) |
There was a problem hiding this comment.
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)| 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, | ||
| ) |
There was a problem hiding this comment.
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,
)| 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() |
There was a problem hiding this comment.
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.
| 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 |
There was a problem hiding this comment.
Nit: two small hardening tweaks for test_concurrent_unauthenticated_failures_build_one_channel:
- Pass a
timeouttothreading.Barrier(num_threads, timeout=5)(andf.result(timeout=5)). Becausebarrier.wait()is insidech1'sfail_togetherside effect, a regression where only a subset of threads hitch1(or retry onch1) would hang the test runner indefinitely instead of failing fast. - Adding a small delay inside
factory(liketest_concurrent_pre_rpc_checks_build_one_channelabove) makes it much more likely to actually exercise lock contention when multiple threads race into_replace_stale_channel_locked().
| @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 |
There was a problem hiding this comment.
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.
| 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() |
There was a problem hiding this comment.
Nit / test coverage: a few edge cases added in this PR don't have direct test coverage yet:
close()racing duringcert_manager.refresh()(grpc_helpers.pyL1411–1412 / L1446–1447):test_unauthenticated_after_close_does_not_rebuildcloses beforefut.result(), so it only hits the pre-refresh fast-path (or self._closedon L1438). Testingrotating.close()triggered insidecert_manager.refresh()on a synchronousunary_unarycall would cover_replace_stale_channel_locked()returningFalseand confirm no retry is attempted on the closed channel.- Attempt 2 also raising
UNAUTHENTICATED: verifying the single-retry bound (even whencert_managerwould rotate again) and — if moving Attempt 2 outsideexcept— assertingexc.__context__ is None. _check_rotation_from_callback()suppressingself._call.code()exceptions (grpc_helpers.pyL976–977): verifying that ifraw_call.code()raises duringadd_done_callback/add_callback, the exception is suppressed and the caller's callback still runs.
| class _RotatingCall(grpc.Call, grpc.Future): | ||
| """Call and Future proxy that runs the rotation check when the call fails.""" |
There was a problem hiding this comment.
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.
Adds reactive
UNAUTHENTICATEDrecovery and the_RotatingCallwrapper to_RotatingGrpcChannel, stacked on PR 4a.When an RPC fails with
UNAUTHENTICATED, the channel checks whether the client certificate rotated (refreshing throughcert_managerif needed). If the certificate did not change, or if refreshing or rebuilding the channel fails, the originalgrpc.RpcErroris re-raised unchanged. When the certificate did rotate, the wrapper swaps to a fresh inner channel once under a lock:_RotatingCallholds 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 agrpc.RpcError. Nothing is retried or swapped onUNAVAILABLE, and_RotatingGrpcChannelis not wired intocreate_channel()yet.