Repository navigation
[Serve] Cancel local await task on unary proxy response timeout/disconnect - #67109
Conversation
…nnect On timeout or client disconnect, _get_unary_result() cancelled the DeploymentResponse but left the local task awaiting it pending. Cancel and await that task too, as the streaming path already cancels its own. Signed-off-by: Pardeep Singh <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request ensures that pending unary response tasks are properly cancelled and awaited when a client disconnects or a timeout occurs, preventing hanging tasks. Unit tests have been added to verify this behavior for both HTTP and gRPC proxies. The feedback suggests replacing the use of asyncio.gather with return_exceptions=True on a single task with a standard try-except block to avoid silently swallowing unexpected exceptions and to reduce overhead.
| result_task.cancel() | ||
| await asyncio.gather(result_task, return_exceptions=True) |
There was a problem hiding this comment.
Using asyncio.gather with return_exceptions=True on a single task is an anti-pattern. It introduces unnecessary overhead by creating a gather task, and more importantly, it silently swallows all unexpected exceptions (not just cancellation-related ones) without logging or propagating them. This can make debugging extremely difficult if the task fails due to an unexpected error during cancellation.
Instead, use a standard try-except block to await the task and explicitly catch and handle only the expected cancellation exceptions (asyncio.CancelledError and RequestCancelledError), allowing any other unexpected exceptions to propagate.
| result_task.cancel() | |
| await asyncio.gather(result_task, return_exceptions=True) | |
| result_task.cancel() | |
| try: | |
| await result_task | |
| except (asyncio.CancelledError, RequestCancelledError): | |
| pass |
There was a problem hiding this comment.
Thanks. I moved the cancel-and-wait into _cancel_result_task, and it now logs any exception other than RequestCancelledError instead of dropping it silently. I kept gather rather than a bare await with except CancelledError: awaiting the cancelled task always raises CancelledError, so catching that would also swallow a cancellation of the caller itself, and letting it propagate would replace the TimeoutError/disconnect the caller expects.
| result_task.cancel() | ||
| await asyncio.gather(result_task, return_exceptions=True) |
There was a problem hiding this comment.
Using asyncio.gather with return_exceptions=True on a single task is an anti-pattern. It introduces unnecessary overhead by creating a gather task, and more importantly, it silently swallows all unexpected exceptions (not just cancellation-related ones) without logging or propagating them. This can make debugging extremely difficult if the task fails due to an unexpected error during cancellation.
Instead, use a standard try-except block to await the task and explicitly catch and handle only the expected cancellation exceptions (asyncio.CancelledError and RequestCancelledError), allowing any other unexpected exceptions to propagate.
| result_task.cancel() | |
| await asyncio.gather(result_task, return_exceptions=True) | |
| result_task.cancel() | |
| try: | |
| await result_task | |
| except (asyncio.CancelledError, RequestCancelledError): | |
| pass |
There was a problem hiding this comment.
Handled by the same helper; see the reply above.
Factor the cancel-and-wait into a helper and log exceptions other than RequestCancelledError instead of silently dropping them, while keeping gather so the caller's own cancellation still propagates. Signed-off-by: Pardeep Singh <[email protected]>
Fixes the pre-commit mypy check ("Cannot determine type of 'result'").
Signed-off-by: Pardeep Singh <[email protected]>
…67531) ## Summary Corrects the exception that the `DeploymentResponse.cancel` docstring says later operations raise after a successful cancel. This is a docstring-only change. Behavior is unchanged. The docstring sits on `_DeploymentResponseBase`, so `DeploymentResponseGenerator.cancel` inherits the fix. ## Before > - If the request was cancelled before assignment, they'll raise `asyncio.CancelledError` (or a `concurrent.futures.CancelledError` for synchronous methods like `.result()`.). > - If the request was cancelled after assignment, they'll raise `ray.exceptions.TaskCancelledError`. A reader following this writes `except concurrent.futures.CancelledError:` around `.result()`, or `except asyncio.CancelledError:` around `await response`. Neither clause catches what Serve raises. ## What the code does Every path raises `ray.serve.exceptions.RequestCancelledError`, which subclasses `TaskCancelledError` ([exceptions.py#L101](https://github.com/ray-project/ray/blob/30ca1d144c9d077177c04acdebbc6486739922bf/python/ray/serve/exceptions.py#L101)): - **Synchronous, before assignment.** `_fetch_future_result_sync` catches the cancelled routing future's `concurrent.futures.CancelledError` and raises `RequestCancelledError` ([handle.py#L394-L395](https://github.com/ray-project/ray/blob/30ca1d144c9d077177c04acdebbc6486739922bf/python/ray/serve/handle.py#L394-L395)). - **Synchronous, after assignment.** `ActorReplicaResult._process_response` converts `TaskCancelledError` to `RequestCancelledError` ([replica_result.py#L159-L165](https://github.com/ray-project/ray/blob/30ca1d144c9d077177c04acdebbc6486739922bf/python/ray/serve/_private/replica_result.py#L159-L165)). The gRPC replica result does the same for `concurrent.futures.CancelledError` ([replica_result.py#L388-L389](https://github.com/ray-project/ray/blob/30ca1d144c9d077177c04acdebbc6486739922bf/python/ray/serve/_private/replica_result.py#L388-L389)). - **`await`, either side.** The async path surfaces an `asyncio.CancelledError` internally ([replica_result.py#L172](https://github.com/ray-project/ray/blob/30ca1d144c9d077177c04acdebbc6486739922bf/python/ray/serve/_private/replica_result.py#L172)), and `DeploymentResponse.__await__` re-raises it as `RequestCancelledError` when the response was cancelled ([handle.py#L548-L556](https://github.com/ray-project/ray/blob/30ca1d144c9d077177c04acdebbc6486739922bf/python/ray/serve/handle.py#L548-L556)). `DeploymentResponseGenerator.__anext__` does the same ([handle.py#L715-L721](https://github.com/ray-project/ray/blob/30ca1d144c9d077177c04acdebbc6486739922bf/python/ray/serve/handle.py#L715-L721)). `test_handle_cancellation.py` already asserts `RequestCancelledError` for all four cases: sync and async, during assignment and during execution ([L17](https://github.com/ray-project/ray/blob/30ca1d144c9d077177c04acdebbc6486739922bf/python/ray/serve/tests/test_handle_cancellation.py#L17), [L46](https://github.com/ray-project/ray/blob/30ca1d144c9d077177c04acdebbc6486739922bf/python/ray/serve/tests/test_handle_cancellation.py#L46), [L82](https://github.com/ray-project/ray/blob/30ca1d144c9d077177c04acdebbc6486739922bf/python/ray/serve/tests/test_handle_cancellation.py#L82), [L118](https://github.com/ray-project/ray/blob/30ca1d144c9d077177c04acdebbc6486739922bf/python/ray/serve/tests/test_handle_cancellation.py#L118)). ## After > If the request is successfully cancelled, subsequent operations on the response raise `ray.serve.exceptions.RequestCancelledError`. This is the same whether the request was cancelled before or after it was assigned to a replica, and whether you `await` the response or call a synchronous method such as `.result()`. `RequestCancelledError` is a subclass of `ray.exceptions.TaskCancelledError`, so `except TaskCancelledError` also catches it. ## Subsystems Serve (docstrings only) ## Not a duplicate I searched open PRs for `DeploymentResponse cancel`, `RequestCancelledError`, and Serve `handle.py` docstring changes. #66643 edits `handle.py` to let a handler claim an unrouted call, and #67109 and #67210 change cancellation handling in the proxy and gRPC stream paths. None of them changes this docstring or the exception the public `cancel` path raises. ## Testing - `pre-commit run --files python/ray/serve/handle.py` passes, including ruff, black, pydoclint, mypy and pyrefly for Serve, and the Ray docstyle check. - I read each path above on master at 30ca1d1. - I ran a probe script against the released `ray[serve]==2.59.0` wheel, whose cancellation paths match master. It cancels a request queued behind a full replica (`max_ongoing_requests=1`) and one already running on it, from a driver with `.result()` and from inside a deployment with `await`. All four raised `ray.serve.exceptions.RequestCancelledError`, and none was an instance of `asyncio.CancelledError` or `concurrent.futures.CancelledError`. - I didn't run the Serve test suite. The existing tests linked above cover the behavior this docstring now describes. The `docstring-only` label is applied to skip the heavy Serve test suites, and the commit carries an `@rtd-build` line to build the API reference preview. I wrote this with AI assistance (Claude Code). I reviewed every changed line and can defend the change. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: Douglas Strodtman <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
|
This pull request has been automatically marked as stale because it has not had You can always ask for help on our discussion forum or Ray's public slack channel. If you'd like to keep this open, just leave any comment, and the stale label will be removed. |
johntaylor-cell
left a comment
There was a problem hiding this comment.
LGTM. The new tests fail without the fix and pass with it (40/40 under CPU load). Against real replicas, timeouts and disconnects still return at the deadline, and this also removes the Task exception was never retrieved: RequestCancelledError log that the unary path emitted on every timeout/disconnect.
Description
On a timeout or client disconnect,
ProxyResponseGenerator._get_unary_result()cancels theDeploymentResponsebut never touches the local asyncio task that is awaiting it. If cancelling the response doesn't promptly wake that await, the proxy keeps a pending task (and the response it references) until the response eventually resolves. The streaming path already cancels its local task.This change calls
self._response.cancel()first, so the replica-side cancellation starts right away. It then cancels and awaits the local result task before raisingTimeoutError/CancelledError.This picks up #65721 by @hsusul, which was closed as stale, and addresses its review feedback:
ProxyResponseGeneratordirectly. Instead they go through the gRPC proxy's unary entrypoint (timeout) andHTTPProxy.__call__(client disconnect) intests/unit/test_proxy.py. Both use a fake response whose await is not woken bycancel().self._response.cancel()before awaiting the local task.With the current replica result implementations,
cancel()wakes the await promptly. I checked this end to end against gRPC timeouts, including with a SIGSTOP'd replica. So this is defensive hardening against delayed cancellation rather than a fix for a leak you can see in today's code paths.Tests:
tests/unit/test_proxy.py,test_proxy_request_response.py,test_proxy_router.py,tests/test_proxy_response_generator.py,tests/test_request_timeout.pyandtests/test_grpc.py.Related issues
Closes #65718
Additional information
The streaming path still uses the cancel-plus-done-callback style. I kept that unchanged to keep this PR focused, and I'm happy to align the two if you'd prefer.
cc @abrarsheikh
Why this isn't a duplicate: the only earlier PR for #65718 is #65721, closed by the stale bot; no other open PR references the issue.
Test commands:
AI assistance: I used an AI coding assistant to write this change, its tests and this description.