Skip to content

[serve] Let a handler claim its unrouted call - #66643

Open
johntaylor-cell wants to merge 3 commits into
ray-project:masterfrom
johntaylor-cell:serve-forward-router
Open

johntaylor-cell wants to merge 3 commits into
ray-project:masterfrom
johntaylor-cell:serve-forward-router

Conversation

@johntaylor-cell

@johntaylor-cell johntaylor-cell commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

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:

@serve.deployment
class Gateway:
    def __init__(self, model: DeploymentHandle):
        self.model = model

    async def __call__(self, request: Request):
        # Returned unawaited, so Serve sends the model's stream straight to the client.
        return self.model.options(stream=True).generate.remote(await request.json())

This PR adds the routing groundwork; the next PR uses it.

  • A DeploymentResponse keeps its call until routing starts, so the replica can take the call 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, so the handler can return it first. A blocking .result() hands it over at once.

The four PRs

  1. Routing groundwork (this PR): a DeploymentResponse keeps 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.
  2. Forwarding transport: every replica serves a /-/serve/forward route; 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.
  3. End-to-end tests: streamed, plain-text and unary results, child errors, caller disconnects, the Serve proxy path and slot release, in throughput-optimized and default mode.
  4. Least-held picks: 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.

Path (one front replica) req/s, c256 TTFT, c256 req/s, 640 streams TTFT, 640 streams
OpenAI ingress today 25.1 1,059 ms 22.1 13,500 ms
Forwarding 209.8 48 ms 463.6 185 ms
Byte relay (POC #66603) 217.8 40 ms 475.6 138 ms
Direct streaming (no front tier) 216.4 31 ms 492.7 85 ms

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.

@johntaylor-cell
johntaylor-cell requested a review from a team as a code owner October 1, 2026 20:28
@johntaylor-cell johntaylor-cell self-assigned this Oct 1, 2026
@johntaylor-cell johntaylor-cell added serve Ray Serve Related Issue performance go add ONLY when ready to merge, run all tests labels Oct 1, 2026

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

Comment thread python/ray/serve/handle.py Resolved
Comment thread python/ray/serve/_private/router.py Resolved
@johntaylor-cell
johntaylor-cell force-pushed the serve-forward-router branch 2 times, most recently from dda1018 to af150c1 Compare October 1, 2026 20:57
@johntaylor-cell johntaylor-cell changed the title [serve] Let a handler claim its unrouted call; spread pick-only picks [serve] Let a handler claim its unrouted call Oct 1, 2026
@github-actions

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 Oct 17, 2026
@johntaylor-cell johntaylor-cell added unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it. and removed stale The issue is stale. It will be closed within 7 days unless there are further conversation labels Oct 22, 2026
Comment thread python/ray/serve/_private/router.py Resolved
Comment thread python/ray/serve/_private/router.py Resolved
Comment thread python/ray/serve/handle.py Resolved
Comment thread python/ray/serve/_private/replica.py Resolved
johntaylor-cell and others added 3 commits October 27, 2026 00:53
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 YashwanthRanjanSingaravel 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.

Looks good!

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]>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

go add ONLY when ready to merge, run all tests performance serve Ray Serve Related Issue unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants