Repository navigation
[serve] Let a handler claim its unrouted call - #66643
johntaylor-cell wants to merge 3 commits into
Conversation
There was a problem hiding this comment.
Code Review
This pull request introduces a mechanism to allow a replica handler to claim and forward unawaited calls before they are routed. It adds a _routing_started flag to RequestMetadata, tracks held replica picks in the router to balance load, and implements _HandOffFuture to defer cross-thread routing hand-offs. It also adds a _claim_pending_call method to DeploymentResponse along with comprehensive unit tests. The review feedback highlights a potential race condition in _claim_pending_call where a failed cancellation could lead to duplicate execution, and suggests an optimization in _HandOffFuture to check if the future is already done before invoking the hand-off.
dda1018 to
af150c1
Compare
|
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. |
A call a handler makes and returns unawaited can now be taken over before the router sends it, so Serve can forward it instead of relaying its result. In default mode, a call made during a replica request reaches the router thread on the caller's next loop turn; a blocking wait on its future hands it off at once. Co-Authored-By: Claude <[email protected]> Signed-off-by: john.taylor <[email protected]>
Only a plain (non-ASGI) HTTP handler's return value can be forwarded, so only its calls now wait for the caller's next loop turn; every other replica call hands off at once, as on master. Awaiting a deferred call hands it off immediately, so it no longer queues behind the loop's other work, and a composed or cross-loop wait no longer hangs while that loop is blocked. The pending hand-off now lives on the future only until it runs or is claimed, so a routed call is freed without the cycle collector. A claim takes the same pending hand-off that a blocking wait on another thread does, so only one of them wins, and it refuses a cancelled call or a response that another call takes as an argument. _PendingCall is now a NamedTuple. Co-Authored-By: Claude <[email protected]> Signed-off-by: john.taylor <[email protected]>
In default mode a plain HTTP handler's calls reached the router thread only when the handler's loop turned. A handler that blocked its loop on a call's side effect hung, and every call it made waited for its next await. The call now goes to the router thread at once, as on master, and a claim wins only if the router thread has not started it; a lock decides the race, and a call that loses is relayed. Calls outside plain HTTP handlers get a plain Future again. A response also drops its pending call once routing ends, so it stops holding the call's arguments, and a replica test checks that only plain HTTP handlers mark their calls forwardable. Co-Authored-By: Claude <[email protected]> Signed-off-by: john.taylor <[email protected]>
YashwanthRanjanSingaravel
left a comment
There was a problem hiding this comment.
Looks good!
867f02e to
d156190
Compare
…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]>
Description
First of four PRs that let a Serve handler return another deployment's response unawaited. Serve then streams the child's HTTP response straight to the caller instead of passing every chunk through Python:
This PR adds the routing groundwork; the next PR uses it.
DeploymentResponsekeeps its call until routing starts, so the replica can take the call over instead of awaiting its result..result()hands it over at once.The four PRs
DeploymentResponsekeeps its call until routing starts, so the replica can take it over instead of awaiting its result. In default mode, a call made during a replica request reaches the router thread on the handler's next loop turn./-/serve/forwardroute; the parent posts the claimed call there and copies the child's HTTP response bytes into the caller's connection. Calls already routing are relayed over the handle.choose_replica(_reserve=False)takes the candidate with the fewest selections still held, so forwarded streams spread evenly across child replicas. Lands last.Results for the complete effort, all four PRs, on one m5.8xlarge with a mock engine at 2.3 ms per token and 500-token outputs, n=2. Each path except direct streaming has one front replica.
Adding support for direct-streaming functionality that allows responses to bypass parent is planned for next set of PRs (after these 4), and an effort to optimize TTFT is planned for after that.