Skip to content

[Serve] Cancel local await task on unary proxy response timeout/disconnect - #67109

Merged
abrarsheikh merged 3 commits into
ray-project:masterfrom
pardeep-singh:fix/serve-unary-timeout-cancel-local-task
Nov 5, 2026
Merged

abrarsheikh merged 3 commits into
ray-project:masterfrom
pardeep-singh:fix/serve-unary-timeout-cancel-local-task

Conversation

@pardeep-singh

@pardeep-singh pardeep-singh commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Description

On a timeout or client disconnect, ProxyResponseGenerator._get_unary_result() cancels the DeploymentResponse but 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 raising TimeoutError / CancelledError.

This picks up #65721 by @hsusul, which was closed as stale, and addresses its review feedback:

  • Tests don't use the private module: the regression tests no longer use ProxyResponseGenerator directly. Instead they go through the gRPC proxy's unary entrypoint (timeout) and HTTPProxy.__call__ (client disconnect) in tests/unit/test_proxy.py. Both use a fake response whose await is not woken by cancel().
  • Cancel the response first: it adopts the suggestion to call 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:

  • The two new tests fail without the fix and pass with it.
  • Also passing: tests/unit/test_proxy.py, test_proxy_request_response.py, test_proxy_router.py, tests/test_proxy_response_generator.py, tests/test_request_timeout.py and tests/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:

pytest python/ray/serve/tests/unit/test_proxy.py   # 43 passed
pre-commit run --files python/ray/serve/_private/proxy_response_generator.py python/ray/serve/tests/unit/test_proxy.py   # all hooks pass

AI assistance: I used an AI coding assistant to write this change, its tests and this description.

…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]>
@pardeep-singh
pardeep-singh requested a review from a team as a code owner October 16, 2026 07:16

@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 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.

Comment on lines +180 to +181
result_task.cancel()
await asyncio.gather(result_task, return_exceptions=True)

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.

medium

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.

Suggested change
result_task.cancel()
await asyncio.gather(result_task, return_exceptions=True)
result_task.cancel()
try:
await result_task
except (asyncio.CancelledError, RequestCancelledError):
pass

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +185 to +186
result_task.cancel()
await asyncio.gather(result_task, return_exceptions=True)

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.

medium

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.

Suggested change
result_task.cancel()
await asyncio.gather(result_task, return_exceptions=True)
result_task.cancel()
try:
await result_task
except (asyncio.CancelledError, RequestCancelledError):
pass

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]>
@ray-gardener ray-gardener Bot added serve Ray Serve Related Issue community-contribution Contributed by the community labels Oct 16, 2026
Fixes the pre-commit mypy check ("Cannot determine type of 'result'").

Signed-off-by: Pardeep Singh <[email protected]>
akyang-anyscale pushed a commit that referenced this pull request Oct 29, 2026
…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]>
@github-actions

github-actions Bot commented Nov 5, 2026

Copy link
Copy Markdown

This pull request has been automatically marked as stale because it has not had
any activity for 14 days. It will be closed in another 14 days if no further activity occurs.
Thank you for your contributions.

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.

@github-actions github-actions Bot added the stale The issue is stale. It will be closed within 7 days unless there are further conversation label Nov 5, 2026

@johntaylor-cell johntaylor-cell 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.

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.

@abrarsheikh abrarsheikh added the go add ONLY when ready to merge, run all tests label Nov 5, 2026
@abrarsheikh
abrarsheikh enabled auto-merge (squash) November 5, 2026 20:58
@abrarsheikh
abrarsheikh merged commit 1b16e00 into ray-project:master Nov 5, 2026
8 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

community-contribution Contributed by the community go add ONLY when ready to merge, run all tests serve Ray Serve Related Issue stale The issue is stale. It will be closed within 7 days unless there are further conversation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Serve] Unary proxy response timeout leaves local await task pending

3 participants