Repository navigation
Send ASGI lifespan events to api_transformer apps; drop the extra top-level Starlette app - #7624
Conversation
Replace the top-level Starlette app that wrapped the backend only to run lifespan tasks with a lightweight root middleware. It attaches the Reflex contexts to every ASGI call and answers lifespan events itself, using a route-less Starlette Router for the protocol. The lifespan now also enters the lifespan of each Starlette/FastAPI instance passed to api_transformer, after Reflex's own lifespan tasks and in transformer order, stopping in reverse. State they yield is merged into the ASGI lifespan state, so it reaches request.state. Apps mounted on a transformer and apps returned by a callable transformer still get no lifespan events. Requests no longer pass through an extra router, Mount and duplicate CORS middleware; CORS is added on top only when the outermost transformer is a callable, whose routes would otherwise bypass it. Closes #5220. Fixes the gap behind #5749. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01RjudwuP2ZkW5TQ9zdz7H9K
…e internals The previous commit started transformer lifespans by entering Starlette's router.lifespan_context, which only works for Starlette/FastAPI instances. Drive the ASGI lifespan protocol instead, the way a server does: - Lifespan events go to the outermost app the transformers produce, so middleware returned by a callable transformer gets them and forwards them inward per the spec. - Starlette does not forward lifespan events to the apps it mounts, so each app a Starlette transformer mounts (other than Reflex's own API) also gets them. Apps users mount on a transformer themselves do not. - Every app shares the server's lifespan state, so yielded state reaches request.state. - As in a server's "auto" mode, an app that raises, returns or sends another message instead of answering startup is skipped with an info log; startup.failed and shutdown.failed are raised. _RootMiddleware now answers the server's lifespan events itself instead of borrowing a route-less Starlette Router, so it can pass the server's scope through. The docs' logging middleware example now passes lifespan scopes through instead of failing on scope["path"]. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01RjudwuP2ZkW5TQ9zdz7H9K
Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01RjudwuP2ZkW5TQ9zdz7H9K
Users who worked around transformer lifespans not running (#5749) by registering the same function with register_lifespan_task would now run it twice. Warn when building the app if a Starlette transformer's lifespan is also registered, and tell upgrading users in the news fragment to remove such workarounds. Also cover the server-facing shutdown.failed path. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01RjudwuP2ZkW5TQ9zdz7H9K
There was a problem hiding this comment.
All reported issues were addressed across 9 files
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
[Medium impact] The PR appears safe to merge, with the previously reported cleanup concern remaining non-blocking. SummaryThe PR replaces the extra Starlette wrapper with
masenf explicitly acknowledges these behavior changes:
Reviews (2) · Last reviewed commit: "Keep CORS on 500 responses and skip Fast..." · Reviewed by Greptile |
Merging this PR will not alter performance1 warning
Comparing |
# Conflicts: # tests/units/test_app.py
Wrap the outermost app in one CORS layer, outside the outermost Starlette error handler, so unhandled route errors keep their CORS headers. Import FastAPI in the two tests that use it, so test_app.py collects without pydantic. Use a with block for the shutdown-failure test client and fix the starlette_app wording in the lifespan docs.
* Fix 0.11 changelog and database guide gaps from 0.11.0a1 QA - Add a breaking entry for rx.App.__call__ returning a plain ASGI callable (#7624), pointing at api_transformer; drop the same note from the performance entry. Named 7624.breaking.md so it links to the PR that made the change rather than this one. - Admin dashboard guide: say the dashboard is served at /admin/ (/admin without the slash returns 404), define the MyAuthProvider the example uses, and note that MappedAsDataclass models need a default or init=False on every constructor field for starlette-admin's "New" form. - tables.md: build the custom serializer from the mapper's column attributes instead of dataclasses.asdict, which follows relationships and raises DetachedInstanceError / RecursionError. Extend the docs example test with a relationship so the old snippet fails it. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Dxjadq3qkhKnqZR2b9WBFi * Compare admin credentials as UTF-8 bytes in the auth example secrets.compare_digest raises TypeError for non-ASCII str arguments, so the guide's login rejected even correct non-ASCII credentials with a 500. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Dxjadq3qkhKnqZR2b9WBFi * Pin starlette-admin >=1.0 in the admin dashboard install line The guide uses the starlette-admin 1.x API (Admin(secret_key=...), the AuthProvider login/authenticate signatures). Reflex 0.7.5 and earlier installed starlette-admin <1.0, and a plain `pip install starlette-admin` keeps that version, so the pin makes the command upgrade it. --------- Co-authored-by: Claude <[email protected]> Co-authored-by: Farhan <[email protected]>
* Fix 0.11 changelog and database guide gaps from 0.11.0a1 QA - Add a breaking entry for rx.App.__call__ returning a plain ASGI callable (#7624), pointing at api_transformer; drop the same note from the performance entry. Named 7624.breaking.md so it links to the PR that made the change rather than this one. - Admin dashboard guide: say the dashboard is served at /admin/ (/admin without the slash returns 404), define the MyAuthProvider the example uses, and note that MappedAsDataclass models need a default or init=False on every constructor field for starlette-admin's "New" form. - tables.md: build the custom serializer from the mapper's column attributes instead of dataclasses.asdict, which follows relationships and raises DetachedInstanceError / RecursionError. Extend the docs example test with a relationship so the old snippet fails it. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Dxjadq3qkhKnqZR2b9WBFi * Compare admin credentials as UTF-8 bytes in the auth example secrets.compare_digest raises TypeError for non-ASCII str arguments, so the guide's login rejected even correct non-ASCII credentials with a 500. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Dxjadq3qkhKnqZR2b9WBFi * Pin starlette-admin >=1.0 in the admin dashboard install line The guide uses the starlette-admin 1.x API (Admin(secret_key=...), the AuthProvider login/authenticate signatures). Reflex 0.7.5 and earlier installed starlette-admin <1.0, and a plain `pip install starlette-admin` keeps that version, so the pin makes the command upgrade it. --------- Co-authored-by: Claude <[email protected]> Co-authored-by: Farhan <[email protected]> (cherry picked from commit 34f8c3c)
All Submissions:
Type of change
See "Behavior changes" below for the edges that could affect existing apps.
Changes To Core Features:
What and why
App.__call__wrapped the whole backend in an extraStarlette(lifespan=...)and mounted the transformed app inside it. Starlette'sMountdoesn't forward lifespan events, so thelifespanof anything passed toapi_transformernever ran (a FastAPIlifespan=,on_startuphandlers, a lifespan-aware middleware). That's the gap behind #5749. The extra app also added a router, aMountand a second CORS middleware to every request (#5220).This PR:
_RootMiddleware(reflex/app.py). It sets the Reflex contexts on every ASGI call, as_ContextMiddlewaredid, including during lifespan, and answers the server's lifespan events itself. All other scopes go straight to the app._run_asgi_lifespaninreflex/app_mixins/lifespan.py), the way a server does, so it works for any ASGI app, not only Starlette:mount("", ...)itself. So the app each Starlette transformer mounts also gets them, except Reflex's ownStarletteapp, whose lifespan is the registered tasks.register_lifespan_tasktasks run.state, so yielded state reachesrequest.state.startup.failedandshutdown.failedare raised, and lifespans already started still shut down._apiand Starlette transformers keep their own CORS as before, so the header now appears exactly once./ping, roughly 175 µs down to 155 µs in a direct ASGI loop.Closes #5220. Fixes the problem in #5749.
Behavior changes reviewers should weigh
app()returns_RootMiddleware, notStarlette. It's typedASGIAppand already wasn't aStarlettewith OpenTelemetry on, and nothing in this repo relies on it. External code callingapp().mount(...)/url_path_for(...)would break; the performance news fragment calls this out.lifespan=,on_startup,@app.on_event("startup"). That's the fix, but a transformer whose startup raises will now fail server startup.register_lifespan_taskwould now run it twice.App.__call__warns when a Starlette transformer'srouter.lifespan_contextis also a registered task, and the news fragment tells users to drop the workaround.starlette_applifespan-task argument is now Reflex's ownStarletteapp instead of the internal wrapper. Code that searched the wrapper's routes for the transformer (the other workaround suggested in [Question] How to use asynccontextmanager #5749) won't find it; the news fragment covers this.scope["path"]unconditionally raises on it. The server still starts; Reflex logs that the app appears not to support lifespan, and lifespans inside it don't run (they never did before). I fixed the docs' logging middleware example accordingly.ServerErrorMiddleware. Reflex's own routes are unaffected.scope["router"]is now the outermost Starlette in the chain instead of the wrapper. Admin reverse routing is unchanged (tests cover it with and without a transformer), and it now also works behind a callable transformer, where the wrapper'sMountexposed no routes.I also checked granian's and uvicorn's lifespan handling (granian passes
stateand treats a raise afterstartup.failedas fatal) and the OpenTelemetry ASGI middleware (passes non-HTTP scopes through). There's no overlap with #7416, which watches for the standardlifespan.startup.completethat_RootMiddlewarestill sends.Tests
tests/units/test_app.py:request.state;tests/units/app_mixins/test_lifespan.py: a plain non-Starlette ASGI lifespan app, shared state, the three "unsupported" cases, and both failure modes.tests/integration/test_lifespan.py: the FastAPI transformer now has a lifespan whose start and stop are counted. Not run locally: the sandbox's ChromeDriver doesn't match its Chromium, so this PR's CI is the first run. I checked the same flow under a real uvicorn server instead.uv run pre-commit runon the changed files: ruff, codespell, pyright, ty, pyi all pass.docs/appdoc-link tests pass.tests/unitsrun has 262 failures, all inreflex_cli/v2and thereflex_benchbrowser driver; they fail the same way on unmodifiedmainin this sandbox (no network/browser).Generated by Claude Code