Skip to content

A middleware that raises on a lifespan scope silently disables a FastAPI api_transformer's lifespan (only an INFO line) #7832

Description

@masenf

Problem

Since 0.11, Reflex sends ASGI lifespan events to api_transformer apps, so a FastAPI(lifespan=...) passed as a transformer finally runs its lifespan. But if the transformer list also contains a plain ASGI middleware that assumes every scope is HTTP (for example it reads scope["path"], which the 0.10 docs' middleware example did), the middleware raises KeyError('path') on the lifespan scope. Reflex treats any exception during lifespan.startup as "lifespan not supported", logs it at INFO, and skips the lifespan of every Starlette/FastAPI app wrapped below that middleware:

Info: ASGI lifespan appears unsupported by <function old_mw.<locals>.middleware at 0x...>: KeyError('path')

The app starts and serves HTTP normally, so the only symptom is that the FastAPI lifespan never ran: app.state values it sets are missing, background clients it opens are never opened. An INFO line that calls a KeyError "unsupported" is easy to miss.

Not a regression in outcome (on 0.10.1 the FastAPI lifespan never ran at all), but the 0.11 changelog promises that the transformer's lifespan now runs, and anyone who copied the 0.10 docs middleware does not get that.

Repro

import reflex as rx
from contextlib import asynccontextmanager
from fastapi import FastAPI


@asynccontextmanager
async def lifespan(api):
    print("fastapi lifespan start")
    api.state.greeting = "hello"
    yield
    print("fastapi lifespan stop")


fastapi_app = FastAPI(lifespan=lifespan)


@fastapi_app.get("/api/greeting")
async def greeting():
    return {"greeting": getattr(fastapi_app.state, "greeting", None)}


def old_mw(asgi_app):
    async def middleware(scope, receive, send):
        if scope["path"].startswith("/old-docs"):  # raises KeyError on the lifespan scope
            ...
        await asgi_app(scope, receive, send)
    return middleware


app = rx.App(api_transformer=[fastapi_app, old_mw])

reflex run --env prod --backend-only, then curl localhost:8000/api/greeting returns {"greeting": null}; "fastapi lifespan start" is never printed; the log has only the INFO line above. Replace scope["path"] with scope.get("path", "") (the 0.11 docs example) and the lifespan runs.

Expected vs actual

  • Expected: when a wrapped app raises while handling lifespan.startup (as opposed to returning without answering, which is the legitimate "unsupported" signal), Reflex logs a WARNING that includes the exception and names the Starlette/FastAPI transformer(s) under it whose lifespan will therefore not run, with the fix ("pass non-http scopes through, e.g. scope.get("path")").
  • Actual: INFO line only; the inner lifespans are skipped silently.

Fix direction

  • Code: _run_asgi_lifespan in reflex/app_mixins/lifespan.py (the except Exception as err: message = {"type": repr(err)} path) and the place that builds lifespan_apps in reflex/app.py (lifespan_apps gets the outermost wrapped app, so one broken middleware hides every Starlette lifespan below it).
  • Minimum: log at WARNING when startup raises, naming the app and the exception; when it is known which transformers are wrapped below, name the ones with a non-default router.lifespan_context.
  • Optional, larger: send lifespan events directly to inner Starlette transformers (as is already done for mounted ones) so a broken outer middleware cannot hide them. Only do this if it does not run a lifespan twice.
  • Keep the INFO level for apps that do not answer at all (the uvicorn lifespan="auto" behaviour).
  • Docs: one upgrade-note sentence that middleware in api_transformer now sees lifespan scopes.
  • Tests: a unit test in tests/units/app_mixins/ (or the existing lifespan tests) with a middleware that raises on non-http scopes, asserting the WARNING.

Activity

  1. added
    bugSomething isn't working
    release-trainIssues found during agentic /prerelease-testing fanout, not necessarily validated bugs.
    on Nov 11, 2026
  2. linear-code commented on Nov 11, 2026

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingrelease-trainIssues found during agentic /prerelease-testing fanout, not necessarily validated bugs.

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions