Skip to content

[Serve][LLM][5/5] Preserve KV-aware application routing - #67218

Open
eicherseiji wants to merge 12 commits into
masterfrom
celina/router-app-6-kv-aware-control
Open

eicherseiji wants to merge 12 commits into
masterfrom
celina/router-app-6-kv-aware-control

Conversation

@eicherseiji

@eicherseiji eicherseiji commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Why this is needed

A shared router application runs each model's request router in its own process. KV-aware selection needs the tracker and prompt token IDs in that same process, and engine lifecycle events must return to the tracker that made the reservation. This change extends the existing LLMRouter integration to independently deployed model applications.

Summary

  • Share tokenizer startup, tracker registration, socket subscription, prompt token staging, and cleanup between LLMRouter and RouterApplication. Create KV state only for models configured with KVAwareRouter, and register the tracker before initializing the model handle.
  • Give each model one KV routing owner for the deployment. For a shared owner, the model builder skips the local LLMRouter and marks the application as a target of a separate router application. The shared router verifies the deployed model's ownership in the controller before starting its tracker. This lookup works at zero replicas.
  • Cache one lifecycle event forwarder per engine. The configured owner determines its destination, so the request needs no router application name header or Serve context field.
  • Preserve prompt token forwarding over HAProxy. Clear client-supplied router-owned headers before applying routing decisions, and preserve the trusted headers returned by the selected router.
  • Merge tokenizer environment variables when building the shared application. Reject conflicts and scope API keys per model.

For a model built with build_openai_app, set the shared owner's Serve application name in that model's LLM config:

deployment_config:
  request_router_config:
    request_router_class: ray.serve.llm.request_router.KVAwareRouter
    request_router_kwargs:
      kv_router_application_name: shared-router

The name must match the application deployed with build_openai_router_app. Omit the setting to use the model's own LLMRouter. To change ownership, drain traffic through the old router before redeploying the model and router configuration.

Validation

Local pytest runs used the matching compiled Ray wheel with editable Serve and LLM modules and --import-mode=importlib -q -rs.

  • 170 passed and 9 skipped across test_router.py::TestDirectStreamingLLMRouter, test_router_application.py, test_builder_openai_router_app.py, and the KV test_tokenizer.py, test_kv_aware_router.py, test_request_lifecycle_tracking.py, and test_kv_token_tracker.py suites. The skipped cases require dynamo.llm. The 63 builder and tokenizer cases were rerun against the final app build changes.
  • 41 passed in test_build_app.py and test_application_state.py with -k 'router or multiplex'.
  • 38 passed in test_haproxy_router_application.py, test_haproxy_api.py::test_ingress_request_router_forward_body_gate_renders, and test_haproxy.py::test_router_application_dispatches_across_applications.
  • Live smoke checks using serve.run and declarative deployment verified that the controller reports the configured owner, a second router is rejected, and the model remains at zero replicas.
  • test_openai_router_app_direct_streaming.py::test_shared_kv_router_releases_streaming_reservation verified that the configured shared KV router keeps a reservation while a stream is open and releases it after completion. The test runs real Serve and HAProxy with CPU doubles for generation and Dynamo. It passed its assertions in pytest and exited successfully when run standalone. The local pytest process still hit the native shutdown abort described below.
  • Pre-commit checks passed.

The HAProxy and live smoke checks exited successfully. The LLM and Serve build pytest processes reported the results above and then aborted during native shutdown in the local environment.

AI assistance was used for implementation and local validation.

@eicherseiji
eicherseiji added this pull request to stack #67088 October 20, 2026 22:09
eicherseiji added a commit that referenced this pull request Nov 3, 2026
## Why this is needed

Multi-model direct streaming deploys each model as an independent Serve
application. This PR adds a lightweight shared OpenAI router application
that maps the model ID in each request to one of those applications,
then asks the request router for the target application to select a
replica. HAProxy sends the original request directly to that replica,
preserving the direct streaming data path.

## Usage

```python
from ray.llm._internal.serve.core.ingress.builder import build_openai_router_app

build_openai_router_app(
    {
        "model_applications": {
            "qwen-0.5b": "llm-model-qwen",
            "llama-8b": "llm-model-llama",
        },
        "llm_configs": [
            {"model_loading_config": {"model_id": "qwen-0.5b"}},
            {"model_loading_config": {"model_id": "llama-8b"}},
        ],
    }
)
```

The builder is private, requires HAProxy and LLM direct streaming, and
accepts the same dictionary through declarative YAML. It requires
exactly one `LLMConfig` for every model-to-application mapping. Updating
this router does not replace or delete the independently deployed model
applications.

## Design

`RouterApplication` implements the private `POST /internal/route`
protocol introduced in #66507. It reads the model from JSON or form
data, resolves and caches the target application handle, and passes the
routing payload and session ID to the request router for that
application. The response contains the target application name and full
replica ID for HAProxy to validate and dispatch.

Native model routes are delegated without maintaining a duplicate
allowlist. The router itself owns only the global model endpoints: `GET`
and `HEAD /v1/models` and `/v1/models/{model}`. These endpoints do not
wake scale-to-zero model applications. They enforce each target model
API key policy, expose only authorized or public models, and return
vLLM-compatible errors. CORS preflight is handled before model
extraction.

Handle lookup runs in background tasks and retries transient Serve and
Ray failures. Lookup and replica selection remain bounded by the HAProxy
decision deadline. Client errors, unavailable applications, and
router-owned responses use the marked response path from #66507.

This layer uses a fast non-reserving pick and therefore requires an
available target replica. #67087 adds bounded reserving selection for
scale-to-zero targets, and #67218 preserves `KVAwareRouter` behavior in
the shared router process.

## Test plan

- `test_router_application.py` covers model parsing, authentication,
handle lookup, selection, session affinity, errors, and timeouts.
- `test_builder_openai_router_app.py` covers builder validation,
declarative arguments, and router-role propagation.
- `test_openai_router_app_direct_streaming.py` covers the end-to-end
multi-application path and native OpenAI routes.
- Pinned Black 22.10.0 and pre-commit checks on changed files.

Signed-off-by: Seiji Eicher <[email protected]>
Co-authored-by: Seiji Eicher <[email protected]>
@eicherseiji
eicherseiji force-pushed the celina/router-app-6-kv-aware-control branch from 6487ec8 to c7ecfe4 Compare November 3, 2026 18:04
@eicherseiji
eicherseiji force-pushed the celina/router-app-6-kv-aware-control branch from 4e28185 to f410f6c Compare November 9, 2026 23:26
Base automatically changed from celina/router-app-5-scale-to-zero-selection to master November 10, 2026 02:04
@eicherseiji eicherseiji added the go add ONLY when ready to merge, run all tests label Nov 10, 2026
@eicherseiji eicherseiji self-assigned this Nov 10, 2026
@eicherseiji
eicherseiji marked this pull request as ready for review November 11, 2026 00:23
@eicherseiji
eicherseiji requested review from a team as code owners November 11, 2026 00:23
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit b9be1e0. Configure here.

):
state = self._kv_states.get(model_id)
if state is not None and state.tracker is not None:
await state.tracker.on_replica_updates(source_writer_id, batch)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

KV events dropped before tracker starts

Medium Severity

RouterApplication becomes ready with tracker still unset, then on_model_lifecycle_events and on_model_replica_updates silently no-op until _resolve_handle finishes. Engine completions and peer reservations that arrive in that window never reach the new replica, so it starts routing with an empty load view and can overfill busy workers after router scale-out.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit b9be1e0. Configure here.

@ray-gardener ray-gardener Bot added the serve Ray Serve Related Issue label Nov 11, 2026
@jeffreywang88

Copy link
Copy Markdown
Contributor

Still in review -- need more time to complete the review (est. Tue / Wed).

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 serve Ray Serve Related Issue

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants