Reset middleware_stack before re-adding Galaxy middleware

Starlette's ``add_middleware`` guards against mutations once the
stack has been built (at first request), so the rebind path was
hitting ``RuntimeError: Cannot add middleware after an application
has started`` at every subsequent test-class setup —
``caching_fast_app_factory`` → ``_rebind_galaxy_middleware`` →
``add_galaxy_middleware.add_middleware``.

The fix is ordering: clear ``middleware_stack`` first, then re-run
``add_galaxy_middleware``. Starlette then rebuilds the stack
lazily from ``user_middleware`` on the next request with the
current ``gx_app`` config picked up.
This commit is contained in:
mvdbeek
2026-04-22 09:21:37 +02:00
parent 80b3a10db8
commit 22f5fe3614
+5 -3
View File
@@ -824,10 +824,12 @@ def _rebind_galaxy_middleware(app: FastAPI, gx_app) -> None:
app.user_middleware = [
mw for mw in app.user_middleware if mw.cls not in (GalaxyCORSMiddleware, XFrameOptionsMiddleware)
]
add_galaxy_middleware(app, gx_app)
# Force Starlette to rebuild its middleware stack on the next request
# so the re-added middleware actually takes effect.
# Reset the middleware stack BEFORE re-adding middleware: Starlette's
# ``add_middleware`` guards against mutations after the stack has been
# built (first request), so we have to clear it first. The stack will
# be rebuilt lazily from ``user_middleware`` on the next request.
app.middleware_stack = None
add_galaxy_middleware(app, gx_app)
def _rebind_fast_app_for_launch(app: FastAPI, gx_wsgi_webapp, gx_app) -> None: