Skip to content

[serve] Fix multiplexed routing retries without reservations - #66170

Merged
jeffreywang88 merged 7 commits into
masterfrom
serve-multiplex-retry
Sep 21, 2026
Merged

jeffreywang88 merged 7 commits into
masterfrom
serve-multiplex-retry

Conversation

@jeffreywang88

@jeffreywang88 jeffreywang88 commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Problem

choose_replica(_reserve=False) previously called the routing policy once and failed if it returned no candidates. Multiplexed routing can temporarily return no candidates while model-location metadata propagates, even when eligible replicas exist. Through an ingress request router, this becomes a client-visible HTTP 503.

Solution

Reuse the existing selection retry loop with the same pending request so the policy can fall back to an eligible replica. Selection still skips capacity reservations and queue-length probes. Explicitly close the generator to clean up its backoff accounting on success and cancellation.

Add a Serve-only HAProxy integration test emulating Serve LLM's separate ingress router: select a backend replica with a multiplexed handle and _reserve=False, then return its endpoint for HAProxy to forward the original request. Hold the model-location index empty and require two requests to succeed without client retries.

Implication for LLM applications

When a LoRA adapter first loads, there’s a delay before its location propagates through the controller to the router. An immediate subsequent request can fail because the router remembers that an earlier request was sent to a replica to load the adapter, but it has not yet received metadata identifying a replica hosting it. In this state, the multiplexed policy returns no candidates on the new request’s first selection attempt. The old _reserve=False path fails immediately instead of retrying, producing HTTP 503.

With the retry mechanism, selection runs again using the same pending request, preserving its fallback state. The policy can then select an eligible replica even before the metadata arrives, so this propagation delay alone no longer causes a client-visible failure.

Stack

#65678 → #65679 → this PR → #65680

@jeffreywang88 jeffreywang88 changed the title [Serve] Fix multiplexed routing retries without reservations [serve] Fix multiplexed routing retries without reservations Sep 15, 2026
@jeffreywang88
jeffreywang88 marked this pull request as ready for review September 15, 2026 06:40
@jeffreywang88
jeffreywang88 requested a review from a team as a code owner September 15, 2026 06:40

@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 updates the replica selection logic in choose_replica (when reserve=False) to reuse the selection retry loop with backoff, allowing it to handle cases where routing policies temporarily return no candidates. It also adds a test to verify multiplexed routing retry behavior. The review feedback highlights a compatibility issue: the use of contextlib.aclosing and anext() will cause runtime errors on Python 3.8 and 3.9, which Ray supports. The reviewer suggests replacing these with a try...finally block that manually calls __anext__() and aclose().

Comment thread python/ray/serve/_private/router.py Resolved
Comment thread python/ray/serve/_private/router.py Resolved
@jeffreywang88 jeffreywang88 added the go add ONLY when ready to merge, run all tests label Sep 15, 2026
@ray-gardener ray-gardener Bot added serve Ray Serve Related Issue llm labels Sep 15, 2026
jeffreywang88 added a commit that referenced this pull request Sep 15, 2026
)

## Description
- Enable model multiplexing for direct-ingress deployments over both
HTTP and gRPC.
- Remove the deployment-time and runtime rejections that prevented a
multiplexed direct-ingress app from running.
- At the direct ASGI entry point, recognize both
`serve_multiplexed_model_id` and proxy-normalized
`serve-multiplexed-model-id`, then store the value in
`RequestMetadata.multiplexed_model_id`.
- At the direct gRPC entry point, read `multiplexed_model_id` from gRPC
invocation metadata and store it in
`RequestMetadata.multiplexed_model_id`.

### Client usage

```python
# HTTP
response = httpx.get(
    direct_ingress_url,
    headers={"serve_multiplexed_model_id": "multiplex-model-id"},
)
```

```python
# gRPC
response = stub.Method2(
    request,
    metadata=(
        ("application", "default"),
        ("multiplexed_model_id", "multiplex-model-id"),
    ),
)
```

## Related issues
Stack: This PR -> #65679 ->
#66170 ->
#65680 -> `KVAwareRouter` LoRA
support.

## Additional information
> Optional: Add implementation details, API changes, usage examples,
screenshots, etc.

---------

Signed-off-by: Jeffrey Wang <[email protected]>
Base automatically changed from round-robin-multiplexing to master September 15, 2026 18:49
@jeffreywang88
jeffreywang88 requested a review from a team as a code owner September 15, 2026 18:49
jeffreywang88 added a commit that referenced this pull request Sep 15, 2026
## Description
Enable `RoundRobinRouter` to use `MultiplexMixin` for requests with a
multiplexed model ID. Replica selection proceeds as follows:

1. Serve provides the currently viable candidate replicas.
2. `apply_multiplex_routing()` first selects replicas already hosting
the requested model. This warm tier uses a per-model round-robin cursor.
3. If no host is known, or those hosts were already attempted, it
selects replicas with the fewest loaded models. This fallback uses the
shared cursor.
4. After the matching timeout, it tries fewest-model replicas once more,
then all replicas, using the shared cursor.
5. The router intersects the selected tier with viable candidates and
applies round-robin ordering.

Non-multiplexed requests retain existing shared-cursor round-robin
behavior.

### Why `ConsistentHashRouter` is skipped?

Model multiplexing and consistent hashing can place conflicting
constraints on replica selection. Model multiplexing limits the
candidates to replicas that have the requested model loaded, while
consistent hashing maps a request to a specific replica. The problem is
that the hashed replica may not be one of the replicas with that model
loaded.

Since it is unclear which constraint should take priority, we
deliberately do not support model multiplexing with
`ConsistentHashRouter`.

## Related issues

Stack: #65678 -> this PR ->
#66170 ->
#65680 -> `KVAwareRouter` LoRA
support.

---------

Signed-off-by: Jeffrey Wang <[email protected]>
asyncio.wrap_future(future)
)
else:
selection, context_manager = await asyncio.wrap_future(future)

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.

This is the path for “pick a replica, but do not reserve capacity,” used by direct streaming.

Why? If the caller gives up, Serve now stops looking for a replica too. It no longer keeps a background selection attempt alive while waiting for replicas or retrying an empty result. That is, with _reserve=False, cancellation propagates through asyncio.wrap_future() to the router-loop selection task instead of being blocked by asyncio.shield().

Normal requests still behave as before: they reserve replica capacity, so asyncio.shield() keeps selection entry running after caller cancellation. This ensures that, if a reservation is acquired, Serve can safely close the selection context and release that reservation.

assert reserved_slots == 0

@pytest.mark.asyncio
async def test_no_reserve_cancel_stops_replica_wait(

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.

Added two tests to cover both ways replica selection can wait:

  • No replicas are available yet.
  • Replicas exist, but the routing policy temporarily returns no candidates and retries.

These verify that cancelling the caller stops the underlying selection work and cleans up retry/backoff tracking. Without this change, the caller receives cancellation but replica selection can continue in the background, so the client’s cancellation is not fully honored.

)
replica = FakeReplica(r1_id)
fake_request_router._replicas_list = [replica]
fake_request_router._replicas = {r1_id: replica}

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.

_replicas tells selection that a replica exists, and _replicas_list supplies it to the policy. The test needs both to avoid waiting for replicas instead of testing selection.

)
else:
# Unlike reserved requests, which shield cancellation until
# ``__aenter__`` completes so their slot can be released, do not shield:

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.

Not blocking: would a handle.pick_replica() API distinct from handle.choose_replica() be helpful here?

Seems that we're entering into distinct task lifetime regimes based on _reserve parameter that may be cleaner to separate

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.

Yes, I think in general we should re-factor / re-implement RequestRouter to have better abstractions. Tracking here: #63200.

@jeffreywang88
jeffreywang88 merged commit 60c1819 into master Sep 21, 2026
6 checks passed
@jeffreywang88
jeffreywang88 deleted the serve-multiplex-retry branch September 21, 2026 19:42
owenowenisme pushed a commit to owenowenisme/ray that referenced this pull request Sep 23, 2026
…ject#66170)

## Problem
`choose_replica(_reserve=False)` previously called the routing policy
once and failed if it returned no candidates. Multiplexed routing can
temporarily return no candidates while model-location metadata
propagates, even when eligible replicas exist. Through an ingress
request router, this becomes a client-visible HTTP 503.

## Solution
Reuse the existing selection retry loop with the same pending request so
the policy can fall back to an eligible replica. Selection still skips
capacity reservations and queue-length probes. Explicitly close the
generator to clean up its backoff accounting on success and
cancellation.

Add a Serve-only HAProxy integration test emulating Serve LLM's separate
ingress router: select a backend replica with a multiplexed handle and
`_reserve=False`, then return its endpoint for HAProxy to forward the
original request. Hold the model-location index empty and require two
requests to succeed without client retries.

## Implication for LLM applications
When a LoRA adapter first loads, there’s a delay before its location
propagates through the controller to the router. An immediate subsequent
request can fail because the router
[remembers](https://github.com/ray-project/ray/blob/9634fa77aab2ece9759b380d20d315d4e27c912b/python/ray/serve/_private/request_router/request_router.py#L331)
that an earlier request was sent to a replica to load the adapter, but
it has not yet received metadata identifying a replica hosting it. In
this state, the multiplexed policy returns no candidates on the new
request’s first selection attempt. The old `_reserve=False`
[path](https://github.com/ray-project/ray/blob/9634fa77aab2ece9759b380d20d315d4e27c912b/python/ray/llm/_internal/serve/core/ingress/router.py#L314-L319)
fails immediately instead of retrying, producing HTTP 503.

With the retry mechanism, selection runs again using the same pending
request, preserving its fallback state. The policy can then select an
eligible replica even before the metadata arrives, so this propagation
delay alone no longer causes a client-visible failure.

## Stack

ray-project#65678 → ray-project#65679 → this PR → ray-project#65680

---------

Signed-off-by: Jeffrey Wang <[email protected]>
jeffreywang88 added a commit that referenced this pull request Sep 29, 2026
…gregated deployments (#65680)

## Description
Enable LoRA multiplexing for direct streaming, including PD deployments.

### How LoRA used to work with non-direct-streaming?
For normal, non-direct-streaming requests, `OpenAIIngress` calls
`LLMServer.chat()` or `completions()`, which reach `_run_request()` and
resolve the requested LoRA before submitting work to vLLM.

### How LoRA now works with direct streaming?
Direct streaming instead has the ingress router select a replica,
HAProxy proxy the request to that replica’s native vLLM ASGI
application, and stream the response back to the client. That path
bypasses `LLMServer.chat()`, `completions()`, and `_run_request()`, so
LoRA was never resolved.

In this PR,
- [Fix] Initialize vLLM’s OpenAI serving state once and share it with
the native ASGI app. When the LoRA resolver registers an adapter, the
`/v1/completions`, `/v1/chat/completions`, and `/v1/models` handlers now
see that same adapter registry.
- [Test] Add a direct-streaming LoRA test that sends a cold adapter
request through HAProxy, verifies the adapter appears in `/v1/models`,
and exercises base-model and adapter requests through completions and
chat-completions, with and without streaming.
- [Config and docs] Require request-body forwarding for direct-streaming
multi-LoRA, enable it in the direct-streaming release test job, and
document the required settings.
- [Existing] For a LoRA-enabled direct-streaming application,
`LLMRouter` reads the requested `model` from the forwarded request body.
If it belongs to the configured base model, it selects through a
multiplexed Serve handle and HAProxy injects the resulting trusted
adapter header for the selected replica.
- [Existing] `LLMServer` adds a LoRA-resolving ASGI middleware before
vLLM handles the request.
- [Existing] Serve’s multiplexed loader downloads and caches the adapter
lazily on the selected replica.

For PD deployments, propagate the multiplexed model ID to the prefill
handle and reject incompatible prefill/decode LoRA configuration.

## Related issues
Stack: #65678 ->
#65679 ->
#66170 -> this PR ->
`KVAwareRouter` LoRA support

## Additional information
> Optional: Add implementation details, API changes, usage examples,
screenshots, etc.

---------

Signed-off-by: Jeffrey Wang <[email protected]>
jeffreywang88 added a commit that referenced this pull request Oct 3, 2026
…66489)

## Problem
`choose_replica(_reserve=False)` picks a replica and returns without
calling the request router's `on_request_routed` hook. Pick-only callers
send the request themselves. For example, the Serve LLM ingress router
[returns the picked
replica](https://github.com/ray-project/ray/blob/743f0d31866a05a221ccb605e2ae8331cdff304a/python/ray/llm/_internal/serve/core/ingress/router.py#L314-L319)
to HAProxy, and HAProxy forwards the request. For these callers the pick
is the routing decision, but stateful routing policies never see it.

## Solution
Call `on_request_routed(pending_request, replica_id, None)` on the
pick-only path. There is no `ReplicaResult` on this path, so the base
class now types `result` as `Optional[ReplicaResult]` and documents when
it is `None`. Update the `CapacityQueueRouter` docstring, which said
that the hook runs only for the rejection protocol. The reserved path
does not change.

Add a unit test: a `_reserve=False` selection calls `on_request_routed`
once, with the request args and `result=None`, and exiting the context
does not call it again.

Add a Serve-only HAProxy test in the same shape as
`test_multiplexed_routing_retry` (#66170): an ingress router picks a
backend replica with `_reserve=False`, and HAProxy forwards the request
to it. The backend policy keeps its state only in `on_request_routed`
(it ranks the last routed replica last). Four requests must reach both
replicas. Without this change, all four go to the same replica.

Add a manual GPU release test (`release/llm_tests/prefix_router_test`,
mirrors `llm_tests/kv_router_test`) that reproduces this bug on a real
cluster: 4 direct-streaming `LLMServer` replicas routed by
`PrefixCacheAffinityRouter`, asserting that unrelated prompts spread
across every replica and repeated prompts pin to one. Both checks call
`choose_replica(_reserve=False)` directly, so they exercise the real
routing decision without spending GPU time on inference.

## Implication for LLM applications
With direct streaming (`RAY_SERVE_LLM_ENABLE_DIRECT_STREAMING=1`), the
LLM ingress router picks replicas with `_reserve=False`.
`PrefixCacheAffinityRouter` inserts prompts into its prefix tree only in
[`on_request_routed`](https://github.com/ray-project/ray/blob/743f0d31866a05a221ccb605e2ae8331cdff304a/python/ray/llm/_internal/serve/routing_policies/prefix_aware/prefix_aware_router.py#L414-L418),
so on this path the tree stays empty. No prompt matches, so every
request falls back to
[`get_smallest_tenants()`](https://github.com/ray-project/ray/blob/743f0d31866a05a221ccb605e2ae8331cdff304a/python/ray/llm/_internal/serve/routing_policies/prefix_aware/prefix_tree.py#L546-L562).
That call returns all replicas tied at 0 characters, in the same order
each time, and the pick-only path takes the first one. All traffic goes
to one replica, and there is no prefix-cache affinity.

We saw this on a 5-replica deployment with the same image and the same
prompts:

| Ingress | Load | Requests per replica | Prefix tree |
|---|---|---|---|
| Default | 100 unique prompts + 1 smoke test, concurrency 1 | 20 / 20 /
20 / 20 / 21 | Filled |
| Direct streaming | 100 unique prompts + 1 smoke test, concurrency 1 |
101 / 0 / 0 / 0 / 0 | Empty |
| Direct streaming | 20 shared prefixes, concurrency 16 | 1,000 / 0 / 0
/ 0 / 0 | Empty |

## Additional information
- `PrefixCacheAffinityRouter.on_request_routed` waits for the tree actor
with `ray.get`. The reserved path already calls it. The pick-only path
now calls it once per selection.
- Related: #63517 added the pick-only path, and #66170 added its
selection retry loop.
- The GPU release test is `frequency: manual`, matching
`llm_serve_kv_router`; it has not been run on a real cluster from this
environment.

---------

Signed-off-by: Dhakshin Suriakannu <[email protected]>
Signed-off-by: Jeffrey Wang <[email protected]>
Co-authored-by: Jeffrey Wang <[email protected]>
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
…-project#65678)

## Description
- Enable model multiplexing for direct-ingress deployments over both
HTTP and gRPC.
- Remove the deployment-time and runtime rejections that prevented a
multiplexed direct-ingress app from running.
- At the direct ASGI entry point, recognize both
`serve_multiplexed_model_id` and proxy-normalized
`serve-multiplexed-model-id`, then store the value in
`RequestMetadata.multiplexed_model_id`.
- At the direct gRPC entry point, read `multiplexed_model_id` from gRPC
invocation metadata and store it in
`RequestMetadata.multiplexed_model_id`.

### Client usage

```python
# HTTP
response = httpx.get(
    direct_ingress_url,
    headers={"serve_multiplexed_model_id": "multiplex-model-id"},
)
```

```python
# gRPC
response = stub.Method2(
    request,
    metadata=(
        ("application", "default"),
        ("multiplexed_model_id", "multiplex-model-id"),
    ),
)
```

## Related issues
Stack: This PR -> ray-project#65679 ->
ray-project#66170 ->
ray-project#65680 -> `KVAwareRouter` LoRA
support.

## Additional information
> Optional: Add implementation details, API changes, usage examples,
screenshots, etc.

---------

Signed-off-by: Jeffrey Wang <[email protected]>
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
…#65679)

## Description
Enable `RoundRobinRouter` to use `MultiplexMixin` for requests with a
multiplexed model ID. Replica selection proceeds as follows:

1. Serve provides the currently viable candidate replicas.
2. `apply_multiplex_routing()` first selects replicas already hosting
the requested model. This warm tier uses a per-model round-robin cursor.
3. If no host is known, or those hosts were already attempted, it
selects replicas with the fewest loaded models. This fallback uses the
shared cursor.
4. After the matching timeout, it tries fewest-model replicas once more,
then all replicas, using the shared cursor.
5. The router intersects the selected tier with viable candidates and
applies round-robin ordering.

Non-multiplexed requests retain existing shared-cursor round-robin
behavior.

### Why `ConsistentHashRouter` is skipped?

Model multiplexing and consistent hashing can place conflicting
constraints on replica selection. Model multiplexing limits the
candidates to replicas that have the requested model loaded, while
consistent hashing maps a request to a specific replica. The problem is
that the hashed replica may not be one of the replicas with that model
loaded.

Since it is unclear which constraint should take priority, we
deliberately do not support model multiplexing with
`ConsistentHashRouter`.

## Related issues

Stack: ray-project#65678 -> this PR ->
ray-project#66170 ->
ray-project#65680 -> `KVAwareRouter` LoRA
support.

---------

Signed-off-by: Jeffrey Wang <[email protected]>
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
…ject#66170)

## Problem
`choose_replica(_reserve=False)` previously called the routing policy
once and failed if it returned no candidates. Multiplexed routing can
temporarily return no candidates while model-location metadata
propagates, even when eligible replicas exist. Through an ingress
request router, this becomes a client-visible HTTP 503.

## Solution
Reuse the existing selection retry loop with the same pending request so
the policy can fall back to an eligible replica. Selection still skips
capacity reservations and queue-length probes. Explicitly close the
generator to clean up its backoff accounting on success and
cancellation.

Add a Serve-only HAProxy integration test emulating Serve LLM's separate
ingress router: select a backend replica with a multiplexed handle and
`_reserve=False`, then return its endpoint for HAProxy to forward the
original request. Hold the model-location index empty and require two
requests to succeed without client retries.

## Implication for LLM applications
When a LoRA adapter first loads, there’s a delay before its location
propagates through the controller to the router. An immediate subsequent
request can fail because the router
[remembers](https://github.com/ray-project/ray/blob/9634fa77aab2ece9759b380d20d315d4e27c912b/python/ray/serve/_private/request_router/request_router.py#L331)
that an earlier request was sent to a replica to load the adapter, but
it has not yet received metadata identifying a replica hosting it. In
this state, the multiplexed policy returns no candidates on the new
request’s first selection attempt. The old `_reserve=False`
[path](https://github.com/ray-project/ray/blob/9634fa77aab2ece9759b380d20d315d4e27c912b/python/ray/llm/_internal/serve/core/ingress/router.py#L314-L319)
fails immediately instead of retrying, producing HTTP 503.

With the retry mechanism, selection runs again using the same pending
request, preserving its fallback state. The policy can then select an
eligible replica even before the metadata arrives, so this propagation
delay alone no longer causes a client-visible failure.

## Stack

ray-project#65678 → ray-project#65679 → this PR → ray-project#65680

---------

Signed-off-by: Jeffrey Wang <[email protected]>
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
…gregated deployments (ray-project#65680)

## Description
Enable LoRA multiplexing for direct streaming, including PD deployments.

### How LoRA used to work with non-direct-streaming?
For normal, non-direct-streaming requests, `OpenAIIngress` calls
`LLMServer.chat()` or `completions()`, which reach `_run_request()` and
resolve the requested LoRA before submitting work to vLLM.

### How LoRA now works with direct streaming?
Direct streaming instead has the ingress router select a replica,
HAProxy proxy the request to that replica’s native vLLM ASGI
application, and stream the response back to the client. That path
bypasses `LLMServer.chat()`, `completions()`, and `_run_request()`, so
LoRA was never resolved.

In this PR,
- [Fix] Initialize vLLM’s OpenAI serving state once and share it with
the native ASGI app. When the LoRA resolver registers an adapter, the
`/v1/completions`, `/v1/chat/completions`, and `/v1/models` handlers now
see that same adapter registry.
- [Test] Add a direct-streaming LoRA test that sends a cold adapter
request through HAProxy, verifies the adapter appears in `/v1/models`,
and exercises base-model and adapter requests through completions and
chat-completions, with and without streaming.
- [Config and docs] Require request-body forwarding for direct-streaming
multi-LoRA, enable it in the direct-streaming release test job, and
document the required settings.
- [Existing] For a LoRA-enabled direct-streaming application,
`LLMRouter` reads the requested `model` from the forwarded request body.
If it belongs to the configured base model, it selects through a
multiplexed Serve handle and HAProxy injects the resulting trusted
adapter header for the selected replica.
- [Existing] `LLMServer` adds a LoRA-resolving ASGI middleware before
vLLM handles the request.
- [Existing] Serve’s multiplexed loader downloads and caches the adapter
lazily on the selected replica.

For PD deployments, propagate the multiplexed model ID to the prefill
handle and reject incompatible prefill/decode LoRA configuration.

## Related issues
Stack: ray-project#65678 ->
ray-project#65679 ->
ray-project#66170 -> this PR ->
`KVAwareRouter` LoRA support

## Additional information
> Optional: Add implementation details, API changes, usage examples,
screenshots, etc.

---------

Signed-off-by: Jeffrey Wang <[email protected]>
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
…ay-project#66489)

## Problem
`choose_replica(_reserve=False)` picks a replica and returns without
calling the request router's `on_request_routed` hook. Pick-only callers
send the request themselves. For example, the Serve LLM ingress router
[returns the picked
replica](https://github.com/ray-project/ray/blob/743f0d31866a05a221ccb605e2ae8331cdff304a/python/ray/llm/_internal/serve/core/ingress/router.py#L314-L319)
to HAProxy, and HAProxy forwards the request. For these callers the pick
is the routing decision, but stateful routing policies never see it.

## Solution
Call `on_request_routed(pending_request, replica_id, None)` on the
pick-only path. There is no `ReplicaResult` on this path, so the base
class now types `result` as `Optional[ReplicaResult]` and documents when
it is `None`. Update the `CapacityQueueRouter` docstring, which said
that the hook runs only for the rejection protocol. The reserved path
does not change.

Add a unit test: a `_reserve=False` selection calls `on_request_routed`
once, with the request args and `result=None`, and exiting the context
does not call it again.

Add a Serve-only HAProxy test in the same shape as
`test_multiplexed_routing_retry` (ray-project#66170): an ingress router picks a
backend replica with `_reserve=False`, and HAProxy forwards the request
to it. The backend policy keeps its state only in `on_request_routed`
(it ranks the last routed replica last). Four requests must reach both
replicas. Without this change, all four go to the same replica.

Add a manual GPU release test (`release/llm_tests/prefix_router_test`,
mirrors `llm_tests/kv_router_test`) that reproduces this bug on a real
cluster: 4 direct-streaming `LLMServer` replicas routed by
`PrefixCacheAffinityRouter`, asserting that unrelated prompts spread
across every replica and repeated prompts pin to one. Both checks call
`choose_replica(_reserve=False)` directly, so they exercise the real
routing decision without spending GPU time on inference.

## Implication for LLM applications
With direct streaming (`RAY_SERVE_LLM_ENABLE_DIRECT_STREAMING=1`), the
LLM ingress router picks replicas with `_reserve=False`.
`PrefixCacheAffinityRouter` inserts prompts into its prefix tree only in
[`on_request_routed`](https://github.com/ray-project/ray/blob/743f0d31866a05a221ccb605e2ae8331cdff304a/python/ray/llm/_internal/serve/routing_policies/prefix_aware/prefix_aware_router.py#L414-L418),
so on this path the tree stays empty. No prompt matches, so every
request falls back to
[`get_smallest_tenants()`](https://github.com/ray-project/ray/blob/743f0d31866a05a221ccb605e2ae8331cdff304a/python/ray/llm/_internal/serve/routing_policies/prefix_aware/prefix_tree.py#L546-L562).
That call returns all replicas tied at 0 characters, in the same order
each time, and the pick-only path takes the first one. All traffic goes
to one replica, and there is no prefix-cache affinity.

We saw this on a 5-replica deployment with the same image and the same
prompts:

| Ingress | Load | Requests per replica | Prefix tree |
|---|---|---|---|
| Default | 100 unique prompts + 1 smoke test, concurrency 1 | 20 / 20 /
20 / 20 / 21 | Filled |
| Direct streaming | 100 unique prompts + 1 smoke test, concurrency 1 |
101 / 0 / 0 / 0 / 0 | Empty |
| Direct streaming | 20 shared prefixes, concurrency 16 | 1,000 / 0 / 0
/ 0 / 0 | Empty |

## Additional information
- `PrefixCacheAffinityRouter.on_request_routed` waits for the tree actor
with `ray.get`. The reserved path already calls it. The pick-only path
now calls it once per selection.
- Related: ray-project#63517 added the pick-only path, and ray-project#66170 added its
selection retry loop.
- The GPU release test is `frequency: manual`, matching
`llm_serve_kv_router`; it has not been run on a real cluster from this
environment.

---------

Signed-off-by: Dhakshin Suriakannu <[email protected]>
Signed-off-by: Jeffrey Wang <[email protected]>
Co-authored-by: Jeffrey Wang <[email protected]>
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 llm serve Ray Serve Related Issue

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants