Skip to content

[serve] Copy the ASGI lifespan state into each request scope - #67844

Merged
abrarsheikh merged 3 commits into
ray-project:masterfrom
miggle711:fix/serve-asgi-lifespan-state
Nov 10, 2026
Merged

abrarsheikh merged 3 commits into
ray-project:masterfrom
miggle711:fix/serve-asgi-lifespan-state

Conversation

@miggle711

@miggle711 miggle711 commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Description

A FastAPI app or ASGI middleware that stores resources in its lifespan state can't read them from a request in Ray Serve. Under plain FastAPI plus uvicorn, each request's scope["state"] holds a shallow copy of the lifespan state, as the ASGI lifespan state spec describes. In Serve, the replica runs the lifespan (ASGIAppReplicaWrapper uses uvicorn's LifespanOn), but ASGIAppReplicaWrapper.__call__ forwards the request scope from the proxy unchanged. The proxy runs uvicorn with the lifespan off, so the scope it sends has no lifespan state. The result:

KeyError: 'my.producer'      # middleware reading scope["state"]
AttributeError: 'State' object has no attribute 'greeting'   # request.state.greeting

For http and websocket scopes, __call__ now sets scope["state"] to a shallow copy of the replica's lifespan state, with any state already on the scope merged over it. The scope's own values win on a conflict, as under uvicorn, where per-request values override the lifespan's. The stored objects stay shared across requests, but each request gets its own dict, so changing one request's state doesn't leak into the lifespan state or other requests.

Related issues

Fixes #45395

Additional information

Prior work: #66704 made the same change (it was auto-closed as stale without a human review). This PR follows its approach, without the getattr guard Gemini suggested there: _set_asgi_app sets _asgi_app and _serve_asgi_lifespan together, and __call__ can't run without _asgi_app.

Not a duplicate: no open PR references #45395 or changes ASGIAppReplicaWrapper.__call__. The issue has no assignee, and johntaylor-cell confirmed on the issue that it's mine to take.

Decisions (asked on the issue):

  1. If the incoming scope and the lifespan define the same key, the scope's value wins. This is the opposite of [Serve] Preserve ASGI lifespan state in request scopes #66704, per a suggestion on this PR: the incoming state only holds what proxy-side middleware set for this request, and under uvicorn per-request values override lifespan ones.
  2. WebSocket scopes get the same treatment as HTTP, as in uvicorn.

Tests:

  • test_asgi_app_wrapper_copies_lifespan_state_into_request in python/ray/serve/tests/unit/test_http_util.py, parametrized over http and websocket. It checks precedence, that other entries are kept, and that the request's dict is a copy.
  • test_fastapi_lifespan_state_in_request in python/ray/serve/tests/test_fastapi.py: a FastAPI lifespan yields {"greeting": "hello"} and a route returns request.state.greeting.

Commands and results (Ray 2.59.0 wheel, macOS, Python 3.12, fastapi 0.162.0, starlette 1.10.0, uvicorn 0.54.0, pytest==7.4.4 and pytest-asyncio==0.17.2 as pinned in test-requirements.txt):

python -m pytest test_http_util.py -q
22 passed        # 20 existing + 2 new (http, websocket)

Without the change, both new unit cases fail because the request scope has no lifespan entries. They also fail if the lifespan's value wins over the scope's.

Master's Serve code needs newer core code than the 2.59 wheel has, so I ran the end-to-end checks against the wheel with the same five lines applied to its http_util.py (the wheel's __call__ is identical to master's):

  • The issue's reproduction (middleware storing a producer in the lifespan state) now returns HTTP 200 with the right body, with "producer created", "producer sending message" and "producer flushed" in the replica logs, matching the plain uvicorn output in the issue. Before the change it raised KeyError: 'my.producer' and the client saw a broken connection.
  • The body of test_fastapi_lifespan_state_in_request, run as a script, returns hello. Without the change the replica raises AttributeError: 'State' object has no attribute 'greeting'.

pre-commit run --files on the three changed files passes (black, ruff, pydoclint, mypy and pyrefly for Serve, and the rest).

AI assistance (Claude Code) was used for this change.

@miggle711
miggle711 requested a review from a team as a code owner November 4, 2026 23:48

@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 in Ray Serve to copy the lifespan state into the request scope for HTTP and WebSocket connections, ensuring that state set during startup is accessible within requests. It also includes comprehensive integration and unit tests to verify this behavior. The review feedback points out a potential TypeError if the request scope's state is explicitly set to None, suggesting a more robust fallback mechanism using scope.get("state") or {}.

Comment on lines +673 to +676
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

Using scope.get("state", {}) can raise a TypeError if scope["state"] is explicitly set to None by a proxy or middleware, as .get() will return None instead of the default {}. Using scope.get("state") or {} is more robust and prevents potential unpacking errors.

Suggested change
scope["state"] = {
**scope.get("state", {}),
**self._serve_asgi_lifespan.state,
}
scope["state"] = {
**(scope.get("state") or {}),
**self._serve_asgi_lifespan.state,
}

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.

I won't be changing this. The ASGI spec defines state as a dict or an absent key, uvicorn always sends a dict copy, and nothing in Serve sets it on a request scope, so None can't reach this point. Starlette's Request.state would also fail on a None state before this code mattered. scope.get("state", {}) covers the real cases.

@ray-gardener ray-gardener Bot added serve Ray Serve Related Issue community-contribution Contributed by the community labels Nov 5, 2026
@johntaylor-cell johntaylor-cell added the go add ONLY when ready to merge, run all tests label Nov 5, 2026
@johntaylor-cell

Copy link
Copy Markdown
Contributor

On your Q1 from #45395: I’d let the incoming state win, {**self._serve_asgi_lifespan.state, **scope.get("state", {})}. The incoming dict only holds what proxy-side middleware set for this request, and under uvicorn per-request values override lifespan ones. The unit test’s precedence assertion would flip accordingly.

@miggle711

Copy link
Copy Markdown
Contributor Author

On your Q1 from #45395: I’d let the incoming state win, {**self._serve_asgi_lifespan.state, **scope.get("state", {})}. The incoming dict only holds what proxy-side middleware set for this request, and under uvicorn per-request values override lifespan ones. The unit test’s precedence assertion would flip accordingly.

Heya @johntaylor-cell, thanks for the suggestion. In bb88e5e I changed which value wins when a key is in both the lifespan state and the request's own state. The request's value now wins, with the lifespan state as the base, as under uvicorn. The unit test also now checks entries that exist only in the lifespan, so it fails without the copy. And I updated the PR description to match.

@abrarsheikh

Copy link
Copy Markdown
Contributor

lg2m, please write a e2e test for what the PR fixes.

@Jadiouo Jadiouo 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.

Thanks @miggle711, this looks good to me.

I checked bb88e5e against a Ray nightly (4f54411) with only http_util.py swapped, since master's Serve needs a newer core than the wheel (__call__ is the same as on master).

With a real Serve deployment using @serve.ingress(FastAPI(lifespan=...)) that yields {"db": ..., "counter": ...}:

  • Before: reading request.state.db returns 500 (AttributeError), and a pure-ASGI middleware reading scope["state"]["producer"] hits KeyError.
  • After: 200. request.state.db is the lifespan's object, a mutable counter in the state is shared across requests (1, 2, 3), and request.state.x set in one request doesn't show up in the next. A plain Starlette app and a lifespan that yields nothing also work. This matches the same apps run directly under uvicorn.

Tests: the two new unit cases fail on base and pass with the PR (22 passed), and test_fastapi_lifespan_state_in_request fails on base and passes with the PR.

Declining the or {} suggestion makes sense to me, since the ASGI spec doesn't allow state to be None. Approving.

@johntaylor-cell johntaylor-cell 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.

lg2m

@miggle711

Copy link
Copy Markdown
Contributor Author

Thanks @abrarsheikh. The PR includes an end-to-end test: test_fastapi_lifespan_state_in_request in python/ray/serve/tests/test_fastapi.py deploys a FastAPI app through serve.run whose lifespan yields state, and a route reads it with request.state. It fails on master and passes here (@Jadiouo confirmed that too). If you'd like a different scenario covered, such as the middleware from the issue or a WebSocket route, tell me and I'll add it.

@abrarsheikh
abrarsheikh merged commit 80ceee0 into ray-project:master Nov 10, 2026
6 checks passed
eugenepaniot added a commit to eugenepaniot/ray that referenced this pull request Nov 19, 2026
…floop-input

* upstream/master:
  [Data][3/n] update progress bar on lineage reconstruction (ray-project#67366)
  [Data] Enable the Top-N rewrite by default and expose it on DataContext (ray-project#68329)
  [Data] Adaptively skip map-side partial aggregation for high-cardinality keys (ray-project#68118)
  [Core] Spawn specific servers without preexec_fn to fix intermittent startup crashes (ray-project#67947)
  [Serve] Stop the __wrapped__ walk at non-callables (ray-project#67117)
  [Data] Deflake test_read_parquet_v2 by cutting redundant Ray Data executions (ray-project#68318)
  [Data] Retry FooterReader actor deaths with Ray Core and yield footers in listing order (ray-project#67988)
  [Data] Fix order-dependent schema unification when a list<null> arm is present (ray-project#68259)
  [Serve] Make @serve.batch work when wrapped in another decorator (ray-project#68177)
  [serve] Deflake test_metrics_3 - record the batch queue length once a batch is taken (ray-project#68302)
  [serve] Drop completed requests from the multiplexed model ID index (ray-project#68085)
  [Data] Fix flaky test_hudi: read each table once instead of sorting in Ray Data, keep size small (ray-project#68162)
  [Data] Fix flaky test_context: start 2 Ray clusters instead of 5 and keep size small (ray-project#68161)
  [Data] Fix flaky test_kafka: use recent timestamps in test_read_kafka_datetime_partial_range (ray-project#68248)
  [Data] Iceberg DSv2 [2/5]: The listing-to-reading manifest for Iceberg (ray-project#67951)
  [Train] Report training errors when the post-mortem debugger raises a BaseException (ray-project#68317)
  [RLlib] Skip the PPOConfig docstring example that crashes the rllib doctest target (ray-project#68306)
  [Train] Support post-mortem debugging for training function errors (ray-project#68296)
  [train][1/n] Give each health probe its own timeout (ray-project#68191)
  [Data] Fix unifying a fixed-shape tensor array with a lower-ndim variable-shaped one (ray-project#67266)
  [Train] Add a guide to debugging failures and hangs (ray-project#68299)
  [Data] Persist BlockMetadata.num_rows and batch ray.get in _calculate_blocks_rows (ray-project#67662)
  [Data] Vectorize LeRobot delta segment preparation and validate index contiguity (ray-project#67845)
  [Data] Avoid full-DataFrame apply in _AbstractKBinsDiscretizer._transform_pandas (ray-project#67862)
  [doc] Refresh intersphinx inventory snapshots (ray-project#68303)
  [Data] Fix SimpleImputer on categorical columns in append mode and with existing category values (ray-project#67467)
  [Data] Replace O(N) list.pop(0) with deque.popleft() in PushBasedShuffleTaskScheduler (ray-project#67243)
  [Train] Reject an elastic ScalingConfig with max_workers=0 (ray-project#68218)
  [core][move semantics][3/n]Populate task args with is_move for movable refs (ray-project#66803)
  [core][sandbox] Remove the readonly option (ray-project#68088)
  [Data](1/n) Implement the line-chunk reader for CSV and JSONL on DataSource V2 (ray-project#67907)
  [Data] Set MIMALLOC_PURGE_DELAY=0 on random_shuffle to fix the pyarrow 25 OOM regression (ray-project#68151)
  [core] Quote each `uv run` argument in the uv runtime env hook (ray-project#68156)
  [core] Don't let gRPC cancel calls that wait over 30s in the server queue (ray-project#68210)
  [Data] Fix shuffle and join on native tensor columns with pyarrow 25+ (ray-project#68072)
  [serve][llm] Remove decode load progress (ray-project#68258)
  [ci] Bump sglang to 0.5.23 in release tests (ray-project#68250)
  [Core] Build the test auth token file locally so Windows tests can read it (ray-project#68262)
  [image] Bump EFA installer to 1.51.0 in CPU base-extra images (ray-project#67730)
  [serve] Observe the result of rank reassignment reconfigures (ray-project#67923)
  [Serve][Docs] Explain imperative vs declarative deploys and in-place updates from Python (ray-project#68243)
  [Data] (Fault tolerance) Ray Data lineage reconstruction docs (ray-project#68061)
  [RLlib] Add a multi-node footsies APPO memory release test (ray-project#67595)
  [Train] Remove local mode (ray-project#68239)
  [Data] Fix filtered Lance row-count metadata (ray-project#67228)
  [Serve][2/2] Propagate TracingConfig to proxies at startup (ray-project#65437)
  [Data] Fix synthesized path filtering in DataSourceV2 (ray-project#67079)
  [RLlib] Run the BCConfig Tune example one trial at a time to unblock the rllib doctest target (ray-project#68242)
  [Data][Delta DSv2][2/7] List Delta Lake table files from the log (ray-project#67888)
  [Data] Parallelize Parquet and ORC full-schema reads (ray-project#67542)
  [Data] Random Shuffle on Shuffle V2 Map/Reduce Operators (ray-project#68004)
  [Data] Propagate metadata prefetch thread failures to executor (ray-project#68171)
  [core] Send generator consumed-progress updates from io_service_ (ray-project#67160)
  [Data] Add @ray-data-connectors as codeowner for datasource/sinks files (ray-project#68154)
  [data][llm] Keep the prompt in vLLM error rows (ray-project#67665)
  [data][actor-only][3/n] Actor-only backend: operator fusion (ray-project#67699)
  [Data] Read text files on DataSource v2 (ray-project#68063)
  [Autoscaler][KubeRay] Never patch worker group replicas below minReplicas (ray-project#67332)
  [Serve] Show progress of updating (ray-project#67107)
  [core][test] Trigger usage-stats OOM test without exhausting host memory (ray-project#68009)
  [Serve] Remove unused RAY_SERVE_HAPROXY_INGRESS_RETRY_ON and RAY_SERV… (ray-project#68175)
  [Data] Implement lineage tracker garbage collection upon marking operator durable (ray-project#67788)
  [Core] Fix recovery suppression race in ObjectRecoveryManager (ray-project#64974)
  [serve] Pass grpc.so_reuseport to gRPC as an integer (ray-project#66816)
  [Autoscaler][v2] Preserve retry accounting when trimming status history (ray-project#67360)
  [doc] Refresh intersphinx inventory snapshots (ray-project#68069)
  [Doc] Add item to AGENTS.md to update documentation when modifying API-facing code. (ray-project#68204)
  [Train] Preserve `num_boost_round=0` and avoid mutating `callbacks` in legacy LightGBM/XGBoost trainers (ray-project#68145)
  [Train] Raise in prepare_data_loader instead of dropping a custom batch_sampler (ray-project#68201)
  [air] Return None in skip_exceptions when exc or StartTraceback cause is None (ray-project#68172)
  [Train] Fix `checkpoint_manager` to support metrics only reported in a validation function (ray-project#67909)
  [Train] Count elastic workers in resource units for fractional resources (ray-project#68139)
  [Data] Refactor Disk shuffle map to use map Operator (ray-project#67130)
  [core][move semantics][2/n] Change state to moved on consumption and add enforcements (ray-project#66767)
  [Data] Propagate labels to object-store SHUFFLE_V2 map/reduce tasks (ray-project#67135)
  feat(core): add Cambricon MLU resource support (ray-project#66368)
  [Data] Make `zero_copy_batch=False` copy default batches (ray-project#67154)
  [data] Fix Parquet filename suffix detection (ray-project#67156)
  [data] Fix docstring/behavior mismatches in read_json and Dataset.sort (ray-project#66927)
  [Data] Run video_object_detection.ray on T4s with more memory (ray-project#68149)
  [core][sandbox] Let a node override network="public" sandboxes' default resolvers (ray-project#67691)
  [Data] read_mcap: resolve each sample's steps and lay out its row (ray-project#67925)
  [Data] read_mcap: sample read inputs: TopicSpec, steps, match and samples checks (ray-project#67924)
  [Data] Keep a map task's buffered rows when max_errored_blocks skips its error; read past corrupt MCAP chunks (ray-project#67167)
  [core][move semantics][1/n] Adding consume_once flag in actor methods (ray-project#66620)
  [Data] Size the schema pin and the columns Ray adds in the Parquet decoded-size estimate [3/6] (ray-project#67838)
  [Serve][LLM][1/3] Token based autoscaling: track autoscaling workload in KV router (ray-project#67937)
  [Data] Add native direct reads for nonpartitioned Hive tables (ray-project#67114)
  [Train] Count elastic workers in resource units for fractional resources (ray-project#68139)
  [Data] Add `condition` to `Dataset.join` and extract equi-join keys from it (ray-project#67590)
  [data] Add Top-N execution (ray-project#66931)
  [build] Bazel 8.8.1: bump protobuf to v29.6, rules_java to 8.12.0 and gRPC to 1.69.0 (ray-project#66483)
  [build] Use Arena::Create and pin Java 8 bytecode ahead of protobuf 29 / rules_java 8 (ray-project#67720)
  [core][sandbox] Don't join a sandbox's cgroup on every exec (ray-project#67690)
  [Data] Run `training_ingest_regression_test` on Instances that can be Provisioned (ray-project#68110)
  [Data] Run Sort on Disk-based Shuffle under SHUFFLE_V2 (ray-project#67850)
  [core] Deflake tests that race on timing (ray-project#67717)
  [ci] Bump pypa manylinux2014 base image to 2026.10.22-0 for CPython 3.15 (ray-project#67285)
  [Data] Make Mcap Data Column Test Insensitive to Struct Field Order (ray-project#68109)
  [Data] read_mcap V2: cut large files where their log-time order holds (ray-project#67166)
  [core][sandbox] Commit sandbox as new registry image (ray-project#67972)
  [Data] read_mcap V2: read neighbouring chunks in one ranged request (ray-project#67930)
  [train][4/n] Wire WorkerProbes through the HealthManager (ray-project#67915)
  [train][3/n] Add WorkerProbe results and health reports to the HealthState (ray-project#67879)
  [Data] (Data fault tolerance ray-project#6/6) Add a manual release test for lineage reconstruction (ray-project#67519)
  [train][6/n] Act on health decisions in the Ray Train controller (ray-project#67856)
  [Train] Do not start an elastic worker group with zero workers (ray-project#68101)
  [Train] Keep the last checkpoint after a metrics-only report in local mode (ray-project#68070)
  [Data][2/n] Migrate GPU Shuffle to Unified Phase Metrics (ray-project#67359)
  [Data][Chkpt] Fix `ArrowInvalid` when loading large generated-ID checkpoints (ray-project#68065)
  [core][test] Create auth token in test_redis_wrong_password (ray-project#68014)
  [data][actor-only][2/n] Actor-only backend: promote task pools to actor pools (ray-project#67698)
  [Data] Fix typing mismatches in Dataset public API (ray-project#62077)
  [Data] read_mcap V2: carry read tasks' summary records in the manifest (ray-project#67929)
  [Data] Distinguish generated ID collisions with synthesized columns (ray-project#67164)
  [Data] Fix incorrect scale-up in rate-based autoscaler for custom resources (ray-project#66647)
  [Data][Delta DSv2][1/7] Shared Parquet and partitioning fixes for the Delta reader (ray-project#67887)
  [Data] Eliminate redundant aggregation shuffle (ray-project#67198)
  [Data] Raise minimum supported pyarrow to 23.0.0 and test up to 26.0.1 (ray-project#68005)
  [Train] Use the default validation timeout when a report's ValidationTaskConfig has none (ray-project#68045)
  [doc][train] Use the global batch size in the TensorFlow Train examples (ray-project#68006)
  [TPU] Default multi-slice MASTER_ADDR to slice 0 host 0 in SlicePlacementGroup (ray-project#67878)
  [Data] Estimate a Parquet row group's decoded Arrow bytes from its footer [2/6] (ray-project#67837)
  [Data] Predicate pushdown through joins: split conjuncts, derive one-sided OR weakenings (ray-project#67122)
  [Data] Add partition_filters to read_delta and take file sizes from the log (ray-project#67900)
  [Data] Stop writing Unity Catalog vended credentials to the environment (ray-project#67899)
  [Data] Raise an error for Delta tables with column mapping in write_delta (ray-project#67898)
  [Core] Add initial foundational configurations and flags for fork server (ray-project#67356)
  [core][sandbox] Image layers caching (ray-project#67874)
  [Doc][Train] Add device stream batch prefetching section to accelerator guide (ray-project#67779)
  [Train] Use user-defined train function name in training thread name and error stack traces (ray-project#64292)
  [serve][docs] Remove beta label from custom autoscaling policies (ray-project#68046)
  [core] Don't treat a gRPC client with calls in flight as idle (ray-project#67718)
  [train] Fix checkpoint sorting to support nested metrics (ray-project#59130)
  [train][5/n] Run ControllerProbes on the controller's node monitor (ray-project#67671)
  [Train] Rank a checkpoint without the score attribute as worst in min order (ray-project#67901)
  [Core][RuntimeEnv] Stream runtime environment package downloads (ray-project#67184)
  [core] Deflake `_run_hanging_command` tests (ray-project#67461)
  [Data] Add Gravitino Iceberg REST catalog provider (ray-project#67007)
  [Data] Fix mixed-root partition filtering in Parquet and ORC V2 (ray-project#67067)
  [core] Keep absl logging at ERROR unless GRPC_VERBOSITY is set (ray-project#67719)
  [Data][1/n]Add Shuffle Metrics Unification Instrumentation (ray-project#66968)
  [ci][release] Stop publishing Python 3.10 wheels and images (ray-project#67722)
  [serve] Copy the ASGI lifespan state into each request scope (ray-project#67844)
  [Serve][LLM][4/5] Support scale-to-zero application routing (ray-project#67087)
  [core][sandbox] Let GPU sandboxes request NVIDIA profiling capabilities (ray-project#67974)
  [Serve][LLM] Exclude LLMRouter from dashboard QPS (ray-project#67873)
  [Data] Read the Parquet SizeStatistics PyArrow doesn't expose [1/6] (ray-project#67836)
  Add perf metrics for 2.60.0 (ray-project#67727)
  [Observability / Train] Add Grafana Annotation support with Ray Train usage (ray-project#66958)

Signed-off-by: Eugene Paniot <[email protected]>

# Conflicts:
#	python/ray/data/_internal/planner/plan_udf_map_op.py
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 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.

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

4 participants