[Python aio] Unary-unary call drops the CancelledError message and context on cancellation (unary-stream keeps it)
What version of gRPC and what language are you using?
grpcio 1.84.0 (also reproduced on 1.83.0), Python, grpc.aio client.
What operating system (Linux, Windows,...) and version?
macOS 15 (Darwin 25.6.0), arm64. The failure that led here was on GitHub Actions ubuntu-latest.
What runtime / compiler are you using (e.g. python version or version of gcc)
CPython 3.11.13, 3.12.11 and 3.13.7 (all reproduce).
What did you do?
Cancelled a task that is awaiting a grpc.aio unary-unary call, using Task.cancel(msg) (the cancellation message added in Python 3.9). The unary-stream path is included for comparison; it behaves correctly.
import asyncio
import grpc
from grpc import aio
class Sleepy(grpc.GenericRpcHandler):
def service(self, details):
async def unary(request, context):
await asyncio.sleep(30)
return b""
async def stream(request, context):
await asyncio.sleep(30)
yield b""
if details.method.endswith("Stream"):
return grpc.unary_stream_rpc_method_handler(stream)
return grpc.unary_unary_rpc_method_handler(unary)
async def cancel_with_message(label, coro_fn):
async def inner():
await coro_fn()
task = asyncio.ensure_future(inner())
await asyncio.sleep(0.2)
task.cancel("my reason")
try:
await task
except asyncio.CancelledError as e:
print(f"{label}: CancelledError args={e.args!r}")
async def main():
server = aio.server()
server.add_generic_rpc_handlers((Sleepy(),))
port = server.add_insecure_port("127.0.0.1:0")
await server.start()
async with aio.insecure_channel(f"127.0.0.1:{port}") as ch:
unary = ch.unary_unary("/t.S/Unary")
stream = ch.unary_stream("/t.S/Stream")
async def consume():
async for _ in stream(b""):
pass
await cancel_with_message("control (asyncio.sleep)", lambda: asyncio.sleep(30))
await cancel_with_message("unary_unary call ", lambda: unary(b""))
await cancel_with_message("unary_stream call ", consume)
await server.stop(None)
asyncio.run(main())What did you expect to see?
The CancelledError that reaches the awaiting task should carry the cancellation message (and its __context__), as it does for a plain await asyncio.sleep() and for a grpc.aio unary-stream call:
control (asyncio.sleep): CancelledError args=('my reason',)
unary_unary call : CancelledError args=('my reason',)
unary_stream call : CancelledError args=('my reason',)What did you see instead?
control (asyncio.sleep): CancelledError args=('my reason',)
unary_unary call : CancelledError args=()
unary_stream call : CancelledError args=('my reason',)Cause, in grpc/aio/_call.py (1.84.0):
UnaryUnaryCall._invokeruns the RPC in a separate task. When the awaiting task is cancelled, asyncio forwards the cancel (with its message) to that inner task._invokecatches theCancelledError, callsself.cancel(), and returnscygrpc.EOFnormally, discarding the exception._UnaryResponseMixin.__await__then seesEOFwithis_locally_cancelled()true and doesraise asyncio.CancelledError(): a new exception with no args and no__context__._StreamResponseMixin._read, by contrast, catches theCancelledError, callsself.cancel()and re-raises the same exception, which is why the stream path keeps the message.
Practical impact: libraries that attribute cancellations by message break for unary calls. anyio (>= 4) only treats a CancelledError as its own if the message (or one in the __context__ chain) starts with "Cancelled via cancel scope". So this:
with anyio.fail_after(1):
await stub.SomeUnaryMethod(request)raises a bare asyncio.CancelledError instead of TimeoutError (scope.cancelled_caught stays False), which is how we hit it: a test-suite timeout around an xAI (xai-sdk, grpc.aio based) unary call surfaced as an unhandled CancelledError rather than a retryable TimeoutError, and the same happens to anyio-based per-attempt timeouts in production. asyncio.timeout() and asyncio.wait_for() are not affected because they count cancel requests rather than reading the message.
Suggested fix: in UnaryUnaryCall._invoke, after self.cancel(), re-raise the caught CancelledError instead of return cygrpc.EOF, mirroring _StreamResponseMixin._read. The inner task then finishes cancelled with its message, and awaiting it inside __await__ raises a CancelledError carrying that message, which the existing except asyncio.CancelledError branch there already handles. The NOTE(lidiz) above the try says CancelledError was avoided as a status transport because Task does not cache the exception object; but Future.result() on a cancelled task re-creates the error from _cancel_message, so the message itself survives. Alternatively, stash the caught exception on the call and re-raise that object from __await__, which also preserves __context__.
Anything else we should know about your project / environment?
Found while investigating a CI failure in inspect_ai (tracked in meridianlabs-ai/inspect_ai#517); we are adding a workaround in our provider. The grpc PR that introduced the current cancellation design is #21506.
Generated with Claude Fable 5.1 (claude-fable-5-1) from a local investigation, reproduced as shown above; filed at Ransom Richardson's request, not reviewed by him.
Source: grpc/grpc