Repository navigation
[serve][llm] Parse direct-streaming routing payload for body-aware routers - #64328
Conversation
…uters Direct streaming forwarded the raw HTTP body to `choose_replica`, but `PrefixCacheAffinityRouter._extract_text_from_request` reads `.messages` / `.prompt` off the first positional routing arg (the parsed request the normal ingress forwards). The body-aware router therefore never received a parsable payload on the direct-streaming path: it raised `ValueError` out of `_fulfill_pending_requests` (every request hangs, ray-project#64326), and on current HEAD -- where the body rides in as a `request_body=` kwarg, leaving `pending_request.args` empty -- it silently degrades to load-balancing with prefix-cache affinity disabled and no signal. Normalize at the ingress boundary so the router contract stays singular. `LLMRouter.route()` now leniently parses the (possibly truncated) body into a lightweight `_RoutingPayload` exposing the same `.messages` / `.prompt` attributes, and passes it to `choose_replica` positionally so it lands where body-aware routers already look. When no routing key can be derived (empty, non-object, truncated, or unparseable body), nothing is forwarded, so the configured router sees empty args and falls back to its default load-balanced pick instead of failing the request. A once-per-replica warning surfaces the degradation. `PrefixCacheAffinityRouter` needs no changes. Fixes ray-project#64326 Signed-off-by: Seiji Eicher <[email protected]>
2530eb4 to
880f1f0
Compare
There was a problem hiding this comment.
Code Review
This pull request introduces a lightweight _RoutingPayload helper to leniently parse raw HTTP request bodies on the direct-streaming path, enabling body-aware routers like PrefixCacheAffinityRouter to extract routing keys (such as messages or prompt) without special-casing. If parsing fails due to truncation or invalid format, the router gracefully falls back to default load-balancing and logs a rate-limited warning. The feedback suggests refining this warning message to distinguish between actual body truncation and invalid JSON or missing fields, which improves clarity for users.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
- Make _warned_no_routing_key a class-level default so the route() guard is safe on instances built via __new__ (the 503 unit tests construct LLMRouter without running __init__, so the prior instance attribute raised AttributeError before reaching _pick_replica). - Treat empty messages/prompt as no routing key, so an empty body cannot reach PrefixCacheAffinityRouter and divide by len(input_text) == 0. - Reword the no-routing-key warning so it no longer states truncation as the cause when body_truncated is False. - Trim docstrings/comments and drop em-dash substitutes. Signed-off-by: Seiji Eicher <[email protected]>
ed1eb6d to
211e1cf
Compare
…mments _parse_routing_payload now returns a SimpleNamespace exposing only the non-empty messages or prompt field, dropping the bespoke _RoutingPayload class. Body-aware routers read it the same as a parsed request, so PrefixCacheAffinityRouter stays unchanged. Also rewrite the routing docstrings, comments, and the no-routing-key warning in terse style. No behavior change. Signed-off-by: Seiji Eicher <[email protected]>
Add a nightly release test that runs the direct-streaming ingress with PrefixCacheAffinityRouter across two replicas. Guards ray-project#64326, where a body-aware router got no routing key on the direct-streaming path. Reuses the existing serve LLM harness so the probe suite exercises the path end to end. Signed-off-by: Seiji Eicher <[email protected]>
Extract parse_routing_payload into ingress/routing_payload.py so router.py holds only the ingress logic, and restore the _pick_replica docstring paragraphs the parameter change did not affect. No behavior change. Signed-off-by: Seiji Eicher <[email protected]>
Expose the parsed body as a SimpleNamespace over all its fields, gated by a frozen tuple of routing-key fields (messages, prompt). Body-aware routers read their key off it by attribute, the same as the parsed request, so this handles any request type carrying a routing key and exposes every field to custom routers. Bodies without a key degrade to load-balancing. The parser stays in router.py and PrefixCacheAffinityRouter is unchanged. Signed-off-by: Seiji Eicher <[email protected]>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
Reviewed by Cursor Bugbot for commit ab271ca. Configure here.
| return None | ||
| if not any(data.get(field) for field in _ROUTING_KEY_FIELDS): | ||
| return None | ||
| return SimpleNamespace(**data) |
There was a problem hiding this comment.
Non-identifier JSON keys crash route
Medium Severity
_parse_routing_payload is meant to return None and fall back to load-balancing when parsing fails, but SimpleNamespace(**data) raises TypeError if the JSON object includes keys that are not valid Python identifiers (e.g. hyphenated vendor fields). That exception is not caught, so /internal/route can 500 even when messages or prompt is present—unlike the normal ingress, which typically accepts the same body via Pydantic.
Reviewed by Cursor Bugbot for commit ab271ca. Configure here.
kouroshHakha
left a comment
There was a problem hiding this comment.
sg. just one comment on release test.
| max_model_len: 8192 | ||
| tensor_parallel_size: 1 | ||
| # NOTE: This is used for perf testing as well, so cuda graph must be enabled. | ||
| enforce_eager: false |
There was a problem hiding this comment.
this line item 9 and 10 don't apply anymore?
There was a problem hiding this comment.
Ah good catch, will tack this onto a follow up
…uters (ray-project#64328) ## Why Serve LLM direct streaming breaks with a content-based router such as `PrefixCacheAffinityRouter`. The trigger is `RAY_SERVE_LLM_ENABLE_DIRECT_STREAMING=1` with `RAY_SERVE_ENABLE_HA_PROXY=1`. See ray-project#64326. The router reads `.messages` or `.prompt` off the first positional routing arg, where the OpenAI ingress puts the parsed request. Direct streaming forwards the raw body bytes to `choose_replica` instead, so the router gets no routing key. Requests either hang or silently fall back to load-balancing. Introduced by ray-project#63280. It routed direct streaming through `choose_replica` but passed the body as a `request_body=` kwarg rather than a parsable positional arg. ## What Normalize the body at the ingress so the router contract is the same on both paths. - Add `_parse_routing_payload(body)`. It `json.loads` the body and wraps it in a `SimpleNamespace` over every field, gated by a frozen tuple of routing-key fields (`messages`, `prompt`). It returns `None` for an empty, non-object, unparseable, or keyless body. - `route()` passes the namespace to `choose_replica` positionally, where body-aware routers already look. With no key, nothing is forwarded and the router load-balances. - Warn once per replica when no key is derived. `PrefixCacheAffinityRouter` is unchanged. ### Why a namespace over the whole body The router contract is that body-aware routers scan `pending_request.args` for an object exposing a routing field by attribute. The namespace mirrors that at `args[0]`, the same slot and access the normal ingress uses, so the direct path is indistinguishable from the normal path to any router, and custom routers that read request fields keep working unchanged. The discarded alternatives: - A plain dict fails attribute access, since `hasattr(some_dict, "messages")` is `False`, so every attribute-reading router would break. - A routing field on the request metadata would bypass routers that scan `args`. - Reconstructing the typed `ChatCompletionRequest` / `CompletionRequest` works only for the two endpoints we enumerate, and the body alone can't identify the type for the others (`messages` is shared by chat-completion, chat-embedding, and tokenize). The namespace carries every field, so it serves any request type that has a routing key and exposes the rest to custom routers, with no endpoint lookup and no per-type branching. Bodies without a key degrade to load-balancing. ## Tests `test_router.py` covers `_parse_routing_payload`, a contract test through the real `PrefixCacheAffinityRouter._extract_text_from_request`, and `route()` and `_pick_replica` forwarding plus the warn-once path. A release test runs the prefix-cache-aware router with direct streaming end to end. ## Related issue number Fixes ray-project#64326 Introduced by ray-project#63280 ## Checks - [x] I've signed off every commit (`-s`) - [x] I've run `scripts/format.sh` to lint the changes in this PR - [ ] Testing done by reviewers / CI --------- Signed-off-by: Seiji Eicher <[email protected]>
…uters (#64328) (#64488) Cherry-pick of #64328 into `releases/2.56.1`. ## Why Serve LLM direct streaming breaks with a content-based router such as `PrefixCacheAffinityRouter`. The trigger is `RAY_SERVE_LLM_ENABLE_DIRECT_STREAMING=1` with `RAY_SERVE_ENABLE_HA_PROXY=1`. See #64326. The router reads `.messages` or `.prompt` off the first positional routing arg, where the OpenAI ingress puts the parsed request. Direct streaming forwards the raw body bytes to `choose_replica` instead, so the router gets no routing key. Requests either hang or silently fall back to load-balancing. ## What Normalize the body at the ingress so the router contract is the same on both paths. - Add `_parse_routing_payload(body)`. It `json.loads` the body and wraps it in a `SimpleNamespace` over every field, gated by a frozen tuple of routing-key fields (`messages`, `prompt`). It returns `None` for an empty, non-object, unparseable, or keyless body. - `route()` passes the namespace to `choose_replica` positionally, where body-aware routers already look. With no key, nothing is forwarded and the router load-balances. - Warn once per replica when no key is derived. `PrefixCacheAffinityRouter` is unchanged. ## Related issue number Fixes #64326 Cherry-pick of #64328 Signed-off-by: Seiji Eicher <[email protected]>
…uters (ray-project#64328) ## Why Serve LLM direct streaming breaks with a content-based router such as `PrefixCacheAffinityRouter`. The trigger is `RAY_SERVE_LLM_ENABLE_DIRECT_STREAMING=1` with `RAY_SERVE_ENABLE_HA_PROXY=1`. See ray-project#64326. The router reads `.messages` or `.prompt` off the first positional routing arg, where the OpenAI ingress puts the parsed request. Direct streaming forwards the raw body bytes to `choose_replica` instead, so the router gets no routing key. Requests either hang or silently fall back to load-balancing. Introduced by ray-project#63280. It routed direct streaming through `choose_replica` but passed the body as a `request_body=` kwarg rather than a parsable positional arg. ## What Normalize the body at the ingress so the router contract is the same on both paths. - Add `_parse_routing_payload(body)`. It `json.loads` the body and wraps it in a `SimpleNamespace` over every field, gated by a frozen tuple of routing-key fields (`messages`, `prompt`). It returns `None` for an empty, non-object, unparseable, or keyless body. - `route()` passes the namespace to `choose_replica` positionally, where body-aware routers already look. With no key, nothing is forwarded and the router load-balances. - Warn once per replica when no key is derived. `PrefixCacheAffinityRouter` is unchanged. ### Why a namespace over the whole body The router contract is that body-aware routers scan `pending_request.args` for an object exposing a routing field by attribute. The namespace mirrors that at `args[0]`, the same slot and access the normal ingress uses, so the direct path is indistinguishable from the normal path to any router, and custom routers that read request fields keep working unchanged. The discarded alternatives: - A plain dict fails attribute access, since `hasattr(some_dict, "messages")` is `False`, so every attribute-reading router would break. - A routing field on the request metadata would bypass routers that scan `args`. - Reconstructing the typed `ChatCompletionRequest` / `CompletionRequest` works only for the two endpoints we enumerate, and the body alone can't identify the type for the others (`messages` is shared by chat-completion, chat-embedding, and tokenize). The namespace carries every field, so it serves any request type that has a routing key and exposes the rest to custom routers, with no endpoint lookup and no per-type branching. Bodies without a key degrade to load-balancing. ## Tests `test_router.py` covers `_parse_routing_payload`, a contract test through the real `PrefixCacheAffinityRouter._extract_text_from_request`, and `route()` and `_pick_replica` forwarding plus the warn-once path. A release test runs the prefix-cache-aware router with direct streaming end to end. ## Related issue number Fixes ray-project#64326 Introduced by ray-project#63280 ## Checks - [x] I've signed off every commit (`-s`) - [x] I've run `scripts/format.sh` to lint the changes in this PR - [ ] Testing done by reviewers / CI --------- Signed-off-by: Seiji Eicher <[email protected]> Signed-off-by: 400Ping <[email protected]>
## Why The current 256 KiB cap truncates the router copy of large LLM requests, causing body-aware routing to lose information. Several recent routing changes depend on this body: - [#64224](#64224), [#64328](#64328), and [#65095](#65095) use it for KV-aware routing. - [#65680](#65680) uses it for LoRA model selection. - [#66258](#66258) and [#66315](#66315) use it for deployment-aware, multi-model direct streaming. - [#63183](#63183) introduced the body-forwarding gate shared by these paths. This PR raises the default buffer to 8 MiB and lowers the default `maxconn` to 4,096. The sizing and behavior were verified with a real HAProxy 2.8.25 test and against the bundled HAProxy source code. Both settings retain their existing environment-variable overrides. | Consideration | Result | |---|---| | Request size | A one-million-token English request is commonly estimated at roughly 4 MB. The test request is 5.72 MiB, so 8 MiB leaves 2.28 MiB (~40%) headroom. | | Latency | Requests below 256 KiB do not wait longer. Requests from 256 KiB to 8 MiB now wait for the complete body before routing. | | Memory | Buffers are allocated dynamically. A live stream can use roughly 16 MiB across request and response buffers. Lowering `maxconn` from 20,000 to 4,096 reduces the theoretical buffer ceiling from 320 GiB to 64 GiB. | ## Changes - Raise `RAY_SERVE_HAPROXY_INGRESS_REQUEST_ROUTER_BUFSIZE` from 256 KiB to 8 MiB. - Lower `RAY_SERVE_HAPROXY_MAXCONN` from 20,000 to 4,096. - Test a 6,000,014-byte, million-token-sized request end to end. - Derive rendered-config assertions from their constants so environment overrides remain testable. - Update the KV-aware routing guide. ## Tests - Pre-commit hooks, Python compilation, Serve mypy, and Serve pyrefly passed. - HAProxy end-to-end test passed: 1 passed, 37 deselected in 2.85s using bundled HAProxy 2.8.25. This does not duplicate the related PRs: they introduce or consume body-aware routing, while this PR increases the shared buffer default and tests a million-token-sized body. AI assistance was used to implement and validate this change; the submitter reviewed every changed line. --------- Signed-off-by: Seiji Eicher <[email protected]> Signed-off-by: Seiji Eicher <[email protected]>
…t#66360) ## Why The current 256 KiB cap truncates the router copy of large LLM requests, causing body-aware routing to lose information. Several recent routing changes depend on this body: - [ray-project#64224](ray-project#64224), [ray-project#64328](ray-project#64328), and [ray-project#65095](ray-project#65095) use it for KV-aware routing. - [ray-project#65680](ray-project#65680) uses it for LoRA model selection. - [ray-project#66258](ray-project#66258) and [ray-project#66315](ray-project#66315) use it for deployment-aware, multi-model direct streaming. - [ray-project#63183](ray-project#63183) introduced the body-forwarding gate shared by these paths. This PR raises the default buffer to 8 MiB and lowers the default `maxconn` to 4,096. The sizing and behavior were verified with a real HAProxy 2.8.25 test and against the bundled HAProxy source code. Both settings retain their existing environment-variable overrides. | Consideration | Result | |---|---| | Request size | A one-million-token English request is commonly estimated at roughly 4 MB. The test request is 5.72 MiB, so 8 MiB leaves 2.28 MiB (~40%) headroom. | | Latency | Requests below 256 KiB do not wait longer. Requests from 256 KiB to 8 MiB now wait for the complete body before routing. | | Memory | Buffers are allocated dynamically. A live stream can use roughly 16 MiB across request and response buffers. Lowering `maxconn` from 20,000 to 4,096 reduces the theoretical buffer ceiling from 320 GiB to 64 GiB. | ## Changes - Raise `RAY_SERVE_HAPROXY_INGRESS_REQUEST_ROUTER_BUFSIZE` from 256 KiB to 8 MiB. - Lower `RAY_SERVE_HAPROXY_MAXCONN` from 20,000 to 4,096. - Test a 6,000,014-byte, million-token-sized request end to end. - Derive rendered-config assertions from their constants so environment overrides remain testable. - Update the KV-aware routing guide. ## Tests - Pre-commit hooks, Python compilation, Serve mypy, and Serve pyrefly passed. - HAProxy end-to-end test passed: 1 passed, 37 deselected in 2.85s using bundled HAProxy 2.8.25. This does not duplicate the related PRs: they introduce or consume body-aware routing, while this PR increases the shared buffer default and tests a million-token-sized body. AI assistance was used to implement and validate this change; the submitter reviewed every changed line. --------- Signed-off-by: Seiji Eicher <[email protected]> Signed-off-by: Seiji Eicher <[email protected]>
…t#66360) ## Why The current 256 KiB cap truncates the router copy of large LLM requests, causing body-aware routing to lose information. Several recent routing changes depend on this body: - [ray-project#64224](ray-project#64224), [ray-project#64328](ray-project#64328), and [ray-project#65095](ray-project#65095) use it for KV-aware routing. - [ray-project#65680](ray-project#65680) uses it for LoRA model selection. - [ray-project#66258](ray-project#66258) and [ray-project#66315](ray-project#66315) use it for deployment-aware, multi-model direct streaming. - [ray-project#63183](ray-project#63183) introduced the body-forwarding gate shared by these paths. This PR raises the default buffer to 8 MiB and lowers the default `maxconn` to 4,096. The sizing and behavior were verified with a real HAProxy 2.8.25 test and against the bundled HAProxy source code. Both settings retain their existing environment-variable overrides. | Consideration | Result | |---|---| | Request size | A one-million-token English request is commonly estimated at roughly 4 MB. The test request is 5.72 MiB, so 8 MiB leaves 2.28 MiB (~40%) headroom. | | Latency | Requests below 256 KiB do not wait longer. Requests from 256 KiB to 8 MiB now wait for the complete body before routing. | | Memory | Buffers are allocated dynamically. A live stream can use roughly 16 MiB across request and response buffers. Lowering `maxconn` from 20,000 to 4,096 reduces the theoretical buffer ceiling from 320 GiB to 64 GiB. | ## Changes - Raise `RAY_SERVE_HAPROXY_INGRESS_REQUEST_ROUTER_BUFSIZE` from 256 KiB to 8 MiB. - Lower `RAY_SERVE_HAPROXY_MAXCONN` from 20,000 to 4,096. - Test a 6,000,014-byte, million-token-sized request end to end. - Derive rendered-config assertions from their constants so environment overrides remain testable. - Update the KV-aware routing guide. ## Tests - Pre-commit hooks, Python compilation, Serve mypy, and Serve pyrefly passed. - HAProxy end-to-end test passed: 1 passed, 37 deselected in 2.85s using bundled HAProxy 2.8.25. This does not duplicate the related PRs: they introduce or consume body-aware routing, while this PR increases the shared buffer default and tests a million-token-sized body. AI assistance was used to implement and validate this change; the submitter reviewed every changed line. --------- Signed-off-by: Seiji Eicher <[email protected]> Signed-off-by: Seiji Eicher <[email protected]>


Why
Serve LLM direct streaming breaks with a content-based router such as
PrefixCacheAffinityRouter. The trigger isRAY_SERVE_LLM_ENABLE_DIRECT_STREAMING=1withRAY_SERVE_ENABLE_HA_PROXY=1. See #64326.The router reads
.messagesor.promptoff the first positional routing arg, where the OpenAI ingress puts the parsed request. Direct streaming forwards the raw body bytes tochoose_replicainstead, causing aValueError. Requests either hang or silently fall back to load-balancing.Introduced by #63280. It routed direct streaming through
choose_replicabut passed the body as arequest_body=kwarg rather than a parsable positional arg.What
Normalize the body at the ingress so the router contract is the same on both paths.
_parse_routing_payload(body). Itjson.loadsthe body and wraps it in aSimpleNamespaceover every field, gated by a frozen tuple of routing-key fields (messages,prompt). It returnsNonefor an empty, non-object, unparseable, or keyless body.route()passes the namespace tochoose_replicapositionally, where body-aware routers already look. With no key, nothing is forwarded and the router load-balances.PrefixCacheAffinityRouteris unchanged.Why a namespace over the whole body
The router contract is that body-aware routers scan
pending_request.argsfor an object exposing a routing field by attribute. The namespace mirrors that atargs[0], the same slot and access the normal ingress uses, so the direct path is indistinguishable from the normal path to any router, and custom routers that read request fields keep working unchanged.The discarded alternatives:
hasattr(some_dict, "messages")isFalse, so every attribute-reading router would break.args.ChatCompletionRequest/CompletionRequestworks only for the two endpoints we enumerate, and the body alone can't identify the type for the others (messagesis shared by chat-completion, chat-embedding, and tokenize). The namespace carries every field, so it serves any request type that has a routing key and exposes the rest to custom routers, with no endpoint lookup and no per-type branching. Bodies without a key degrade to load-balancing.Tests
test_router.pycovers_parse_routing_payload, a contract test through the realPrefixCacheAffinityRouter._extract_text_from_request, androute()and_pick_replicaforwarding plus the warn-once path. A release test runs the prefix-cache-aware router with direct streaming end to end.Related issue number
Fixes #64326
Introduced by #63280
Checks
-s)scripts/format.shto lint the changes in this PR