From 22f5fe3614edae5c42a79ce037db552bc335282e Mon Sep 17 00:00:00 2001 From: mvdbeek Date: Wed, 22 Apr 2026 09:21:37 +0200 Subject: [PATCH] Reset middleware_stack before re-adding Galaxy middleware MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- lib/galaxy_test/driver/driver_util.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/lib/galaxy_test/driver/driver_util.py b/lib/galaxy_test/driver/driver_util.py index c171a446349..e0520967553 100644 --- a/lib/galaxy_test/driver/driver_util.py +++ b/lib/galaxy_test/driver/driver_util.py @@ -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: