Skip to content

[serve] Make root_path independent of the uvicorn version - #66443

Closed
jeffreywang88 wants to merge 4 commits into
masterfrom
serve-root-path-uvicorn
Closed

jeffreywang88 wants to merge 4 commits into
masterfrom
serve-root-path-uvicorn

Conversation

@jeffreywang88

@jeffreywang88 jeffreywang88 commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Description

Previously, Serve passed root_path to uvicorn. uvicorn <0.26 and >=0.26 construct ASGI paths differently, causing client-visible URLs to flip after an upgrade. This change normalizes the ASGI scope inside Serve instead. Check out uvicorn's release notes for more details: https://github.com/Kludex/uvicorn/blob/main/docs/release-notes.md#0260-january-16-2024.

This PR preserves both URL forms that clients may already use, keeps KubeRay probes working, and handles overlapping prefixes by preferring the canonical route before retrying the proxy-stripped interpretation.

Difference in uvicorn behavior

With root_path="/serve", Uvicorn changed whether it adds that prefix to the ASGI path:

Request sent to Uvicorn Uvicorn <0.26 scope["path"] Uvicorn ≥0.26 scope["path"]
/hello /hello /serve/hello
/serve/hello /serve/hello /serve/serve/hello

scope["root_path"] is /serve in both versions. Uvicorn ≥0.26 also prepends the prefix to raw_path; older Uvicorn leaves raw_path as received. See the 0.22 implementation and 0.26 implementation.

Ray Serve derives its route by removing root_path from the start of path. Consequently, /serve/hello reaches route /hello with old Uvicorn, while /hello reaches route /hello with newer Uvicorn. That is why upgrading Uvicorn flips which client URL works.

This PR's behavior

Assume:

serve.start(http_options={"root_path": "/serve"})
serve.run(hello.bind(), route_prefix="/hello")
Client path Master, Uvicorn <0.26 Master, Uvicorn >=0.26 This PR, either version
/serve/hello works 404 works
/hello 404 works works
/serve/-/healthz works 404 works
/-/healthz 404 works works
/serve/-/routes works 404 works
/-/routes 404 works works

The PR does not redirect client requests. It normalizes ASGI path, raw_path, and root_path internally so routing sees one stable representation.

Approach

The PR solves the version difference by leaving root_path unset in uvicorn and applying it in Serve’s ASGI wrapper (_apply_root_path). Both uvicorn versions then pass through the request path as received.

Related issues

Additional information

Optional: Add implementation details, API changes, usage examples, screenshots, etc.

@jeffreywang88 jeffreywang88 added the go add ONLY when ready to merge, run all tests label Sep 24, 2026
@jeffreywang88
jeffreywang88 force-pushed the serve-root-path-uvicorn branch from 0dadc76 to a872664 Compare September 24, 2026 06:18
if not is_direct_ingress:
path = scope["path"]
if path == root_path or path.startswith(root_path + "/"):
scope[ROOT_PATH_PREFIXED_SCOPE_KEY] = True

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.

ROOT_PATH_PREFIXED_SCOPE_KEY remembers whether the incoming URL already started with root_path, before Serve changes the path here.

For example, with root_path="/api", both /v1 and /api/v1 become /api/v1 after normalization. The marker remembers which URL actually arrived.

For an incoming /api/v1, Serve first treats /api as the root and looks for route /v1. If that fails, the marker lets it try /api/v1 as the application route instead. That retry is only valid when /api was in the incoming URL, not when Serve added it.

@jeffreywang88
jeffreywang88 marked this pull request as ready for review September 25, 2026 20:00
@jeffreywang88
jeffreywang88 requested a review from a team as a code owner September 25, 2026 20:00

@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 introduces changes to correctly apply and preserve root_path across ASGI scopes independently of the uvicorn version, particularly for direct ingress replica routing. It adds a new _apply_root_path middleware, updates proxy routing logic to handle unprefixed route paths, and includes corresponding unit and integration tests. The review feedback highlights several missing imports in the newly added tests (HTTPOptions, DeploymentID, httpx, and ServeInstanceDetails) that would cause runtime NameErrors, and suggests using utf-8 instead of ascii encoding for the root_path to prevent potential UnicodeEncodeErrors.

)
from ray.serve._private.proxy_request_response import ResponseStatus
from ray.serve._private.replica import Replica
from ray.serve.config import ProxyLocation, gRPCOptions

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.

high

The newly added test test_direct_ingress_root_path_health_endpoints uses HTTPOptions, but it is not imported from ray.serve.config. Please add HTTPOptions to the import statement to avoid a NameError during test execution.

Suggested change
from ray.serve.config import ProxyLocation, gRPCOptions
from ray.serve.config import HTTPOptions, ProxyLocation, gRPCOptions

send_http_response_on_exception,
)
from ray.serve._private.proxy_request_response import ResponseStatus
from ray.serve._private.replica import Replica

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.

high

The newly added test test_direct_ingress_root_path_health_endpoints uses DeploymentID, but it is not imported in this file. Please import DeploymentID from ray.serve._private.common to prevent a NameError when running the tests.

Suggested change
from ray.serve._private.replica import Replica
from ray.serve._private.common import DeploymentID
from ray.serve._private.replica import Replica

Comment on lines +500 to +502
def test_root_path_direct_ingress(ray_shutdown):
"""Check replica routing with a nonempty root_path."""
ray.init(num_cpus=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.

high

The test test_root_path_direct_ingress uses httpx and ServeInstanceDetails, but they might not be imported in this test file. To ensure the test runs reliably and avoid potential NameErrors, please import them inside the test function.

Suggested change
def test_root_path_direct_ingress(ray_shutdown):
"""Check replica routing with a nonempty root_path."""
ray.init(num_cpus=4)
def test_root_path_direct_ingress(ray_shutdown):
"""Check replica routing with a nonempty root_path."""
import httpx
from ray.serve.schema import ServeInstanceDetails
ray.init(num_cpus=4)

return app


def _apply_root_path(

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.

We leave uvicorn's root_path unset and let this function decide the ASGI path.

For direct ingress, HAProxy has already stripped the configured root prefix before forwarding the request. The replica matches its deployment route prefix against that forwarded path, so we set the ASGI root_path but leave path and raw_path unchanged.

Comment on lines +310 to +312
resp = httpx.get(f"http://127.0.0.1:{port}{prefix}/-/healthz")
assert resp.status_code == 200
assert resp.text == "success"

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 assertion is specifically for avoiding this issue kuberay-project/kuberay#4494 (comment).

jeffreywang88 and others added 4 commits September 25, 2026 13:56
uvicorn>=0.26 prepends its `root_path` to every request path, assuming a
reverse proxy already stripped it. Serve passed `http_options.root_path`
to uvicorn, so its behavior depended on the installed uvicorn version:

- uvicorn<0.26 (Ray images pin 0.22): apps and "/-/healthz" are only
  served under the prefix, so KubeRay's "/-/healthz" probes fail
  (kuberay#4494).
- uvicorn>=0.26 (e.g., `pip install ray[serve]`): apps are only served
  without the prefix, so the URLs Serve advertises return 404 (#55776).

Apply root_path to the ASGI scope in Serve instead of passing it to
uvicorn. The proxy serves requests both with and without the prefix,
normalizing the scope to the form uvicorn>=0.26 produces, so apps see the
same root_path either way. If a prefixed request only matches a route
when read without the prefix (e.g., root_path "/api" and route_prefix
"/api/v1" behind a reverse proxy that strips "/api"), route it that way.

Replica direct ingress only sets root_path on the scope, which matches
uvicorn<0.26. This also fixes it under uvicorn>=0.26, where HAProxy
forwards already-stripped paths.

This unblocks upgrading uvicorn past 0.31.1 (required by vLLM 0.30 via
mcp>=2) without breaking root_path users or KubeRay.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Jeffrey Wang <[email protected]>
Signed-off-by: Jeffrey Wang <[email protected]>
@jeffreywang88
jeffreywang88 force-pushed the serve-root-path-uvicorn branch from 0e79930 to 36d211f Compare September 25, 2026 20:57
@ray-gardener ray-gardener Bot added the serve Ray Serve Related Issue label Sep 26, 2026
@jeffreywang88

Copy link
Copy Markdown
Contributor Author

Chatted offline with @abrarsheikh -- we should respect the ASGI protocol. Ray serve's current behavior depends on uvicorn 0.22 which has the incorrect implementation. 0.26 fixes it. I'll fold ray serve changes into #66446 as they need to be merged together with the uvicorn version upgrade. Closing this PR.

@jeffreywang88
jeffreywang88 removed this pull request from stack #66447 September 29, 2026 06:12
jeffreywang88 added a commit that referenced this pull request Sep 30, 2026
#66446)

## Description

Ray images pin `uvicorn` 0.22, which doesn't follow the ASGI spec for
`root_path`, so `http_options.root_path` behaves differently depending
on the installed uvicorn (#55776), and it breaks direct ingress and
HAProxy. This PR upgrades uvicorn to 0.53 (with a `>=0.26` floor) and
makes every ingress mode follow ASGI. Transitively, we also raise
`watchfiles` to `>=0.20` as required by newer `uvicorn` installs.

### How each ingress mode handles `root_path`

Example: `root_path="/serve"` and `route_prefix="/hello"`. A proxy in
front of Serve strips `/serve`, so Serve receives `/hello/items/1`. In
every mode, the app should see:

```
path      = /serve/hello/items/1
root_path = /serve/hello
```

- **HTTP proxy:** uvicorn adds `/serve` to the path. The proxy matches
`/hello` after `root_path`, then sets `root_path=/serve/hello`. This was
already correct with uvicorn 0.26+.
- **Direct ingress:** the replica's uvicorn adds `/serve`. The replica
now matches `/hello` after `root_path` and sets
`root_path=/serve/hello`.
- **Problem**: Prior to this PR, it matched against the full path, so
every request got a 404.
- **HAProxy:** forwards `/hello/items/1` unchanged to a replica, which
then works like direct ingress.
- **Problem**: Prior to this PR, it also stripped `/serve` whenever the
path started with it, which removed the prefix a second time.

### `/-/healthz` and `/-/routes`

These are Serve's own endpoints, not part of ASGI.
- `/-/healthz` reports whether the ingress is ready. KubeRay probes,
load balancers and HAProxy's replica checks call it.
- `/-/routes` returns the route table, like `{"/hello": "default"}`.

Serve must match them **after** removing `root_path`. Direct ingress
didn't, so `/-/healthz` returned 404. HAProxy then marked every replica
down, and traffic silently fell back to the proxy actor.

## Breaking changes

Requests that still include the prefix, like `/serve/hello` or
`/serve/-/healthz`, now return 404. Users must strip the prefix at their
ingress or unset `root_path`.

### Impact on KubeRay: None
kuberay-project/kuberay#4494 happened because
Serve only answered health checks at `<root_path>/-/healthz`. That was
true on uvicorn 0.22 images, and again after #57555, which forced the
0.22 behavior onto uvicorn 0.41. KubeRay's worker readiness probe and
head-pod check always call `/-/healthz` on port 8000, so the pods never
became ready.

This PR doesn't cause the same issue. Following ASGI, Serve now expects
requests without `root_path`, so `/-/healthz` returns 200 when
`root_path` is set, in all three modes.
[test_http_root_path](https://github.com/ray-project/ray/pull/66446/changes#diff-2351bd6cf47275a74cc504b065e417ee6c550affc762df3d90e2e7f2ecb277f2R311)
checks exactly this. Therefore, KubeRay needs no changes.


## Related issues
Closes #55776. Supersedes #66443.

## 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
ray-project#66446)

## Description

Ray images pin `uvicorn` 0.22, which doesn't follow the ASGI spec for
`root_path`, so `http_options.root_path` behaves differently depending
on the installed uvicorn (ray-project#55776), and it breaks direct ingress and
HAProxy. This PR upgrades uvicorn to 0.53 (with a `>=0.26` floor) and
makes every ingress mode follow ASGI. Transitively, we also raise
`watchfiles` to `>=0.20` as required by newer `uvicorn` installs.

### How each ingress mode handles `root_path`

Example: `root_path="/serve"` and `route_prefix="/hello"`. A proxy in
front of Serve strips `/serve`, so Serve receives `/hello/items/1`. In
every mode, the app should see:

```
path      = /serve/hello/items/1
root_path = /serve/hello
```

- **HTTP proxy:** uvicorn adds `/serve` to the path. The proxy matches
`/hello` after `root_path`, then sets `root_path=/serve/hello`. This was
already correct with uvicorn 0.26+.
- **Direct ingress:** the replica's uvicorn adds `/serve`. The replica
now matches `/hello` after `root_path` and sets
`root_path=/serve/hello`.
- **Problem**: Prior to this PR, it matched against the full path, so
every request got a 404.
- **HAProxy:** forwards `/hello/items/1` unchanged to a replica, which
then works like direct ingress.
- **Problem**: Prior to this PR, it also stripped `/serve` whenever the
path started with it, which removed the prefix a second time.

### `/-/healthz` and `/-/routes`

These are Serve's own endpoints, not part of ASGI.
- `/-/healthz` reports whether the ingress is ready. KubeRay probes,
load balancers and HAProxy's replica checks call it.
- `/-/routes` returns the route table, like `{"/hello": "default"}`.

Serve must match them **after** removing `root_path`. Direct ingress
didn't, so `/-/healthz` returned 404. HAProxy then marked every replica
down, and traffic silently fell back to the proxy actor.

## Breaking changes

Requests that still include the prefix, like `/serve/hello` or
`/serve/-/healthz`, now return 404. Users must strip the prefix at their
ingress or unset `root_path`.

### Impact on KubeRay: None
kuberay-project/kuberay#4494 happened because
Serve only answered health checks at `<root_path>/-/healthz`. That was
true on uvicorn 0.22 images, and again after ray-project#57555, which forced the
0.22 behavior onto uvicorn 0.41. KubeRay's worker readiness probe and
head-pod check always call `/-/healthz` on port 8000, so the pods never
became ready.

This PR doesn't cause the same issue. Following ASGI, Serve now expects
requests without `root_path`, so `/-/healthz` returns 200 when
`root_path` is set, in all three modes.
[test_http_root_path](https://github.com/ray-project/ray/pull/66446/changes#diff-2351bd6cf47275a74cc504b065e417ee6c550affc762df3d90e2e7f2ecb277f2R311)
checks exactly this. Therefore, KubeRay needs no changes.


## Related issues
Closes ray-project#55776. Supersedes ray-project#66443.

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

---------

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant