Skip to content

[Serve] Preserve ASGI lifespan state in request scopes - #66704

Closed
sxxaysq wants to merge 2 commits into
ray-project:masterfrom
sxxaysq:fix/serve-asgi-lifespan-state-45395
Closed

sxxaysq wants to merge 2 commits into
ray-project:masterfrom
sxxaysq:fix/serve-asgi-lifespan-state-45395

Conversation

@sxxaysq

@sxxaysq sxxaysq commented Oct 4, 2026

Copy link
Copy Markdown

Description

FastAPI applications and ASGI middleware that initialize resources in lifespan fail to retrieve those resources from requests in Ray Serve. Copy the replica's lifespan state into a fresh HTTP/WebSocket request namespace, retaining non-conflicting incoming state. This follows the ASGI lifespan state specification.

The new namespace is a shallow copy: stored resource objects remain shared, while request-level key replacement or insertion does not leak into later requests. Replica lifespan entries take precedence over same-named incoming fields. Startup and shutdown handling are unchanged.

Related issues

Fixes #45395.

Additional information

Four regressions cover HTTP/WebSocket requests with and without existing state. They exercise a real FastAPI lifespan, shared resources, per-request dictionary isolation, and state merging. The matching Ray nightly wheel was verified against source commit 43b706d733c590cf497cc322c57b9fd610bf214f before testing.

Baseline: all four added regressions fail, and a CPU Ray Serve deployment returns HTTP 500 because request.state.resource is missing. With the fix, the complete HTTP utility unit module passes 24 tests with RuntimeWarning treated as an error. The live deployment returns HTTP 200 on successive requests with calls=1, calls=2, and isolated=true.

The exact test module was copied outside the checkout to avoid unrelated cluster fixtures, and run against the matching wheel with only http_util.py patched. Validation commands:

python -m pytest "$TASK_ROOT/input/ray/test_http_util.py" -q --confcutdir="$TASK_ROOT/input/ray" -W error::RuntimeWarning
python "$TASK_ROOT/input/ray/ray_lifespan_smoke.py"
pre-commit run --files python/ray/serve/_private/http_util.py python/ray/serve/tests/unit/test_http_util.py
git diff --check

Ruff, import ordering, Black, and the complete repository-configured changed-file pre-commit run passed. This includes both Serve type checkers, docstyle, whole-tree import ordering and repository-link validation. No hook was bypassed; rules for unrelated file types skipped normally.

Duplicate checks found no open PR referencing #45395 or implementing lifespan-state propagation. Issue comments and the timeline were also checked.

AI assistance from OpenAI Codex was used to investigate, implement, and validate this change.

Resources initialized by FastAPI lifespan were absent from Ray Serve request
state, causing endpoints to fail after successful startup. Shallow-copy the
replica namespace into each HTTP/WebSocket scope, retaining non-conflicting
incoming state and preserving references to lifespan-owned resources.

Fixes ray-project#45395.

Test Plan:
The matching Ray nightly wheel at 43b706d
was checked against the source. Four regressions fail on the baseline; the
complete copied HTTP utility unit module passes 24 tests with the fix.
Real CPU Ray Serve requests return 500 on the baseline and 200 after the fix,
with resource sharing and request-local state isolation verified.

```bash
python -m pytest "$TASK_ROOT/input/ray/test_http_util.py" -q --confcutdir="$TASK_ROOT/input/ray" -W error::RuntimeWarning
python "$TASK_ROOT/input/ray/ray_lifespan_smoke.py"
pre-commit run --files python/ray/serve/_private/http_util.py python/ray/serve/tests/unit/test_http_util.py
git diff --check
```

AI assistance: OpenAI Codex. The submitter reviewed and approved the exact
diff and validation evidence before submission.

Co-authored-by: OpenAI Codex
Signed-off-by: sxxaysq <[email protected]>
…repair

The premerge corebuild/docgpubuild image jobs failed before Serve tests because
Astral re-published the torch 2.10 wheels under unchanged version names. This
branch inherits the old lock hashes. Upstream PR ray-project#66713 regenerated and verified
the hashes, and was merged as cd7636d.

Merge the current upstream master without manually changing hashes or disabling
verification. The ASGI feature diff remains exactly the same two files.

Test Plan:
Compare the feature patch before and after the merge; confirm the upstream
lock hashes match the CPU and CUDA artifacts reported in the failed jobs.
Run the repository commit hooks normally.

Co-authored-by: OpenAI Codex
Signed-off-by: sxxaysq <[email protected]>
@sxxaysq
sxxaysq marked this pull request as ready for review October 5, 2026 08:41
@sxxaysq
sxxaysq requested a review from a team as a code owner October 5, 2026 08:41

@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 updates the ASGI application wrapper to preserve middleware state and shallow-copy lifespan resources into the namespace of each HTTP and WebSocket request. It also adds a comprehensive unit test to verify this behavior. The feedback suggests using getattr to safely access _serve_asgi_lifespan and its state attribute to prevent potential AttributeError exceptions if the lifespan helper is not initialized.

Comment on lines +670 to +676
if scope["type"] in ("http", "websocket"):
# Preserve middleware state and shallow-copy this replica's
# lifespan resources into each request's namespace.
scope["state"] = {
**scope.get("state", {}),
**self._serve_asgi_lifespan.state,
}

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.

medium

To ensure robust and defensive programming, it is safer to access _serve_asgi_lifespan and its state attribute using getattr. This prevents potential AttributeError exceptions if the lifespan helper is not initialized (e.g., in certain testing or custom subclassing scenarios) or if the underlying third-party library (uvicorn) changes its internal implementation details in future versions.

        if scope["type"] in ("http", "websocket"):
            # Preserve middleware state and shallow-copy this replica's
            # lifespan resources into each request's namespace.
            lifespan = getattr(self, "_serve_asgi_lifespan", None)
            lifespan_state = getattr(lifespan, "state", {}) if lifespan else {}
            scope["state"] = {
                **scope.get("state", {}),
                **lifespan_state,
            }

@ray-gardener ray-gardener Bot added serve Ray Serve Related Issue community-contribution Contributed by the community labels Oct 5, 2026
@github-actions

Copy link
Copy Markdown

This pull request has been automatically marked as stale because it has not had
any activity for 14 days. It will be closed in another 14 days if no further activity occurs.
Thank you for your contributions.

You can always ask for help on our discussion forum or Ray's public slack channel.

If you'd like to keep this open, just leave any comment, and the stale label will be removed.

@github-actions github-actions Bot added the stale The issue is stale. It will be closed within 7 days unless there are further conversation label Oct 20, 2026
@github-actions

github-actions Bot commented Nov 3, 2026

Copy link
Copy Markdown

This pull request has been automatically closed because there has been no more activity in the 14 days
since being marked stale.

Please feel free to reopen or open a new pull request if you'd still like this to be addressed.

Again, you can always ask for help on our discussion forum or Ray's public slack channel.

Thanks again for your contribution!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

community-contribution Contributed by the community serve Ray Serve Related Issue stale The issue is stale. It will be closed within 7 days unless there are further conversation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Serve] FastAPI based deployment doesn't respect ASGI scope state.

1 participant