Skip to content

[Serve][2/5] Dispatch router decisions and direct responses in HAProxy - #66507

Merged
eicherseiji merged 46 commits into
masterfrom
celina/router-app-2-haproxy-dispatch
Oct 21, 2026
Merged

eicherseiji merged 46 commits into
masterfrom
celina/router-app-2-haproxy-dispatch

Conversation

@celinaky

@celinaky celinaky commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Why this is needed

PR #66506 marks router applications and publishes that role to HAProxy. This PR implements the private HAProxy protocol that lets a router application choose a replica in another Serve application while preserving the direct model-to-client streaming path.

Summary

For a request whose longest-prefix match is a router application, HAProxy:

  1. Holds the original client request and sends a separate POST /internal/route control request to a router replica. The control request carries the original method, prefix-stripped path and query, selected headers including Authorization, request ID, session ID, and buffered body.
  2. Accepts either a routing decision or a router-owned response.
  3. Validates the selected application and full replica ID against its current target configuration.
  4. Rewrites the router prefix to the target application's route prefix.
  5. Pins the original request to the selected replica with forced persistence, so connection failure cannot redispatch it to a different replica.
  6. Streams the target replica's response directly to the client. The Lua response path is bypassed after a successful routing decision.

A routing decision has this private shape:

{"application": "llm-model-qwen", "replica_id": "SERVE_REPLICA::..."}

A router-owned response contains X-Serve-Router-Direct-Response: 1. HAProxy strips that private marker and hop-by-hop headers while preserving end-to-end headers, status, and body. Chunked router responses are decoded before forwarding or parsing. Unmarked non-2xx responses are returned as errors.

Decision parsing supports escaped JSON strings and rejects unknown applications, unknown replicas, malformed decisions, unavailable replicas, and router failures with a fail-closed 503. Ordinary applications and the existing ingress request router path retain their previous behavior.

Test plan

  • RAY_SERVE_ENABLE_HA_PROXY=1 python -m pytest -q python/ray/serve/tests/test_haproxy_router_application.py
  • Coverage includes POST and non-POST methods, query forwarding, route-prefix rewriting, escaped names, CORS preflight metadata, direct responses and headers, chunked responses, malformed decisions, unavailable replicas, router failures, and scale-to-zero router fallback.
  • Pinned Black 22.10.0 and pre-commit checks on changed files.

@celinaky
celinaky added this pull request to stack #66518 September 27, 2026 16:35
@celinaky celinaky changed the title [Serve][2/4] [Serve][2/4] Dispatch router application decisions in HAProxy Sep 29, 2026
@celinaky celinaky added the go add ONLY when ready to merge, run all tests label Sep 29, 2026
@celinaky celinaky changed the title [Serve][2/4] Dispatch router application decisions in HAProxy [Serve][2/4] Dispatch router decisions and direct responses in HAProxy Oct 1, 2026
@celinaky
celinaky force-pushed the celina/router-app-2-haproxy-dispatch branch from f478204 to 6becfba Compare October 1, 2026 22:42
celinaky and others added 18 commits October 4, 2026 23:10
Add an internal, application-wide role, `Application._as_router_application()`,
for applications whose ingress chooses which replica of which other
application serves a request. HAProxy will consume the role in a follow-up;
this change only carries it from the application to the target group.

The role marks the application's existing ingress. No router deployment is
added. It flows through BuiltApplication, DeploymentArgs and DeploymentInfo
(new `router_application` proto fields), ApplicationState, and the HTTP
TargetGroup (`is_router_application`). gRPC target groups never carry it.

The marker is read from the target state rather than running replicas, so a
router application scaled to zero keeps it. Otherwise HAProxy would stop
treating the application as a router and return its routing decisions to
clients as responses.

Validation:
- requires HAProxy;
- cannot be combined with `_with_ingress_request_router()`: both choose the
  replica for requests to the application;
- requires a route prefix, checked for `serve.run` in the client and for
  config deploys after route-prefix overrides.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Signed-off-by: Celina Yang <[email protected]>
…oups

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Signed-off-by: Celina Yang <[email protected]>
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Signed-off-by: Celina Yang <[email protected]>
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Signed-off-by: Celina Yang <[email protected]>
Signed-off-by: Celina Yang <[email protected]>
Signed-off-by: Celina Yang <[email protected]>
…HAProxy

When a request's longest-prefix match is a router application, HAProxy holds
it and sends a copy (method, path, query, body, content type, request ID,
session header) to one of the router's ingress replicas. A 200
{"application", "replica_id"} is validated against controller-provided
ingress targets; HAProxy then replaces the router's route prefix with the
target application's and pins the original request to that replica:

  /v1/chat/completions -> /v1/model-a/v1/chat/completions
  /v1/models           -> /v1/control/v1/models

Router non-2xx responses are returned to the client. Everything else that
does not select a live replica returns 503 with X-Serve-Reason:
router_unavailable, router_unreachable, router_timeout, malformed_decision,
unknown_application, unknown_replica_id, replica_unavailable. A routed
request never runs the target application's ingress request router, and a
stale decision is not retried through it. Host/port in the decision are
ignored. With the router scaled to zero, HAProxy asks the fallback proxy.

Direct requests to non-router applications are unchanged.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Signed-off-by: Celina Yang <[email protected]>
json.dumps renders non-ASCII as \uXXXX, which Lua 5.4 rejects, so an
application or deployment name with such characters made HAProxy fail to
load router_application.lua. Emit \ddd byte escapes instead, and cover it
with a haproxy -c test. Also clarify the tune.bufsize comment and drop an
unused test variable.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Signed-off-by: Celina Yang <[email protected]>
Signed-off-by: Celina Yang <[email protected]>
Signed-off-by: Celina Yang <[email protected]>
@celinaky
celinaky force-pushed the celina/router-app-2-haproxy-dispatch branch from 6becfba to 531a2b4 Compare October 5, 2026 00:19
celinaky and others added 4 commits October 5, 2026 17:00
Replace Application._as_router_application() with a private class
decorator. Being a router application depends on what the class returns,
so the marker lives on the class (like @serve.multiplexed) and build_app
reads it from the ingress. The wire format is unchanged.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Signed-off-by: Celina Yang <[email protected]>
Keep original method metadata scoped to router applications and combine overlapping HAProxy scenarios.

Signed-off-by: Seiji Eicher <[email protected]>
Dechunk marked direct responses and router errors inside reply_with while keeping routing decisions on the existing non-streaming JSON path.

Signed-off-by: Seiji Eicher <[email protected]>
@eicherseiji eicherseiji changed the title [Serve][2/4] Dispatch router decisions and direct responses in HAProxy [Serve][2/5] Dispatch router decisions and direct responses in HAProxy Oct 15, 2026
@eicherseiji eicherseiji changed the title [Serve][2/5] Dispatch router decisions and direct responses in HAProxy [Serve][2/4] Dispatch router decisions and direct responses in HAProxy Oct 15, 2026
@eicherseiji
eicherseiji removed this pull request from stack #66518 October 15, 2026 18:58
@eicherseiji
eicherseiji added this pull request to stack #67088 October 15, 2026 18:58
Signed-off-by: Seiji Eicher <[email protected]>

# Conflicts:
#	python/ray/serve/_private/build_app.py
#	python/ray/serve/tests/unit/test_application_state.py
…2-haproxy-dispatch

Signed-off-by: Seiji Eicher <[email protected]>

# Conflicts:
#	python/ray/serve/_private/haproxy.py
#	python/ray/serve/_private/haproxy_templates.py
#	python/ray/serve/_private/ingress_request_router.lua.tmpl
Comment thread python/ray/serve/_private/haproxy.py Outdated
continue
servers = sorted(backend.servers, key=lambda s: (s.host, s.port))
colocated = [s for s in servers if s.host == local_host]
pool = colocated or servers

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.

Consider this situation:

  • Node A runs HAProxy and router replica R1.
  • Node B runs router replica R2.
  • Both routers can select healthy model replicas.

HAProxy on A prefers local R1 and excludes R2 from its candidate list. If R1 crashes, requests through A return 503, even though R2 could handle them. This lasts until the controller updates HAProxy’s configuration. Router replica refers to a replica of the ingress deployment inside a router application.

Can we evaluate keeping remote router replicas as fallback candidates?

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.

Good catch. I’m keeping colocated replicas as the primary round-robin pool and will only try remote replicas after all local connection attempts fail. The first version flattened both sets, which could periodically select a remote replica first, so I’m correcting that before resolving this thread.

if not sock:connect(server.host, server.port) then
return nil, "router_unreachable"
end
local req = "POST /internal/route HTTP/1.0\r\n"

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.

There are some rough edges regarding route_prefix. Consider this example:

  1. You deploy the router with route_prefix="/llm".
  2. A client sends POST /llm/v1/chat/completions.
  3. HAProxy recognizes the router application and asks its ingress replica for a routing decision.
  4. That internal request goes to /internal/route.
  5. The replica expects requests under /llm, so it returns 404 before the router’s handler runs.

The control request should use /llm/internal/route; FastAPI then sees /internal/route after accounting for the application prefix. Let's add some tests with specified route_prefix.

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.

Fixed in 8587cfd. The control request now uses <route_prefix>/internal/route, while ingress request routers retain /internal/route. I also changed the real Serve E2E to deploy the router under /llm and verified requests reach POST /llm/internal/route.

Comment thread python/ray/serve/tests/test_haproxy.py Outdated
assert f"::{model}#Backend#" in body["replica_id"]
served[f"req-{i}"] = body["replica_id"]
# Round-robin over two replicas per model: all four replicas served.
assert len(set(served.values())) == 4

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.

handle.choose_replica(_reserve=False) uses the default power-of-two router, whose candidate order is randomized, not round-robin. Four requests per model can legitimately miss one replica, so correct dispatch fails the test.

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.

Fixed in 8587cfd. I removed the assertion that all four replicas must be selected. The test still verifies that every request reaches the exact replica returned by the router decision.

async def test_scaled_to_zero_router(with_fallback):
"""With no router replicas HAProxy asks the fallback proxy, else 503s."""
async with _router_cluster(
router_scaled_to_zero=True, router_fallback=with_fallback

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.

Could we exercise scale-from-zero with a real serve proxy? Here the fallback points straight at FakeRouter, so the test doesn't cover proxy route matching or waking a router deployment with no replicas.

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.

Agreed. The current test verifies the generated HAProxy behavior but bypasses the real Serve proxy. The scale-from-zero E2E in PR4 #67087 covers a target model application, not the router deployment itself. I’ll add real proxy coverage for waking a router application from zero before resolving this thread.

@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 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 8587cfd. Configure here.

Base automatically changed from celina/router-app-1-serve-role to master October 20, 2026 20:59
@eicherseiji eicherseiji changed the title [Serve][2/4] Dispatch router decisions and direct responses in HAProxy [Serve][2/5] Dispatch router decisions and direct responses in HAProxy Oct 20, 2026
Signed-off-by: Seiji Eicher <[email protected]>

# Conflicts:
#	python/ray/serve/api.py
@eicherseiji
eicherseiji merged commit 9625027 into master Oct 21, 2026
7 checks passed
@eicherseiji
eicherseiji deleted the celina/router-app-2-haproxy-dispatch branch October 21, 2026 18:35
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]>
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.

4 participants