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: take common SQLite reads off the event loop thread (#9234)

oobabooga8bad21be0d44
diff --git a/studio/backend/auth/authentication.py b/studio/backend/auth/authentication.py
index 810509d2a19..492622ad467 100644
--- a/studio/backend/auth/authentication.py
+++ b/studio/backend/auth/authentication.py
@@ -8,6 +8,7 @@ from typing import Optional, Tuple
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
import jwt
+from starlette.concurrency import run_in_threadpool
from .storage import (
API_KEY_PREFIX,
@@ -220,7 +221,7 @@ async def authenticated_via_desktop_jwt(
Lets routes treat the desktop as an authority of its own: it authenticates
with a local secret rather than the account password.
"""
- return is_desktop_access_token(credentials.credentials)
+ return await run_in_threadpool(is_desktop_access_token, credentials.credentials)
async def get_current_subject_allow_password_change(
@@ -257,12 +258,14 @@ async def _get_current_credential(
The generation is the credential version this request actually authenticated
against. Routes that persist new credentials must bind their write to it, or
a reset landing mid-request would bless what it just revoked.
+
+ Credential reads run in the threadpool so stalled SQLite cannot block the event loop.
"""
token = credentials.credentials
# --- API key path (sk-unsloth-...) ---
if token.startswith(API_KEY_PREFIX):
- verified = validate_api_key_with_credential(token)
+ verified = await run_in_threadpool(validate_api_key_with_credential, token)
if verified is None:
raise HTTPException(
status_code = status.HTTP_401_UNAUTHORIZED,
@@ -279,7 +282,7 @@ async def _get_current_credential(
detail = "Invalid token payload",
)
- record = get_user_and_secret(subject)
+ record = await run_in_threadpool(get_user_and_secret, subject)
if record is None:
raise HTTPException(
status_code = status.HTTP_401_UNAUTHORIZED,
diff --git a/studio/backend/core/inference/llama_keepwarm.py b/studio/backend/core/inference/llama_keepwarm.py
index 4b82f249410..8f0fd5dc9d8 100644
--- a/studio/backend/core/inference/llama_keepwarm.py
+++ b/studio/backend/core/inference/llama_keepwarm.py
@@ -456,7 +456,8 @@ async def idle_unload_loop(poll_seconds: float = 15.0) -> None:
except Exception as exc:
logger.debug("media idle_unload_step failed: %s", exc)
try:
- ttl = get_auto_unload_idle_seconds()
+ # Keep SQLite-backed setting reads off the event loop.
+ ttl = await asyncio.to_thread(get_auto_unload_idle_seconds)
if ttl <= 0:
continue
from routes.inference import get_llama_cpp_backend
@@ -473,14 +474,14 @@ async def idle_unload_loop(poll_seconds: float = 15.0) -> None:
if current is not None:
_note_activity()
_set_last_unloaded(None) # a model is loaded; drop stale stash
- if backend.is_loaded and _user_pinned(backend):
+ if backend.is_loaded and await asyncio.to_thread(_user_pinned, backend):
# Loaded from the UI, so the user wants it resident; only
# models the API loaded are freed.
continue
if backend.is_loaded and _is_idle(ttl):
freed = _loaded_identity(backend)
manifest = None
- if get_auto_unload_keep_kv():
+ if await asyncio.to_thread(get_auto_unload_keep_kv):
try:
manifest = await asyncio.to_thread(
backend.save_slots_for_resume,
@@ -489,14 +490,24 @@ async def idle_unload_loop(poll_seconds: float = 15.0) -> None:
except Exception as exc:
logger.debug("slot save before idle unload failed: %s", exc)
# Re-read settings: the save can outlive a settings change.
- ttl = get_auto_unload_idle_seconds()
- if ttl <= 0 or not _is_idle(ttl) or _user_pinned(backend):
+ ttl = await asyncio.to_thread(get_auto_unload_idle_seconds)
+ if (
+ ttl <= 0
+ or not _is_idle(ttl)
+ or await asyncio.to_thread(_user_pinned, backend)
+ ):
if manifest:
_delete_resume_files(manifest)
continue
- if manifest and not get_auto_unload_keep_kv():
+ if manifest and not await asyncio.to_thread(get_auto_unload_keep_kv):
_delete_resume_files(manifest)
manifest = None
+ # A request may register _pending while an off-loop setting read runs.
+ # Recheck idleness before unloading.
+ if not _is_idle(ttl):
+ if manifest:
+ _delete_resume_files(manifest)
+ continue
try:
await asyncio.to_thread(backend.unload_model)
except Exception:
diff --git a/studio/backend/core/inference/mcp_client.py b/studio/backend/core/inference/mcp_client.py
index e865723d8bf..d2b8f242763 100644
--- a/studio/backend/core/inference/mcp_client.py
+++ b/studio/backend/core/inference/mcp_client.py
@@ -14,7 +14,9 @@ import sys
import threading
import time
import uuid
+from functools import wraps
from typing import Any, Optional
+from weakref import WeakKeyDictionary
from loggers import get_logger
@@ -841,6 +843,28 @@ _tool_cache: dict[str, list[dict]] = {}
# eviction.
_probe_cooloff_until: dict[str, float] = {}
+# Coordinate off-loop token-count snapshots with row and schema-cache mutations.
+_mcp_server_snapshot_locks: WeakKeyDictionary[asyncio.AbstractEventLoop, asyncio.Lock] = (
+ WeakKeyDictionary()
+)
+
+
+def mcp_server_snapshot_guard() -> asyncio.Lock:
+ loop = asyncio.get_running_loop()
+ return _mcp_server_snapshot_locks.setdefault(loop, asyncio.Lock())
+
+
+def serialize_mcp_server_mutation(handler):
+ """Run an MCP mutation from validation through row/cache commit as one snapshot."""
+
+ @wraps(handler)
+ async def _serialized(*args, **kwargs):
+ async with mcp_server_snapshot_guard():
+ return await handler(*args, **kwargs)
+
+ return _serialized
+
+
# MCP server fields whose change invalidates a server's discovered tools: the
# endpoint/auth used to probe it (url, headers, oauth) or whether it's used at
# all (is_enabled). A rename does not. The update route's eviction and
diff --git a/studio/backend/core/inference/media_keepwarm.py b/studio/backend/core/inference/media_keepwarm.py
index e69a2f6bc9c..704b826e66a 100644
--- a/studio/backend/core/inference/media_keepwarm.py
+++ b/studio/backend/core/inference/media_keepwarm.py
@@ -374,18 +374,21 @@ async def _tick(tracker: _Tracker, ttl: float) -> None:
# backends and an unload frees several GB, so a residency veto applied while it runs
# (Model Memory, or the TTL itself moved) would otherwise be ignored by every teardown
# left in the step, freeing a model the settings page now calls pinned.
- ttl = _effective_ttl()
- if (
- ttl <= 0
- or not tracker.is_idle(ttl)
- or _user_pinned(
- tracker.owner,
- status.get("repo_id"),
- status.get("gguf_variant"),
- status.get("h3_task"),
- )
+ ttl = await asyncio.to_thread(_effective_ttl)
+ if ttl <= 0 or not tracker.is_idle(ttl):
+ return
+ if await asyncio.to_thread(
+ _user_pinned,
+ tracker.owner,
+ status.get("repo_id"),
+ status.get("gguf_variant"),
+ status.get("h3_task"),
):
return
+ # A request may register _pending during an off-loop setting read.
+ # Recheck idleness before unloading.
+ if not tracker.is_idle(ttl):
+ return
await asyncio.to_thread(backend.unload)
# Drop ownership only if nothing came back meanwhile, and check it under the arbiter
# lock so a same-owner load that re-registered keeps it. Mirrors /images/unload.
@@ -418,7 +421,8 @@ def _user_pinned(
async def idle_unload_step() -> None:
"""The media half of one idle_unload_loop tick. Inert when the TTL is off."""
- ttl = _effective_ttl()
+ # Keep this SQLite-backed setting read off the event loop.
+ ttl = await asyncio.to_thread(_effective_ttl)
if ttl <= 0:
return
for tracker in _TRACKERS.values():
diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.py
index 1a8ea33f910..2ed5bc96933 100644
--- a/studio/backend/core/inference/tools.py
+++ b/studio/backend/core/inference/tools.py
@@ -9881,7 +9881,10 @@ def cached_mcp_tools() -> tuple[list[dict], bool]:
async def get_enabled_mcp_tools() -> list[dict]:
- servers = [s for s in mcp_servers_db.list_servers() if s.get("is_enabled")]
+ # Keep the SQLite-backed server list off the event loop.
+ servers = [
+ s for s in await asyncio.to_thread(mcp_servers_db.list_servers) if s.get("is_enabled")
+ ]
# Never spawn stdio servers when stdio is disabled on this host.
if not stdio_mcp_enabled():
servers = [s for s in servers if not is_stdio(s["url"])]
@@ -9907,9 +9910,8 @@ async def get_enabled_mcp_tools() -> list[dict]:
),
return_exceptions = True,
)
- # An edit/delete can land while we await a probe; re-read and drop a
- # result whose server changed or was removed mid-probe, else a stale
- # tool list (or cool-off on a just-fixed server) persists.
+ # Keep this re-read on-loop so an edit cannot invalidate between it and
+ # the cache writes below. Drop results for changed or removed servers.
current = {s["id"]: s for s in mcp_servers_db.list_servers()}
for server, payload in zip(uncached, results):
fresh = current.get(server["id"])
diff --git a/studio/backend/routes/auth.py b/studio/backend/routes/auth.py
index e630272aded..fce53ac08d9 100644
--- a/studio/backend/routes/auth.py
+++ b/studio/backend/routes/auth.py
@@ -417,8 +417,9 @@ def identity(nonce: str, request: Request) -> dict:
return {"proof": storage.compute_identity_proof(raw, host, port)}
+# FastAPI offloads sync reads; mutations stay on-loop to preserve atomic sequences.
@router.get("/status", response_model = AuthStatusResponse)
-async def auth_status() -> AuthStatusResponse:
+def auth_status() -> AuthStatusResponse:
"""Auth initialization state; ``default_username`` is exposed for first-boot UI prefill only."""
return AuthStatusResponse(
initialized = storage.is_initialized(),
@@ -720,7 +721,7 @@ async def create_api_key(
@router.get("/api-keys", response_model = ApiKeyListResponse)
-async def list_api_keys(current_subject: str = Depends(get_current_subject)) -> ApiKeyListResponse:
+def list_api_keys(current_subject: str = Depends(get_current_subject)) -> ApiKeyListResponse:
"""List all API keys for the authenticated user (raw keys are never exposed)."""
rows = storage.list_api_keys(current_subject)
return ApiKeyListResponse(
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index dacefe7a93f..39dc0916085 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -2387,7 +2387,7 @@ from core.inference.studio_tool_loop import (
stream_with_studio_tools,
)
from core.inference.chat_templates import resolve_effective_chat_template_override
-from routes.provider_credentials import resolve_provider_api_key_or_400
+from routes.provider_credentials import provider_config_guard, resolve_provider_api_key_or_400
from storage import providers_db
from utils.utils import is_hf_authentication_error, safe_error_detail, log_and_http_error
@@ -12384,9 +12384,11 @@ async def _proxy_to_external_provider(
# Resolve provider type and base URL
provider_type = payload.provider_type
base_url = payload.provider_base_url
+ saved_provider_snapshot: Optional[dict] = None
if payload.provider_id and not payload.encrypted_api_key:
- config = providers_db.get_provider(payload.provider_id)
+ # Saved-provider SQLite reads must not block the event loop.
+ config = await asyncio.to_thread(providers_db.get_provider, payload.provider_id)
if config is None:
raise HTTPException(
status_code = 404,
@@ -12399,6 +12401,7 @@ async def _proxy_to_external_provider(
)
# A saved credential is scoped to this saved provider. Never pair it with
# request-controlled routing metadata.
+ saved_provider_snapshot = config
provider_type = config["provider_type"]
base_url = config["base_url"]
@@ -12764,20 +12767,42 @@ async def _proxy_to_external_provider(
headers = {"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
)
- api_key = resolve_provider_api_key_or_400(
- payload.provider_id,
- payload.encrypted_api_key,
- # A durable Deep Research hop authenticates with an internal workflow key,
- # which is still an API key, so the plain check would drop the saved
- # provider id and fail before the provider is ever contacted. The run's
- # connection was already validated as an enabled saved one by
- # research_runs._sanitize_config, and the key is verified against storage.
- # Scoped to that one workflow rather than to "internal", because the other
- # internal key Studio mints is held by a user-authored recipe subprocess.
- allow_saved_key = (
- not _request_has_api_key(request) or _request_is_saved_credential_workflow(request)
- ),
- )
+ api_key: Optional[str] = None
+ if saved_provider_snapshot is not None:
+ async with provider_config_guard(payload.provider_id):
+ current = await asyncio.to_thread(providers_db.get_provider, payload.provider_id)
+ routing_fields = ("provider_type", "base_url", "is_enabled")
+ if current is None or any(
+ current.get(field) != saved_provider_snapshot.get(field) for field in routing_fields
+ ):
+ raise HTTPException(
+ status_code = 409,
+ detail = "Provider changed while the request was starting; retry.",
+ )
+ api_key = await asyncio.to_thread(
+ resolve_provider_api_key_or_400,
+ payload.provider_id,
+ None,
+ allow_saved_key = (
+ not _request_has_api_key(request)
+ or _request_is_saved_credential_workflow(request)
+ ),
+ )
+ else:
+ api_key = resolve_provider_api_key_or_400(
+ payload.provider_id,
+ payload.encrypted_api_key,
+ # A durable Deep Research hop authenticates with an internal workflow key,
+ # which is still an API key, so the plain check would drop the saved
+ # provider id and fail before the provider is ever contacted. The run's
+ # connection was already validated as an enabled saved one by
+ # research_runs._sanitize_config, and the key is verified against storage.
+ # Scoped to that one workflow rather than to "internal", because the other
+ # internal key Studio mints is held by a user-authored recipe subprocess.
+ allow_saved_key = (
+ not _request_has_api_key(request) or _request_is_saved_credential_workflow(request)
+ ),
+ )
model = payload.external_model or payload.model
if model == "default":
@@ -13037,6 +13062,10 @@ def _resolve_openai_cloud_client(
below. The shell tool only exists on api.openai.com, so rejecting non-cloud
bases up front prevents confusing 404s on ollama / llama.cpp / vLLM /
custom presets.
+
+ Callers run this on the event loop, not in a worker: the row read and the
+ credential read have to see one provider, or an edit landing between them
+ pairs the old base URL with the new key.
"""
base_url = body.provider_base_url or get_base_url("openai")
if body.provider_id and not body.encrypted_api_key:
@@ -19804,7 +19833,11 @@ async def chat_count_tokens(
_mcp_tools: list[dict] = []
if _mcp_on and not _takes_passthrough and llama_backend.supports_tools:
from core.inference.tools import cached_mcp_tools
- _mcp_tools, _mcp_complete = cached_mcp_tools()
+ from core.inference.mcp_client import mcp_server_snapshot_guard
+
+ # Keep the SQLite read off-loop while coordinating the row/cache snapshot with edits.
+ async with mcp_server_snapshot_guard():
+ _mcp_tools, _mcp_complete = await asyncio.to_thread(cached_mcp_tools)
if not _mcp_complete:
raise HTTPException(
status_code = 503,
diff --git a/studio/backend/routes/mcp_servers.py b/studio/backend/routes/mcp_servers.py
index ef1f0dd4a6a..f02e90945e4 100644
--- a/studio/backend/routes/mcp_servers.py
+++ b/studio/backend/routes/mcp_servers.py
@@ -27,6 +27,7 @@ from core.inference.mcp_client import (
parse_stdio_command,
probe_timeout,
record_probe_failure,
+ serialize_mcp_server_mutation,
stdio_mcp_disabled_reason,
stdio_mcp_enabled,
)
@@ -128,8 +129,9 @@ def _row_to_response(row: dict) -> McpServerResponse:
)
+# FastAPI offloads sync reads; mutations stay on-loop to preserve atomic sequences.
@router.get("/", response_model = list[McpServerResponse])
-async def list_mcp_servers(
+def list_mcp_servers(
current_subject: str = Depends(get_current_subject), via_api_key: ViaApiKey = False
):
rows = mcp_servers_db.list_servers()
@@ -199,6 +201,7 @@ def _changes_from_payload(payload: McpServerUpdate) -> dict:
@router.put("/{server_id}", response_model = McpServerResponse)
+@serialize_mcp_server_mutation
async def update_mcp_server(
server_id: str,
payload: McpServerUpdate,
@@ -240,13 +243,17 @@ async def update_mcp_server(
is_stdio(current["url"]) or is_stdio(changes.get("url", current["url"]))
):
require_ui_session_for_local_commands(via_api_key)
- mcp_servers_db.update_server(server_id, changes)
# A new endpoint/auth makes cached tools wrong and disabling makes them unreachable, so drop
# them and let the next send re-probe; a rename leaves them valid. Live stdio sessions for the
# old endpoint close too. Gate on a real value change, not mere presence: the edit dialog
# resends url/headers/oauth unchanged on a rename, which must not drop the session.
- if any(changes[k] != old.get(k) for k in changes.keys() & TOOL_CACHE_INVALIDATING_FIELDS):
+ invalidates_tools = any(
+ changes[k] != old.get(k) for k in changes.keys() & TOOL_CACHE_INVALIDATING_FIELDS
+ )
+ mcp_servers_db.update_server(server_id, changes)
+ if invalidates_tools:
invalidate_tool_cache(server_id)
+ if invalidates_tools:
# Narrow to this row's env: another server row sharing the command but
# with a different env keeps its live sessions.
await asyncio.to_thread(close_stdio_sessions, old["url"], parse_server_headers(old))
@@ -254,6 +261,7 @@ async def update_mcp_server(
@router.delete("/{server_id}", status_code = 204)
+@serialize_mcp_server_mutation
async def delete_mcp_server(server_id: str, current_subject: str = Depends(get_current_subject)):
old = mcp_servers_db.get_server(server_id)
if not old:
diff --git a/studio/backend/routes/provider_credentials.py b/studio/backend/routes/provider_credentials.py
index 7aa12cf89a1..1bb7565f042 100644
--- a/studio/backend/routes/provider_credentials.py
+++ b/studio/backend/routes/provider_credentials.py
@@ -5,9 +5,11 @@
from __future__ import annotations
-
+import asyncio
from contextlib import contextmanager
+from functools import wraps
from typing import Iterator
+from weakref import WeakKeyDictionary
from auth import storage as auth_storage
@@ -19,6 +21,29 @@ from storage import credential_secrets
logger = structlog.get_logger(__name__)
+_provider_config_locks: WeakKeyDictionary[asyncio.AbstractEventLoop, dict[str, asyncio.Lock]] = (
+ WeakKeyDictionary()
+)
+
+
+def provider_config_guard(provider_id: str) -> asyncio.Lock:
+ """Serialize one provider's routing metadata and installation credential."""
+ loop = asyncio.get_running_loop()
+ locks = _provider_config_locks.setdefault(loop, {})
+ return locks.setdefault(provider_id, asyncio.Lock())
+
+
+def serialize_provider_config(handler):
+ """Keep provider mutations atomic with saved routing/credential snapshots."""
+
+ @wraps(handler)
+ async def _serialized(provider_id: str, *args, **kwargs):
+ async with provider_config_guard(provider_id):
+ return await handler(provider_id, *args, **kwargs)
+
+ _serialized._provider_config_serialized = True
+ return _serialized
+
@contextmanager
def current_credential_write(credential: tuple[str, str | None]) -> Iterator[None]:
diff --git a/studio/backend/routes/providers.py b/studio/backend/routes/providers.py
index 01815e5a1b2..72f6fc8a2fd 100644
--- a/studio/backend/routes/providers.py
+++ b/studio/backend/routes/providers.py
@@ -28,6 +28,7 @@ from routes.provider_credentials import (
current_credential_write,
require_ui_session,
resolve_provider_api_key_or_400,
+ serialize_provider_config,
)
from core.inference.key_exchange import (
get_public_key_fingerprint,
@@ -181,8 +182,9 @@ async def get_pricing_snapshot(current_subject: str = Depends(get_current_subjec
# ── Provider config CRUD ──────────────────────────────────────────
+# FastAPI offloads sync reads; mutations stay on-loop to preserve atomic sequences.
@router.get("/", response_model = list[ProviderResponse])
-async def list_provider_configs(_current_subject: str = Depends(get_current_subject)):
+def list_provider_configs(_current_subject: str = Depends(get_current_subject)):
"""List all saved provider configurations."""
rows = providers_db.list_providers()
return [_provider_response(row) for row in rows]
@@ -255,6 +257,7 @@ async def create_provider_config(
@router.put("/{provider_id}", response_model = ProviderResponse)
+@serialize_provider_config
async def update_provider_config(
provider_id: str,
payload: ProviderUpdate,
@@ -363,6 +366,7 @@ async def update_provider_config(
@router.put("/{provider_id}/api-key/migrate", response_model = ProviderResponse)
+@serialize_provider_config
async def migrate_provider_api_key(
provider_id: str,
payload: ProviderCredentialMigration,
@@ -385,6 +389,7 @@ async def migrate_provider_api_key(
@router.delete("/{provider_id}", status_code = 204)
+@serialize_provider_config
async def delete_provider_config(
provider_id: str,
credential: tuple = Depends(get_current_credential),
diff --git a/studio/backend/tests/test_auth_lookup_off_event_loop.py b/studio/backend/tests/test_auth_lookup_off_event_loop.py
new file mode 100644
index 00000000000..c7cbaa6e6df
--- /dev/null
+++ b/studio/backend/tests/test_auth_lookup_off_event_loop.py
@@ -0,0 +1,102 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Regression tests for keeping auth.db reads off the event loop."""
+
+from __future__ import annotations
+
+import asyncio
+import threading
+
+import jwt
+import pytest
+from fastapi import FastAPI
+from fastapi.security import HTTPAuthorizationCredentials
+from fastapi.testclient import TestClient
+
+import auth.authentication as authentication
+import routes.auth as auth_routes
+from auth.storage import API_KEY_PREFIX
+
+SECRET = "test-secret-long-enough-for-hs256-hmac-keys"
+SUBJECT = "test-user"
+
+
+def _credentials(token: str) -> HTTPAuthorizationCredentials:
+ return HTTPAuthorizationCredentials(scheme = "Bearer", credentials = token)
+
+
+def _record_thread(threads: list[int], result):
+ def _stub(*_args, **_kwargs):
+ threads.append(threading.get_ident())
+ return result
+
+ return _stub
+
+
+def _jwt_case(monkeypatch, threads):
+ monkeypatch.setattr(
+ authentication,
+ "get_user_and_secret",
+ _record_thread(threads, ("salt", "hash", SECRET, False)),
+ )
+ token = jwt.encode({"sub": SUBJECT}, SECRET, algorithm = authentication.ALGORITHM)
+ return authentication.get_current_subject(_credentials(token))
+
+
+def _api_key_case(monkeypatch, threads):
+ monkeypatch.setattr(
+ authentication,
+ "validate_api_key_with_credential",
+ _record_thread(threads, (SUBJECT, SECRET)),
+ )
+ return authentication.get_current_subject(_credentials(f"{API_KEY_PREFIX}key"))
+
+
+def _desktop_case(monkeypatch, threads):
+ monkeypatch.setattr(authentication, "is_desktop_access_token", _record_thread(threads, True))
+ return authentication.authenticated_via_desktop_jwt(_credentials("token"))
+
+
+ "build_call",
+ [_jwt_case, _api_key_case, _desktop_case],
+ ids = ["session-jwt", "api-key", "desktop-jwt"],
+)
+def test_the_dependency_reads_off_the_event_loop_thread(monkeypatch, build_call):
+ threads: list[int] = []
+
+ async def _drive():
+ await build_call(monkeypatch, threads)
+ return threading.get_ident()
+
+ loop_thread = asyncio.run(_drive())
+
+ assert threads, "the credential read never ran"
+ assert threads[0] != loop_thread, "credential read ran on the event loop thread"
+
+
+def test_the_status_route_reads_off_the_event_loop_thread(monkeypatch):
+ """Verify FastAPI dispatches the sync status handler to its threadpool."""
+ threads: list[int] = []
+ monkeypatch.setattr(auth_routes.storage, "is_initialized", _record_thread(threads, True))
+ monkeypatch.setattr(
+ auth_routes.storage, "requires_password_change", _record_thread(threads, False)
+ )
+
+ app = FastAPI()
+ app.include_router(auth_routes.router, prefix = "/api/auth")
+ loop_threads: list[int] = []
+
+ @app.get("/loop-thread")
+ async def _loop_thread():
+ loop_threads.append(threading.get_ident())
+ return {}
+
+ with TestClient(app) as client:
+ assert client.get("/loop-thread").status_code == 200
+ assert client.get("/api/auth/status").status_code == 200
+
+ assert threads, "the status route never read the auth store"
+ assert loop_threads, "the reference route never ran"
+ assert threads[0] != loop_threads[0], "auth_status read auth.db on the event loop thread"
diff --git a/studio/backend/tests/test_config_mutations_on_event_loop.py b/studio/backend/tests/test_config_mutations_on_event_loop.py
new file mode 100644
index 00000000000..74abd7f61ab
--- /dev/null
+++ b/studio/backend/tests/test_config_mutations_on_event_loop.py
@@ -0,0 +1,188 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""State-changing auth, MCP and provider handlers must keep running on the event loop thread.
+
+Each of these reads (a row, the server list, a rate-limit bucket) and then writes based on what
+it read, with nothing below them serializing the pair:
+
+ * import_mcp_servers builds `seen_urls` and then inserts, and `mcp_servers.url` has no
+ uniqueness constraint.
+ * update_provider_config / migrate_provider_api_key read the row and then save a credential,
+ and `credential_secrets` has no foreign key to `providers`.
+ * login clears its admission check before verify_password reaches _record_login_failure, so
+ the bucket lock guards each call but not the sequence.
+ * refresh consumes a token and inserts its replacement, and logout deletes every token in
+ between without rotating the credential generation.
+
+They are await-free, so the loop is what makes those sequences atomic. In the threadpool, two
+imports duplicate a server row, an update racing a delete writes a credential for a provider that
+is gone, a burst of guesses passes admission together, and a logout leaves the refresh token that
+landed after it. The read-only handlers beside them do belong in the threadpool, so both
+directions are pinned here.
+
+Asserts which thread each handler ran on rather than racing two requests.
+"""
+
+from __future__ import annotations
+
+import threading
+from typing import NamedTuple
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+import routes.auth as auth_routes
+import routes.mcp_servers as mcp_routes
+import routes.providers as provider_routes
+from auth.authentication import (
+ authenticated_via_api_key,
+ get_current_credential,
+ get_current_subject,
+ get_current_subject_allow_password_change,
+)
+
+
+class _Case(NamedTuple):
+ method: str
+ path: str
+ body: dict | None
+ module: object
+ store: str
+ read: str
+ result: object
+ status: int
+
+
+# The first store call is enough to identify the handler's dispatch thread.
+_MUTATIONS = {
+ "mcp-import": _Case(
+ "post",
+ "/api/mcp-servers/import",
+ {"config": {"mcpServers": {}}},
+ mcp_routes,
+ "mcp_servers_db",
+ "list_servers",
+ [],
+ 200,
+ ),
+ "provider-update": _Case(
+ "put",
+ "/api/providers/p1",
+ {"display_name": "renamed"},
+ provider_routes,
+ "providers_db",
+ "get_provider",
+ None,
+ 404,
+ ),
+ "provider-migrate": _Case(
+ "put",
+ "/api/providers/p1/api-key/migrate",
+ {"encrypted_api_key": "k"},
+ provider_routes,
+ "providers_db",
+ "get_provider",
+ None,
+ 404,
+ ),
+ "auth-login": _Case(
+ "post",
+ "/api/auth/login",
+ {"username": "u", "password": "p"},
+ auth_routes,
+ "storage",
+ "get_user_and_secret",
+ None,
+ 401,
+ ),
+ "auth-refresh": _Case(
+ "post",
+ "/api/auth/refresh",
+ {"refresh_token": "t"},
+ auth_routes,
+ "storage",
+ "consume_refresh_token",
+ None,
+ 401,
+ ),
+ "auth-logout": _Case(
+ "post",
+ "/api/auth/logout",
+ None,
+ auth_routes,
+ "storage",
+ "revoke_user_refresh_tokens",
+ None,
+ 204,
+ ),
+}
+
+_READS = {
+ "mcp-list": _Case(
+ "get", "/api/mcp-servers/", None, mcp_routes, "mcp_servers_db", "list_servers", [], 200
+ ),
+ "provider-list": _Case(
+ "get", "/api/providers/", None, provider_routes, "providers_db", "list_providers", [], 200
+ ),
+ "auth-api-keys": _Case(
+ "get", "/api/auth/api-keys", None, auth_routes, "storage", "list_api_keys", [], 200
+ ),
+}
+
+
+def _record(threads: list[int], result):
+ def _call(*_args, **_kwargs):
+ threads.append(threading.get_ident())
+ return result
+
+ return _call
+
+
+def _drive(monkeypatch, case: _Case):
+ """Run one route through real FastAPI dispatch; return (handler threads, loop thread)."""
+ threads: list[int] = []
+ monkeypatch.setattr(getattr(case.module, case.store), case.read, _record(threads, case.result))
+ # A failed login from an earlier test in this session would otherwise 429 this one.
+ monkeypatch.setattr(auth_routes, "_LOGIN_BUCKETS", {})
+ monkeypatch.setattr(auth_routes, "_LOGIN_IP_BUCKETS", {})
+
+ app = FastAPI()
+ app.include_router(auth_routes.router, prefix = "/api/auth")
+ app.include_router(mcp_routes.router, prefix = "/api/mcp-servers")
+ app.include_router(provider_routes.router, prefix = "/api/providers")
+ app.dependency_overrides[get_current_subject] = lambda: "u"
+ app.dependency_overrides[get_current_subject_allow_password_change] = lambda: "u"
+ app.dependency_overrides[authenticated_via_api_key] = lambda: False
+ app.dependency_overrides[get_current_credential] = lambda: ("u", None)
+
+ loop_threads: list[int] = []
+
+ @app.get("/loop-thread")
+ async def _loop_thread(): # Reference event-loop thread.
+ loop_threads.append(threading.get_ident())
+ return {}
+
+ with TestClient(app) as client:
+ assert client.get("/loop-thread").status_code == 200
+ body = {} if case.body is None else {"json": case.body}
+ assert client.request(case.method, case.path, **body).status_code == case.status
+
+ assert threads, f"{case.path} never touched the store"
+ assert loop_threads, "the reference route never ran"
+ return threads, loop_threads[0]
+
+
[email protected]("case", _MUTATIONS.values(), ids = list(_MUTATIONS))
+def test_a_state_changing_handler_runs_on_the_event_loop_thread(monkeypatch, case):
+ threads, loop_thread = _drive(monkeypatch, case)
+ assert (
+ threads[0] == loop_thread
+ ), f"{case.path} ran in the threadpool, so its check-then-write is no longer serialized"
+
+
[email protected]("case", _READS.values(), ids = list(_READS))
+def test_a_read_only_handler_stays_off_the_event_loop_thread(monkeypatch, case):
+ threads, loop_thread = _drive(monkeypatch, case)
+ assert threads[0] != loop_thread, f"{case.path} read its store on the event loop thread"
diff --git a/studio/backend/tests/test_keepwarm_tick_off_event_loop.py b/studio/backend/tests/test_keepwarm_tick_off_event_loop.py
new file mode 100644
index 00000000000..3a884f195b6
--- /dev/null
+++ b/studio/backend/tests/test_keepwarm_tick_off_event_loop.py
@@ -0,0 +1,66 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Keep idle-unload settings reads off the event loop."""
+
+from __future__ import annotations
+
+import asyncio
+import threading
+
+import core.inference.llama_keepwarm as llama_keepwarm
+import core.inference.media_keepwarm as media_keepwarm
+import utils.openai_auto_switch_settings as auto_switch_settings
+
+
+def _record_thread(threads: list[int], result):
+ def _stub(*_args, **_kwargs):
+ threads.append(threading.get_ident())
+ return result
+
+ return _stub
+
+
+def test_the_media_half_reads_off_the_event_loop_thread(monkeypatch):
+ threads: list[int] = []
+ monkeypatch.setattr(media_keepwarm, "_effective_ttl", _record_thread(threads, 0.0))
+
+ async def _drive():
+ await media_keepwarm.idle_unload_step()
+ return threading.get_ident()
+
+ loop_thread = asyncio.run(_drive())
+
+ assert threads, "the tick never read the TTL"
+ assert threads[0] != loop_thread, "the media TTL read ran on the event loop thread"
+
+
+def test_the_chat_half_reads_off_the_event_loop_thread(monkeypatch):
+ """Exercise the settings read through the real polling loop."""
+ threads: list[int] = []
+ monkeypatch.setattr(
+ auto_switch_settings, "get_auto_unload_idle_seconds", _record_thread(threads, 0.0)
+ )
+
+ async def _no_media_half() -> None:
+ return None
+
+ monkeypatch.setattr(media_keepwarm, "idle_unload_step", _no_media_half)
+
+ async def _drive():
+ tick = asyncio.create_task(llama_keepwarm.idle_unload_loop(poll_seconds = 0.001))
+ for _ in range(2000):
+ if threads:
+ break
+ await asyncio.sleep(0.001)
+ tick.cancel()
+ try:
+ await tick
+ except asyncio.CancelledError:
+ pass
+ return threading.get_ident()
+
+ loop_thread = asyncio.run(_drive())
+
+ assert threads, "the tick never read the TTL"
+ assert threads[0] != loop_thread, "the idle-unload TTL read ran on the event loop thread"
diff --git a/studio/backend/tests/test_mcp_stdio_api_key_gate.py b/studio/backend/tests/test_mcp_stdio_api_key_gate.py
index feed07791a2..73bea0ab489 100644
--- a/studio/backend/tests/test_mcp_stdio_api_key_gate.py
+++ b/studio/backend/tests/test_mcp_stdio_api_key_gate.py
@@ -439,7 +439,7 @@ def test_list_hides_stdio_rows_from_api_keys(tmp_path, monkeypatch, stdio_on):
headers_json = '{"Authorization": "Bearer t"}',
)
- keyed = asyncio.run(routes_mcp.list_mcp_servers(current_subject = "u", via_api_key = True))
+ keyed = routes_mcp.list_mcp_servers(current_subject = "u", via_api_key = True)
assert [row.id for row in keyed] == ["http1"]
serialized = repr([row.model_dump() for row in keyed])
assert "sk-argv-secret" not in serialized
@@ -458,7 +458,7 @@ def test_list_shows_stdio_rows_to_a_ui_session(tmp_path, monkeypatch, stdio_on):
url = "npx server --token sk-argv-secret",
headers_json = '{"API_KEY": "sk-env-secret"}',
)
- rows = asyncio.run(routes_mcp.list_mcp_servers(current_subject = "u", via_api_key = False))
+ rows = routes_mcp.list_mcp_servers(current_subject = "u", via_api_key = False)
assert [row.id for row in rows] == ["stdio1"]
assert rows[0].url == "npx server --token sk-argv-secret"
assert rows[0].headers == {"API_KEY": "sk-env-secret"}
diff --git a/studio/backend/tests/test_mcp_tool_read_off_event_loop.py b/studio/backend/tests/test_mcp_tool_read_off_event_loop.py
new file mode 100644
index 00000000000..9e6e7416056
--- /dev/null
+++ b/studio/backend/tests/test_mcp_tool_read_off_event_loop.py
@@ -0,0 +1,230 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Keep MCP server-list reads off the event loop."""
+
+from __future__ import annotations
+
+import asyncio
+import sys
+import threading
+from pathlib import Path
+
+from fastapi import HTTPException
+
+import core.inference.tools as tools
+import core.inference.mcp_client as mcp_client
+import routes.inference as inference_routes
+import routes.mcp_servers as mcp_routes
+from models.mcp_servers import McpServerUpdate
+from storage import mcp_servers_db
+
+_TESTS_DIR = str(Path(__file__).resolve().parent)
+if _TESTS_DIR not in sys.path:
+ sys.path.insert(0, _TESTS_DIR)
+
+# Reuse the token-count handler fixtures.
+from test_openai_auto_switch import ( # noqa: E402
+ MCP_TOOL_PAYLOAD,
+ _count_request,
+ _count_tokens_backend,
+ _enabled_mcp_server,
+)
+
+
+def test_the_server_list_is_read_off_the_event_loop_thread(monkeypatch):
+ threads: list[int] = []
+
+ def _list_servers():
+ threads.append(threading.get_ident())
+ return []
+
+ monkeypatch.setattr(tools.mcp_servers_db, "list_servers", _list_servers)
+
+ async def _drive():
+ assert await tools.get_enabled_mcp_tools() == []
+ return threading.get_ident()
+
+ loop_thread = asyncio.run(_drive())
+
+ assert threads, "the tool list never read the servers"
+ assert threads[0] != loop_thread, "list_servers ran on the event loop thread"
+
+
+def test_the_post_probe_re_read_stays_on_the_event_loop_thread(monkeypatch):
+ """The race-protection re-read must NOT leave the event loop.
+
+ It is the guard for the cache_tools / record_probe_failure writes right after it: awaiting
+ it lets an MCP edit invalidate the cache in between, and the stale probe result then
+ overwrites the invalidation and is served indefinitely.
+ """
+ server = {"id": "s1", "url": "http://127.0.0.1:1/mcp", "is_enabled": True, "use_oauth": False}
+ threads: list[int] = []
+
+ def _list_servers():
+ threads.append(threading.get_ident())
+ return [server]
+
+ async def _probe(**_kwargs):
+ return []
+
+ monkeypatch.setattr(tools.mcp_servers_db, "list_servers", _list_servers)
+ monkeypatch.setattr(tools, "stdio_mcp_enabled", lambda: True)
+ monkeypatch.setattr(tools, "get_cached_tools", lambda _id: None)
+ monkeypatch.setattr(tools, "in_failure_cooloff", lambda _id: False)
+ monkeypatch.setattr(tools, "list_tools_async", _probe)
+
+ async def _drive():
+ await tools.get_enabled_mcp_tools()
+ return threading.get_ident()
+
+ loop_thread = asyncio.run(_drive())
+
+ assert len(threads) == 2, f"expected the read and the post-probe re-read, got {len(threads)}"
+ assert threads[0] != loop_thread, "the first list_servers ran on the event loop thread"
+ assert threads[1] == loop_thread, "the post-probe re-read left the event loop thread"
+
+
+def test_the_token_count_reads_the_cached_tools_off_the_event_loop_thread(tmp_path, monkeypatch):
+ """Exercise the cache-only read through the token-count handler."""
+ _count_tokens_backend(monkeypatch, count = 1234, supports_tools = True)
+ _enabled_mcp_server(tmp_path, monkeypatch, cached = MCP_TOOL_PAYLOAD)
+
+ threads: list[int] = []
+ real_list_servers = mcp_servers_db.list_servers
+
+ def _list_servers():
+ threads.append(threading.get_ident())
+ return real_list_servers()
+
+ monkeypatch.setattr(mcp_servers_db, "list_servers", _list_servers)
+
+ payload = _count_request(
+ [{"role": "user", "content": "hello"}], mcp_enabled = True, enabled_tools = []
+ )
+ loop_thread = threading.get_ident()
+ asyncio.run(inference_routes.chat_count_tokens(payload, "tester"))
+
+ assert threads, "the count never read the enabled MCP servers"
+ assert loop_thread not in threads, "cached_mcp_tools read mcp_servers on the event loop thread"
+
+
+def test_the_cached_row_and_tools_are_one_snapshot_during_an_edit(monkeypatch):
+ state = {
+ "row": {
+ "id": "s1",
+ "display_name": "Saved",
+ "url": "https://old.example/mcp",
+ "headers_json": None,
+ "is_enabled": True,
+ "use_oauth": False,
+ },
+ "cache": {"s1": [{"name": "old_tool"}]},
+ }
+ row_read = threading.Event()
+ release_row = threading.Event()
+
+ def _list_servers():
+ row = dict(state["row"])
+ row_read.set()
+ assert release_row.wait(2), "the concurrent update never reached the row read"
+ return [row]
+
+ def _update_server(_server_id, changes):
+ state["row"].update(changes)
+ return True
+
+ def _invalidate(_server_id):
+ state["cache"].pop("s1", None)
+
+ monkeypatch.setattr(tools.mcp_servers_db, "list_servers", _list_servers)
+ monkeypatch.setattr(tools, "stdio_mcp_enabled", lambda: True)
+ monkeypatch.setattr(tools, "get_cached_tools", lambda server_id: state["cache"].get(server_id))
+ monkeypatch.setattr(tools, "in_failure_cooloff", lambda _server_id: False)
+ monkeypatch.setattr(
+ tools,
+ "_mcp_specs_for_server",
+ lambda server, payload: [(server["url"], payload[0]["name"])],
+ )
+ monkeypatch.setattr(
+ mcp_routes.mcp_servers_db, "get_server", lambda _server_id: dict(state["row"])
+ )
+ monkeypatch.setattr(mcp_routes.mcp_servers_db, "update_server", _update_server)
+ monkeypatch.setattr(mcp_routes, "invalidate_tool_cache", _invalidate)
+ monkeypatch.setattr(mcp_routes, "close_stdio_sessions", lambda *_args, **_kwargs: None)
+ monkeypatch.setattr(mcp_routes, "_row_to_response", lambda row: row)
+
+ async def _read_snapshot():
+ async with mcp_client.mcp_server_snapshot_guard():
+ return await asyncio.to_thread(tools.cached_mcp_tools)
+
+ async def _drive():
+ read = asyncio.create_task(_read_snapshot())
+ assert await asyncio.to_thread(row_read.wait, 2), "the cached read never started"
+ update = asyncio.create_task(
+ mcp_routes.update_mcp_server(
+ "s1",
+ McpServerUpdate(url = "https://new.example/mcp"),
+ current_subject = "u",
+ via_api_key = False,
+ )
+ )
+ release_row.set()
+ return await read, await update
+
+ (specs, complete), _response = asyncio.run(_drive())
+ assert complete is True
+ assert specs == [("https://old.example/mcp", "old_tool")]
+ assert state["row"]["url"] == "https://new.example/mcp"
+ assert state["cache"] == {}
+
+
+def test_queued_updates_recheck_the_stdio_api_key_gate(monkeypatch):
+ state = {
+ "row": {
+ "id": "s1",
+ "display_name": "Saved",
+ "url": "https://old.example/mcp",
+ "headers_json": None,
+ "is_enabled": True,
+ "use_oauth": False,
+ }
+ }
+
+ def _update_server(_server_id, changes):
+ state["row"].update(changes)
+ return True
+
+ monkeypatch.setattr(mcp_routes, "stdio_mcp_enabled", lambda: True)
+ monkeypatch.setattr(mcp_routes.mcp_servers_db, "get_server", lambda _id: dict(state["row"]))
+ monkeypatch.setattr(mcp_routes.mcp_servers_db, "update_server", _update_server)
+ monkeypatch.setattr(mcp_routes, "invalidate_tool_cache", lambda _server_id: None)
+ monkeypatch.setattr(mcp_routes, "close_stdio_sessions", lambda *_args, **_kwargs: None)
+ monkeypatch.setattr(mcp_routes, "_row_to_response", lambda row: row)
+
+ async def _drive():
+ async with mcp_client.mcp_server_snapshot_guard():
+ ui_update = asyncio.create_task(
+ mcp_routes.update_mcp_server(
+ "s1",
+ McpServerUpdate(url = "npx local-server"),
+ current_subject = "u",
+ via_api_key = False,
+ )
+ )
+ api_update = asyncio.create_task(
+ mcp_routes.update_mcp_server(
+ "s1",
+ McpServerUpdate(headers = {"API_KEY": "secret"}),
+ current_subject = "u",
+ via_api_key = True,
+ )
+ )
+ await asyncio.sleep(0)
+ return await asyncio.gather(ui_update, api_update, return_exceptions = True)
+
+ _ui_result, api_result = asyncio.run(_drive())
+ assert isinstance(api_result, HTTPException)
+ assert api_result.status_code == 403
+ assert state["row"]["url"] == "npx local-server"
+ assert state["row"]["headers_json"] is None
diff --git a/studio/backend/tests/test_media_keepwarm.py b/studio/backend/tests/test_media_keepwarm.py
index 792fb78b95f..27920496863 100644
--- a/studio/backend/tests/test_media_keepwarm.py
+++ b/studio/backend/tests/test_media_keepwarm.py
@@ -363,6 +363,21 @@ def test_a_ttl_raised_during_the_step_spares_the_next_teardown(media, monkeypatc
assert video.unloads == 0
+def test_a_request_landing_during_the_pin_read_is_not_unloaded_out_from_under(media, monkeypatch):
+ # A request may register _pending during the off-loop pin read, invalidating prior idleness.
+ monkeypatch.setattr(settings, "get_media_auto_unload_idle_seconds", lambda: 60)
+
+ def _pinned_while_a_request_lands(owner, *_args, **_kwargs):
+ mk._TRACKERS[owner].note_pending()
+ return False
+
+ monkeypatch.setattr(mk, "_user_pinned", _pinned_while_a_request_lands)
+ _step() # Both models are seen; only the TTL remains.
+ _step(*_BOTH)
+ assert media[arb.DIFFUSION].unloads == 0
+ assert media[arb.VIDEO].unloads == 0
+
+
def test_a_different_model_restarts_the_ttl(media, monkeypatch):
monkeypatch.setattr(settings, "get_media_auto_unload_idle_seconds", lambda: 60)
engine = media[arb.DIFFUSION]
diff --git a/studio/backend/tests/test_openai_auto_switch.py b/studio/backend/tests/test_openai_auto_switch.py
index 17b3efd0489..023a9e42537 100644
--- a/studio/backend/tests/test_openai_auto_switch.py
+++ b/studio/backend/tests/test_openai_auto_switch.py
@@ -724,6 +724,60 @@ def test_idle_loop_unloads_after_ttl_and_stashes_for_reload(monkeypatch):
assert stash is not None and stash[0] == "unsloth/Idle-GGUF" and stash[1] == "Q4_K_M"
+def test_a_request_landing_during_the_pin_read_is_not_unloaded_out_from_under(monkeypatch):
+ # A chat may register _pending during the off-loop pin read, invalidating prior idleness.
+ import time
+ from core.inference import llama_keepwarm as kw
+
+ monkeypatch.setattr(settings, "get_auto_unload_idle_seconds", lambda: 0.005)
+ monkeypatch.setattr(settings, "idle_unload_is_configured", lambda: True)
+ monkeypatch.setattr(kw, "_inflight", 0)
+ monkeypatch.setattr(kw, "_pending", 0)
+ monkeypatch.setattr(kw, "_last_active", time.monotonic() - 3600)
+ monkeypatch.setattr(kw, "_last_unloaded_model", None)
+
+ # Mark the interval after the first idle check and before the guarded pin read.
+ inside_the_unload_block = {"flag": False}
+ landed = []
+
+ def _keep_kv_marks_the_block():
+ inside_the_unload_block["flag"] = True
+ return False
+
+ def _api_only_while_a_request_lands():
+ if inside_the_unload_block["flag"]:
+ inside_the_unload_block["flag"] = False
+ kw._note_pending()
+ landed.append(1)
+ return False
+
+ monkeypatch.setattr(settings, "get_auto_unload_keep_kv", _keep_kv_marks_the_block)
+ monkeypatch.setattr(settings, "get_auto_unload_api_only", _api_only_while_a_request_lands)
+
+ unloads = []
+ backend = _FakeBackend("unsloth/Idle-GGUF", hf_variant = "Q4_K_M")
+ backend.unload_model = lambda: unloads.append(1)
+ monkeypatch.setattr(inference_route, "get_llama_cpp_backend", lambda: backend)
+
+ async def _drive():
+ task = asyncio.create_task(kw.idle_unload_loop(poll_seconds = 0.01))
+ deadline = time.monotonic() + 15.0
+ while time.monotonic() < deadline:
+ await asyncio.sleep(0.01)
+ if landed or unloads:
+ break
+ await asyncio.sleep(0.1)
+ task.cancel()
+ try:
+ await task
+ except asyncio.CancelledError:
+ pass
+
+ asyncio.run(_drive())
+ assert landed, "the tick never reached the guard's pin read, so the window was never hit"
+ assert unloads == [], "the loop freed the model out from under a request on the gate"
+
+
def test_idle_loop_deletes_saved_kv_when_unload_fails(monkeypatch, tmp_path):
import time
from core.inference import llama_keepwarm as kw
diff --git a/studio/backend/tests/test_provider_lookup_off_event_loop.py b/studio/backend/tests/test_provider_lookup_off_event_loop.py
new file mode 100644
index 00000000000..9df2a306bdb
--- /dev/null
+++ b/studio/backend/tests/test_provider_lookup_off_event_loop.py
@@ -0,0 +1,166 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Resolving a saved provider must not read providers from the event loop thread.
+
+Every chat routed to a saved external provider looks the row up, so on a stalled store
+that read parks the loop and the server stops answering anything, /api/liveness included.
+
+Asserts which thread the read ran on rather than timing it.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import threading
+from types import SimpleNamespace
+
+import pytest
+from fastapi import HTTPException
+
+import routes.inference as inference_routes
+import routes.provider_credentials as provider_credentials
+import routes.providers as provider_routes
+
+
+def _request():
+ async def is_disconnected():
+ return False
+
+ return SimpleNamespace(
+ headers = {},
+ state = SimpleNamespace(skip_api_monitor = True),
+ is_disconnected = is_disconnected,
+ )
+
+
+def _payload(external_model: str = "gpt-5.4"):
+ from models.inference import ChatCompletionRequest
+ return ChatCompletionRequest(
+ messages = [{"role": "user", "content": "what is 2+2?"}],
+ provider_id = "saved-1",
+ external_model = external_model,
+ stream = True,
+ )
+
+
+def test_the_saved_provider_row_is_read_off_the_event_loop_thread(monkeypatch):
+ threads: list[int] = []
+
+ def _get_provider(_provider_id):
+ threads.append(threading.get_ident())
+ return None
+
+ monkeypatch.setattr(inference_routes.providers_db, "get_provider", _get_provider)
+
+ # run_until_complete drives the loop on this thread.
+ loop_thread = threading.get_ident()
+ with pytest.raises(HTTPException) as excinfo:
+ asyncio.new_event_loop().run_until_complete(
+ inference_routes._proxy_to_external_provider(
+ _payload(), _request(), current_subject = "t"
+ )
+ )
+
+ assert excinfo.value.status_code == 404
+ assert threads, "the proxy never looked the saved provider up"
+ assert loop_thread not in threads, "the provider row was read on the event loop thread"
+
+
+def test_the_saved_provider_target_and_key_are_one_snapshot(monkeypatch):
+ state = {
+ "row": {
+ "id": "saved-1",
+ "provider_type": "openai",
+ "display_name": "Saved",
+ "base_url": "https://old.example/v1",
+ "is_enabled": True,
+ },
+ "key": "old-secret",
+ }
+ row_read = threading.Event()
+ update_done = threading.Event()
+ observed = []
+
+ def _get_provider(_provider_id):
+ row = dict(state["row"])
+ if not row_read.is_set():
+ row_read.set()
+ assert update_done.wait(2), "the concurrent update never completed"
+ return row
+
+ def _resolve_key(*_args, **_kwargs):
+ observed.append(state["key"])
+ return state["key"]
+
+ monkeypatch.setattr(inference_routes.providers_db, "get_provider", _get_provider)
+ monkeypatch.setattr(inference_routes, "resolve_provider_api_key_or_400", _resolve_key)
+
+ async def _update():
+ assert await asyncio.to_thread(row_read.wait, 2), "the saved row was never read"
+ async with provider_credentials.provider_config_guard("saved-1"):
+ state["row"]["base_url"] = "https://new.example/v1"
+ state["key"] = "new-secret"
+ update_done.set()
+
+ async def _drive():
+ proxy = asyncio.create_task(
+ inference_routes._proxy_to_external_provider(
+ _payload(external_model = "default"), _request(), current_subject = "t"
+ )
+ )
+ update = asyncio.create_task(_update())
+ with pytest.raises(HTTPException) as excinfo:
+ await proxy
+ assert excinfo.value.status_code == 409
+ await update
+
+ asyncio.run(_drive())
+ assert observed == []
+ assert state["row"]["base_url"] == "https://new.example/v1"
+ assert state["key"] == "new-secret"
+
+
+ "handler",
+ [
+ provider_routes.update_provider_config,
+ provider_routes.migrate_provider_api_key,
+ provider_routes.delete_provider_config,
+ ],
+)
+def test_provider_mutations_share_the_saved_snapshot_guard(handler):
+ assert getattr(handler, "_provider_config_serialized", False)
+
+
+def _container_body():
+ from models.inference import OpenAIContainerRequest
+ return OpenAIContainerRequest(provider_id = "saved-1")
+
+
+def test_the_container_resolver_reads_on_the_event_loop_thread(monkeypatch):
+ """The container routes resolve the row and the credential as one snapshot.
+
+ _resolve_openai_cloud_client reads the provider row for the base URL and then reads the
+ saved key. Run in a worker, an edit landing between the two pairs the old base URL with
+ the new key, so the routes call it on the loop where nothing interleaves.
+ """
+ threads: list[int] = []
+
+ def _get_provider(_provider_id):
+ threads.append(threading.get_ident())
+ return None
+
+ monkeypatch.setattr(inference_routes.providers_db, "get_provider", _get_provider)
+
+ loop_thread = threading.get_ident()
+ with pytest.raises(HTTPException) as excinfo:
+ asyncio.new_event_loop().run_until_complete(
+ inference_routes.list_openai_containers(
+ _container_body(), _request(), current_subject = "t"
+ )
+ )
+
+ assert excinfo.value.status_code == 404
+ assert threads, "the container route never looked the saved provider up"
+ assert threads[0] == loop_thread, "the container resolver ran off the event loop thread"