Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: build the OpenAPI schema off the event loop (#14239)

Daniel Hana770de942d9b
diff --git a/studio/backend/main.py b/studio/backend/main.py
index f2954dbcbf7..0d57e8ea9bd 100644
--- a/studio/backend/main.py
+++ b/studio/backend/main.py
@@ -336,7 +336,7 @@ if os.getenv("ENVIRONMENT_TYPE", "production") == "production":
from fastapi import Depends, FastAPI, HTTPException, Query, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
-from fastapi.responses import FileResponse, HTMLResponse, Response
+from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, Response
from starlette.middleware.gzip import GZipMiddleware
from pathlib import Path
from datetime import datetime
@@ -1097,7 +1097,10 @@ app = FastAPI(
docs_url = None,
redoc_url = None,
swagger_ui_oauth2_redirect_url = None,
+ # Served below instead, with the schema built off the event loop (#9712).
+ openapi_url = None,
)
+app.openapi_url = "/openapi.json"
app.state.secure = os.environ.get("UNSLOTH_SECURE") == "1"
from fastmcp.utilities.lifespan import combine_lifespans # noqa: E402
@@ -1364,6 +1367,31 @@ def _nonced_docs_response(html: str, *, tag: "_re.Pattern[str]") -> HTMLResponse
return HTMLResponse(nonced, headers = {_CSP_SCRIPT_NONCE_HEADER: nonce})
+# FastAPI's own /openapi.json builds the schema on the event loop: seconds for ~550 routes, fetched by the chat
+# sidebar every session, stalling every request behind it (#9712). Built once in a worker thread instead.
+_openapi_build_lock = threading.Lock()
+_build_openapi_schema = app.openapi
+
+
+def _openapi_once() -> dict:
+ with _openapi_build_lock:
+ return _build_openapi_schema()
+
+
+app.openapi = _openapi_once
+
+
[email protected](app.openapi_url, include_in_schema = False)
+async def openapi_json(request: Request):
+ schema = await asyncio.to_thread(app.openapi)
+ # As FastAPI's built-in route: name the prefix a path-stripping proxy hides.
+ root_path = request.scope.get("root_path", "").rstrip("/")
+ if root_path and app.root_path_in_servers:
+ if root_path not in {server.get("url") for server in schema.get("servers", [])}:
+ schema = {**schema, "servers": [{"url": root_path}, *schema.get("servers", [])]}
+ return JSONResponse(schema)
+
+
if _DOCS_ASSETS_DIR.is_dir():
app.mount(
_DOCS_ASSETS_URL,
diff --git a/studio/backend/tests/test_openapi_off_the_event_loop.py b/studio/backend/tests/test_openapi_off_the_event_loop.py
new file mode 100644
index 00000000000..a6e6c9a83b1
--- /dev/null
+++ b/studio/backend/tests/test_openapi_off_the_event_loop.py
@@ -0,0 +1,98 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Building the OpenAPI schema must not stall the event loop (#9712). The build is slowed so
+the result does not depend on machine speed."""
+
+from __future__ import annotations
+
+import asyncio
+import sys
+import threading
+import time
+from pathlib import Path
+
+import fastapi.applications
+import httpx
+import pytest
+from fastapi.testclient import TestClient
+
+_BACKEND_ROOT = Path(__file__).resolve().parent.parent
+if str(_BACKEND_ROOT) not in sys.path:
+ sys.path.insert(0, str(_BACKEND_ROOT))
+
+_BUILD_S = 3.0
+
+
[email protected](scope = "module")
+def main_module():
+ import main as _main
+ return _main
+
+
+def slow_cold_build(main_module, monkeypatch):
+ """A cold schema cache whose build takes _BUILD_S and counts its calls."""
+ real = fastapi.applications.get_openapi
+ calls = []
+
+ def slow(*args, **kwargs):
+ calls.append(threading.current_thread().name)
+ time.sleep(_BUILD_S)
+ return real(*args, **kwargs)
+
+ monkeypatch.setattr(fastapi.applications, "get_openapi", slow)
+ saved = main_module.app.openapi_schema
+ main_module.app.openapi_schema = None
+ yield calls
+ main_module.app.openapi_schema = saved
+
+
+async def _loop_delay_during_cold_fetches(app, fetches: int):
+ transport = httpx.ASGITransport(app = app)
+ async with httpx.AsyncClient(transport = transport, base_url = "http://127.0.0.1") as client:
+ worst = 0.0
+ done = asyncio.Event()
+
+ async def probe():
+ nonlocal worst
+ while not done.is_set():
+ started = time.perf_counter()
+ await asyncio.sleep(0.02)
+ worst = max(worst, time.perf_counter() - started - 0.02)
+
+ prober = asyncio.create_task(probe())
+ await asyncio.sleep(0.1)
+ responses = await asyncio.gather(*(client.get("/openapi.json") for _ in range(fetches)))
+ done.set()
+ await prober
+ return worst, responses
+
+
+def test_cold_schema_build_leaves_the_loop_answering(main_module, slow_cold_build):
+ worst, (response,) = asyncio.run(_loop_delay_during_cold_fetches(main_module.app, 1))
+ assert response.status_code == 200
+ assert worst < _BUILD_S / 2, f"event loop blocked {worst:.2f}s while the schema was built"
+ assert slow_cold_build and all(name != "MainThread" for name in slow_cold_build)
+
+
+def test_concurrent_cold_fetches_build_once_and_agree(main_module, slow_cold_build):
+ worst, responses = asyncio.run(_loop_delay_during_cold_fetches(main_module.app, 3))
+ assert worst < _BUILD_S / 2
+ assert len(slow_cold_build) == 1
+ assert len({r.content for r in responses}) == 1
+ # What the chat sidebar reads to decide whether title repair is safe.
+ patch = responses[0].json()["components"]["schemas"]["ChatThreadPatch"]["properties"]
+ assert {"expectedTitle", "expectedOpeningMessageId"} <= set(patch)
+
+
+def test_schema_route_keeps_fastapi_behaviour(main_module):
+ plain = TestClient(main_module.app).get("/openapi.json")
+ assert plain.status_code == 200
+ assert plain.json() == main_module.app.openapi()
+ assert "/openapi.json" not in plain.json()["paths"]
+
+ # As FastAPI's own route: a path-stripping proxy's prefix is named in servers.
+ prefixed = TestClient(main_module.app, root_path = "/studio").get("/openapi.json").json()
+ assert prefixed["servers"][0] == {"url": "/studio"}
+ assert "servers" not in main_module.app.openapi()