Skip to content

Send ASGI lifespan events to api_transformer apps; drop the extra top-level Starlette app - #7624

Merged
FarhanAliRaza merged 6 commits into
mainfrom
claude/loving-dijkstra-1su8su
Oct 28, 2026
Merged

FarhanAliRaza merged 6 commits into
mainfrom
claude/loving-dijkstra-1su8su

Conversation

@masenf

@masenf masenf commented Oct 20, 2026 •

Copy link
Copy Markdown
Collaborator

All Submissions:

  • Have you followed the guidelines stated in CONTRIBUTING.md file?
  • Have you checked to ensure there aren't any other open Pull Requests for the desired changed?

Type of change

  • Bug fix (non-breaking change which fixes an issue)
  • This change requires a documentation update (included)

See "Behavior changes" below for the edges that could affect existing apps.

Changes To Core Features:

  • Have you added an explanation of what your changes do and why you'd like us to include them?
  • Have you written new tests for your core changes, as applicable?
  • Have you successfully ran tests with your changes locally?

What and why

App.__call__ wrapped the whole backend in an extra Starlette(lifespan=...) and mounted the transformed app inside it. Starlette's Mount doesn't forward lifespan events, so the lifespan of anything passed to api_transformer never ran (a FastAPI lifespan=, on_startup handlers, a lifespan-aware middleware). That's the gap behind #5749. The extra app also added a router, a Mount and a second CORS middleware to every request (#5220).

This PR:

  • Replaces the wrapper with _RootMiddleware (reflex/app.py). It sets the Reflex contexts on every ASGI call, as _ContextMiddleware did, including during lifespan, and answers the server's lifespan events itself. All other scopes go straight to the app.
  • Sends real ASGI lifespan events to the transformer apps (_run_asgi_lifespan in reflex/app_mixins/lifespan.py), the way a server does, so it works for any ASGI app, not only Starlette:
    • The outermost transformed app gets them. Middleware returned by a callable transformer forwards them inward per the ASGI spec.
    • Starlette/FastAPI don't forward lifespan events to the apps they mount, and Reflex makes that mount("", ...) itself. So the app each Starlette transformer mounts also gets them, except Reflex's own Starlette app, whose lifespan is the registered tasks.
    • Apps a user mounts on a transformer get nothing. Only the transformers and register_lifespan_task tasks run.
    • Every app shares the server's lifespan state, so yielded state reaches request.state.
    • Like uvicorn's/granian's "auto" mode, an app that raises, returns or sends some other message instead of answering startup is skipped, with an info log. startup.failed and shutdown.failed are raised, and lifespans already started still shut down.
  • Order: Reflex lifespan tasks start first. Transformer apps start innermost first and stop in reverse, before the tasks stop.
  • CORS: the top-level CORS layer is now added only when the outermost transformer is a callable, whose own routes would otherwise have none. _api and Starlette transformers keep their own CORS as before, so the header now appears exactly once.
  • Measured: about 11% less per-request ASGI overhead on /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

  1. app() returns _RootMiddleware, not Starlette. It's typed ASGIApp and already wasn't a Starlette with OpenTelemetry on, and nothing in this repo relies on it. External code calling app().mount(...)/url_path_for(...) would break; the performance news fragment calls this out.
  2. Transformer startup code that never ran now runs: FastAPI lifespan=, on_startup, @app.on_event("startup"). That's the fix, but a transformer whose startup raises will now fail server startup.
  3. [Question] How to use asynccontextmanager #5749 workaround runs twice. Users who also registered the transformer's lifespan with register_lifespan_task would now run it twice. App.__call__ warns when a Starlette transformer's router.lifespan_context is also a registered task, and the news fragment tells users to drop the workaround.
  4. starlette_app lifespan-task argument is now Reflex's own Starlette app 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.
  5. Naive raw-ASGI middleware now sees the lifespan scope. Anything that reads 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.
  6. Error pages: an unhandled exception from a callable transformer's own app now gets the server's default 500 instead of the wrapper's ServerErrorMiddleware. Reflex's own routes are unaffected.
  7. Named-route lookup: 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's Mount exposed no routes.

I also checked granian's and uvicorn's lifespan handling (granian passes state and treats a raise after startup.failed as fatal) and the OpenTelemetry ASGI middleware (passes non-HTTP scopes through). There's no overlap with #7416, which watches for the standard lifespan.startup.complete that _RootMiddleware still sends.

Tests

  • Unit, tests/units/test_app.py:
    • start/stop order across Reflex tasks, a FastAPI transformer, a forwarding callable and a Starlette transformer;
    • state on request.state;
    • mounted apps getting no events;
    • CORS header exactly once whether the last transformer is Starlette or a callable;
    • startup and shutdown failure reach the server;
    • the double-registration warning.
  • Unit, tests/units/app_mixins/test_lifespan.py: a plain non-Starlette ASGI lifespan app, shared state, the three "unsupported" cases, and both failure modes.
  • Integration, 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.
  • Checks run locally:
    • uv run pre-commit run on the changed files: ruff, codespell, pyright, ty, pyi all pass.
    • The docs/app doc-link tests pass.
    • The full tests/units run has 262 failures, all in reflex_cli/v2 and the reflex_bench browser driver; they fail the same way on unmodified main in this sandbox (no network/browser).

Generated by Claude Code

View guided diff Turn on auto-fix

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
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
@masenf
masenf requested review from a team and Alek99 as code owners October 20, 2026 23:22

@cubic-dev-ai cubic-dev-ai 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.

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

Comment thread reflex/app_mixins/lifespan.py Resolved
Comment thread reflex/app_mixins/lifespan.py Resolved
Comment thread docs/utility_methods/lifespan_tasks.md Resolved
Comment thread tests/units/app_mixins/test_lifespan.py Resolved
Comment thread tests/units/test_app.py Resolved
@greptile-apps

greptile-apps Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge, with the previously reported cleanup concern remaining non-blocking.

Summary

The PR replaces the extra Starlette wrapper with _RootMiddleware and sends lifespan events through the transformer chain.

  • Transformer apps now run their startup and shutdown code.
  • Requests reach the transformed app without an extra Starlette router.

masenf explicitly acknowledges these behavior changes:

  • app() returns a plain ASGI app to remove the extra routing layer.
  • Transformer startup code now runs; an explicit startup failure stops the server.
  • Existing registered-lifespan workarounds can run twice and should be removed.
  • starlette_app now refers to Reflex's own Starlette app.
  • Middleware that rejects lifespan scopes is skipped, matching the intended automatic fallback.
  • Errors from a callable transformer's own routes use the server's default error response.
  • Named-route lookup now uses the outermost Starlette router rather than the removed wrapper.

Reviews (2) · Last reviewed commit: "Keep CORS on 500 responses and skip Fast..." · Reviewed by Greptile

Comment thread reflex/app.py Resolved
Comment thread reflex/app_mixins/lifespan.py Resolved
@codspeed

codspeed Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

1 warning

⚠️ 19 benchmarks are dominated by system calls

System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

Learn more about system calls

See affected benchmarks

✅ 148 untouched benchmarks


Comparing claude/loving-dijkstra-1su8su (e6de73f) with main (17370c2)

Open in CodSpeed

@masenf masenf added bug Something isn't working perf Performance-improving changes documentation Improvements or additions to documentation breaking Public API facing change considered for minor release bump pre-v1.0 labels Oct 21, 2026 — with ChatGPT Codex Connector
@masenf masenf added roadmap https://github.com/reflex-dev/reflex/issues/2727 on deck PRs lined up to review / merge next labels Oct 22, 2026
# 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.
@FarhanAliRaza
FarhanAliRaza merged commit 1191a38 into main Oct 28, 2026
169 checks passed
@FarhanAliRaza
FarhanAliRaza deleted the claude/loving-dijkstra-1su8su branch October 28, 2026 16:09
FarhanAliRaza added a commit that referenced this pull request Nov 11, 2026
* 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]>
masenf added a commit that referenced this pull request Nov 11, 2026
* 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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

breaking Public API facing change considered for minor release bump pre-v1.0 bug Something isn't working documentation Improvements or additions to documentation on deck PRs lined up to review / merge next perf Performance-improving changes roadmap https://github.com/reflex-dev/reflex/issues/2727

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Optimize lifespan middleware

3 participants