Repository navigation
[serve][LLM] Call on_request_routed for pick-only replica selections - #66489
jeffreywang88 merged 6 commits into
Conversation
There was a problem hiding this comment.
Code Review
This pull request updates the Ray Serve request router to support pick-only routing decisions (where _reserve=False). It modifies the on_request_routed callback to accept an optional ReplicaResult (which is None for pick-only routing), allowing stateful routing policies to track routing decisions and update their internal state. Corresponding unit and integration tests have been added to verify this behavior. There are no review comments to assess, and I have no additional feedback to provide.
There was a problem hiding this comment.
Hey @dhakshin32 thanks for surfacing the issue! Now that you're on it, could you please add some tests for PrefixCacheAffinityRouter with direct streaming under ray/release/llm_tests to exercise the end-to-end path (the behavior you recorded in the PR description)?
Frankly speaking though, adding direct streaming support for PrefixCacheAffinityRouter isn't a high priority as we now recommend to use https://docs.ray.io/en/master/serve/llm/user-guides/kv-aware-routing.html.
ff6cb62 to
8d9218e
Compare
|
@jeffreywang88 Thanks just added that. With regard to KV aware routing, that will be hard to bring it into some stacks since it is couples the ray version with the vllm version. Until we are able to decouple that, we lose the flexibility of vllm versions. |
vinay7373
left a comment
There was a problem hiding this comment.
LGTM. Thanks for raising this and implementing a solution.
There was a problem hiding this comment.
great test cases! can we move test_prefix_affinity_direct_streaming tests under https://github.com/ray-project/ray/blob/master/release/llm_tests/serve/test_llm_serve_integration.py? please fix DCO too.
| """The sequential spread test lets each pick see the previous pick's | ||
| tree insert. With CONCURRENCY requests in flight, picks race those | ||
| inserts, and spreading must still hold. This matches the production | ||
| incident's load shape (16 concurrent requests), where every request | ||
| landed on one replica.""" |
There was a problem hiding this comment.
| """The sequential spread test lets each pick see the previous pick's | |
| tree insert. With CONCURRENCY requests in flight, picks race those | |
| inserts, and spreading must still hold. This matches the production | |
| incident's load shape (16 concurrent requests), where every request | |
| landed on one replica.""" | |
| """The sequential spread test lets each pick see the previous pick's | |
| tree insert. With concurrent requests in flight, picks race those | |
| inserts, and spreading must still hold.""" |
| """Unrelated prompts must spread across every replica. Before the | ||
| fix, ``on_request_routed`` never ran on the pick-only path, so the | ||
| tree stayed empty forever and ``get_smallest_tenants()`` returned | ||
| every replica tied at 0 chars in the same order every time: 100% of | ||
| requests went to one replica.""" |
There was a problem hiding this comment.
| """Unrelated prompts must spread across every replica. Before the | |
| fix, ``on_request_routed`` never ran on the pick-only path, so the | |
| tree stayed empty forever and ``get_smallest_tenants()`` returned | |
| every replica tied at 0 chars in the same order every time: 100% of | |
| requests went to one replica.""" | |
| """Unrelated prompts must spread across every replica. Before | |
| https://github.com/ray-project/ray/pull/66489, ``on_request_routed`` | |
| never ran on the pick-only path, so the prefix tree stayed empty forever | |
| always produced the same replica ordering.""" |
| # Serve replicas can't import this test module, so ship | ||
| # ReplicaIdLLMServer to them by value. | ||
| ray.cloudpickle.register_pickle_by_value(sys.modules[__name__]) | ||
| serve.run(build_openai_app({"llm_configs": [llm_config]}), name=APP_NAME) | ||
|
|
||
| # HAProxy's replica map and LLMRouter's replica set update | ||
| # asynchronously after serve.run() returns. With the bug, every | ||
| # request lands on one replica and this times out. Warm-up prompts | ||
| # are unique, so they never prefix-match a later prompt. | ||
| served = set() |
There was a problem hiding this comment.
we might not need these after moving over to test_llm_serve_integration.py
@dhakshin32 anything that we can help here? |
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 (the Serve LLM ingress router returns the replica to HAProxy, which forwards the request), so the pick is the routing decision. Stateful policies need that hook. PrefixCacheAffinityRouter inserts prompts into its prefix tree only in on_request_routed, so with direct streaming the tree stays empty. Every prompt then falls back to get_smallest_tenants(), which returns all replicas tied in the same order, and the pick-only path takes the first one: all traffic goes to one replica. Call on_request_routed(pr, replica_id, None) on the pick-only path. There is no ReplicaResult there, so document result as Optional on the base class. Update the CapacityQueueRouter docstring to match. Add a unit test for the callback, and a Serve-only HAProxy test that emulates the LLM ingress router with a policy that keeps its state only in on_request_routed. Regression-tested on release by TestPrefixAffinityDirectStreaming in test_llm_serve_integration.py (spread, spread-under-load at the incident concurrency, and prefix pinning), running nightly on llm_serve_vllm_integration_tests_direct_streaming. Co-authored-by: Jeffrey Wang <[email protected]> Signed-off-by: Dhakshin Suriakannu <[email protected]>
8ea7bf1 to
c77b9d6
Compare
|
@jeffreywang88 thanks for the comments, I made some changes to move the tests around and update some of the wording. Regarding the KV aware router usage, the main thing here is the coupling of the Ray and vLLM versions. It restricts us to bring in any version of vLLM we want and with newer models get bug fixes quick we would need the flexibility to quickly upgrade/downgrade vLLM while continuing to use Ray LLM |
gotcha, we've started a conversation about decoupling engine version internally. stay tuned for more updates! |
jeffreywang88
left a comment
There was a problem hiding this comment.
just some styling nits. looking good overall :)
| MODEL_ID = "qwen3-0.6b" | ||
| MODEL_SOURCE = "Qwen/Qwen3-0.6B" | ||
| NUM_REPLICAS = 4 | ||
|
|
||
| # HAProxy's frontend. | ||
| CHAT_URL = "http://localhost:8000/v1/chat/completions" | ||
| REPLICA_ID_HEADER = "x-test-replica-id" | ||
|
|
||
| NUM_UNIQUE_PROMPTS = 60 | ||
| # The bug's signature was 100% of requests on one replica. A cap well below | ||
| # that still fails hard on a regression while tolerating normal | ||
| # length-driven skew in the smallest-tenant tie-break. | ||
| MAX_SHARE_PER_REPLICA = 0.5 | ||
|
|
||
| NUM_PREFIX_GROUPS = 4 | ||
| REPEATS_PER_GROUP = 5 | ||
|
|
||
| # The concurrent spread test uses the production incident's concurrency | ||
| # (16 requests in flight), scaled down from its 1,000 requests. | ||
| NUM_CONCURRENT_PROMPTS = 200 | ||
| CONCURRENCY = 16 |
There was a problem hiding this comment.
can we follow the existing coding style of this file, either use the literals directly for declare local vars within the test functions?
| LLMRouter's ``/internal/route`` handler picks a replica via | ||
| ``handle.choose_replica(_reserve=False)``. Before the fix, that path never | ||
| called the request router's ``on_request_routed`` hook, so | ||
| PrefixCacheAffinityRouter's prefix tree stayed empty and every request fell | ||
| back to ``get_smallest_tenants()``, which returns every replica tied at 0 | ||
| characters in the same order every time -- so 100% of requests went to one | ||
| replica. The tests send chat requests to HAProxy, so each one takes that | ||
| production path, and read the serving replica from the response header that | ||
| ReplicaIdLLMServer stamps. |
There was a problem hiding this comment.
let's rewrite the docstrings (including other tests introduced in this PR) to be more concise and just explain why not what
- Match test_llm_serve_integration.py style: drop the module-level constants, use literals and per-test locals directly. - Tighten the docstrings of the tests added in ray-project#66489 to explain why, not what. Signed-off-by: Dhakshin Suriakannu <[email protected]>
…-on-request-routed # Conflicts: # release/llm_tests/serve/test_llm_serve_integration.py
@jeffreywang88 Thanks looking forward to this! Just addressed the last 2 comments |
Signed-off-by: Jeffrey Wang <[email protected]>
…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]>
…or (#66671) PrefixCacheAffinityRouter called ray.get on its prefix tree actor inside choose_replicas (one or two round trips per routing attempt) and in on_request_routed, update_replicas and on_replica_actor_died. Each call stalled the router's event loop, which every DeploymentHandle in the process shares, so routing throughput was capped by the actor round trip and other requests' queue length probes waited behind it. - Await the tree lookup instead of calling ray.get, and send it before the load check so the round trip overlaps with any queue length probes. - Do the prefix match and the smallest-tenants fallback in one actor call, prefix_match_or_smallest_tenants. Empty text now falls back to the smallest tenants instead of raising ZeroDivisionError. - Don't wait on insert, add_tenants, remove_tenants or start_eviction_loop. The actor runs one caller's tasks in submission order, so later lookups from this process still see them. - Drop tree results for replicas that left while the lookup was in flight. ### Benchmark The release test added here, `llm_serve_prefix_router_overhead_benchmark` (`release/llm_tests/serve/prefix_router_overhead_benchmark.py`): 2 replicas behind `PrefixCacheAffinityRouter` (default kwargs) that reply immediately, so only routing costs time. Prompts are ~1 KiB from 8 shared system prompts; closed-loop clients for 5 s per concurrency level. `handle` is `handle.remote()`, as `OpenAiIngress` calls `LLMServer`; `direct` is `handle.choose_replica(..., _reserve=False)`, as the direct-streaming `LLMRouter` does. "Loop stall" is the p99 oversleep of a 1 ms heartbeat on the router's event loop. Run on the release test's setup (Anyscale m5.2xlarge, `anyscale/ray-llm:nightly-py312-cu130` at master `a4a924c1c5`), 5 rounds alternating the image's router with this PR's (`prefix_aware_router.py` and `prefix_tree.py` at `f4ea105b04` copied over the installed ones). Median of 5, master → this PR: | path | concurrency | req/s | p50 ms | p99 ms | router loop stall p99 ms | |---|---|---|---|---|---| | handle | 1 | 192 → 213 | 5.1 → 4.6 | 7.3 → 7.0 | 1.9 → 1.1 | | handle | 8 | 249 → 316 | 31.5 → 24.7 | 42.9 → 36.7 | 14.3 → 5.6 | | handle | 32 | 260 → 315 | 121.8 → 100.8 | 146.3 → 132.1 | 54.8 → 12.7 | | handle | 64 | 256 → 312 | 242.5 → 202.9 | 320.4 → 238.9 | 143.1 → 13.1 | | direct | 1 | 357 → 436 | 2.7 → 2.1 | 5.1 → 5.1 | 3.8 → 1.6 | | direct | 8 | 375 → 645 | 21.1 → 11.4 | 31.6 → 29.9 | 21.6 → 5.0 | | direct | 32 | 379 → 596 | 83.0 → 49.2 | 118.2 → 111.7 | 85.4 → 12.0 | | direct | 64 | 370 → 794 | 165.7 → 71.6 | 461.6 → 366.3 | 455.2 → 36.1 | On master, throughput is flat in concurrency and the loop stall grows with it. In every round, this PR had higher throughput and a lower loop stall than master at every level. The nightly includes #66489, so `direct` picks also insert into the tree (with a blocking `ray.get` on master). Because routing is now concurrent, a new prefix's first request can be routed before earlier inserts reach the tree: on the `handle` path the 8 prefixes split 5/3 across the 2 replicas in 2 of 5 runs with this PR and 4/4 in all runs on master; on the `direct` path, 4/4 in all runs for both. ### Tests ``` python -m pytest --noconftest --import-mode=importlib -q \ python/ray/llm/tests/serve/cpu/deployments/test_prefix_aware_request_router.py \ python/ray/llm/tests/serve/cpu/deployments/test_prefix_tree.py 68 passed ``` Run locally on macOS (`--noconftest` because the llm `conftest.py` imports vLLM). New tests: `TestNonBlockingTreeCalls` (3) and `TestPrefixTreePrefixMatchOrSmallestTenants` (4). All but `test_replica_removed_during_tree_lookup_is_not_chosen`, which guards a window master doesn't have, fail on master. No existing issue or PR does this (searched open PRs for `PrefixCacheAffinityRouter`, `prefix_aware_router`, `get_smallest_tenants`, "prefix tree actor ray.get"); #64577 fixes the same `ZeroDivisionError`. Written with AI assistance (Claude Code). 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Artur Niederfahrenhorst <[email protected]> Signed-off-by: Artur Niederfahrenhorst <[email protected]> Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]> Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
Problem
choose_replica(_reserve=False)picks a replica and returns without calling the request router'son_request_routedhook. Pick-only callers send the request themselves. For example, the Serve LLM ingress router returns the picked replica 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 noReplicaResulton this path, so the base class now typesresultasOptional[ReplicaResult]and documents when it isNone. Update theCapacityQueueRouterdocstring, which said that the hook runs only for the rejection protocol. The reserved path does not change.Add a unit test: a
_reserve=Falseselection callson_request_routedonce, with the request args andresult=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 inon_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, mirrorsllm_tests/kv_router_test) that reproduces this bug on a real cluster: 4 direct-streamingLLMServerreplicas routed byPrefixCacheAffinityRouter, asserting that unrelated prompts spread across every replica and repeated prompts pin to one. Both checks callchoose_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.PrefixCacheAffinityRouterinserts prompts into its prefix tree only inon_request_routed, so on this path the tree stays empty. No prompt matches, so every request falls back toget_smallest_tenants(). 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:
Additional information
PrefixCacheAffinityRouter.on_request_routedwaits for the tree actor withray.get. The reserved path already calls it. The pick-only path now calls it once per selection.frequency: manual, matchingllm_serve_kv_router; it has not been run on a real cluster from this environment.