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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Prevent shared preview loads from evicting the active Studio model (#7104)
Nilay58c721de6b1c
diff --git a/studio/backend/assets/preview_page.html b/studio/backend/assets/preview_page.htmlindex 36483a824cf..7f3bff49da6 100644--- a/studio/backend/assets/preview_page.html+++ b/studio/backend/assets/preview_page.html@@ -143,6 +143,21 @@margin-top: 16px;line-height: 1.75;}+ .error {+ color: #b42318;+ border: 1px solid #fecdca;+ border-radius: 12px;+ background: #fef3f2;+ padding: 10px 12px;+ line-height: 1.5;+ }+ @media (prefers-color-scheme: dark) {+ .error {+ color: #fda29b;+ border-color: #7a271a;+ background: #2d1716;+ }+ }.dots {display: inline-flex;gap: 5px;@@ -318,6 +333,33 @@down();return d;}+ function showError(out, status, body) {+ out.classList.add("error");+ // FastAPI wraps errors as {detail: ...}; detail may be a string or a+ // structured {error: {message}} envelope, so read the string form.+ let detailText = "";+ try {+ const parsed = JSON.parse(body);+ const detail = parsed.detail;+ detailText =+ (typeof detail === "string" ? detail : detail?.error?.message) ||+ parsed.error?.message ||+ "";+ } catch (_) {+ if (body) detailText = body.slice(0, 300);+ }+ if (status === 503) {+ // 503 covers both "a different model is loaded" (unload it) and a transient+ // "busy, retry" state; show the server's message so a busy response isn't misreported.+ out.textContent =+ detailText ||+ "Studio is currently using another model. To chat with this preview, unload that model in Studio, then try again.";+ return;+ }+ out.textContent =+ "Couldn’t send your message: " ++ (detailText || "Something went wrong. Please try again.");+ }async function send() {// One path for button + Enter; ignore while a request is in flight.if (btn.disabled) return;@@ -343,8 +385,7 @@}),});if (!r.ok) {- out.textContent =- "Error " + r.status + ": " + (await r.text()).slice(0, 300);+ showError(out, r.status, await r.text());msgs.pop();input.value = content; // restore the prompt so the user can retryautosize();diff --git a/studio/backend/core/inference/gpu_arbiter.py b/studio/backend/core/inference/gpu_arbiter.pyindex ca18540b882..f8defe92b3e 100644--- a/studio/backend/core/inference/gpu_arbiter.py+++ b/studio/backend/core/inference/gpu_arbiter.py@@ -67,7 +67,20 @@ def _evict_video() -> None:_EVICTORS = {CHAT: _evict_chat, DIFFUSION: _evict_diffusion, VIDEO: _evict_video}-def acquire_for(owner: str, register: Optional[Callable[[], Any]] = None) -> Any:+class GpuOwnerBusyError(RuntimeError):+ """Raised when an ownership transfer is configured to refuse eviction."""++ def __init__(self, owner: str):+ self.owner = owner+ super().__init__(f"GPU is owned by {owner}")+++def acquire_for(+ owner: str,+ register: Optional[Callable[[], Any]] = None,+ *,+ allow_evict: bool = True,+) -> Any:"""Make ``owner`` the sole GPU owner, evicting the other if it holds it.``register``, if given, runs under the arbiter lock right after ownership transfers and its@@ -81,6 +94,8 @@ def acquire_for(owner: str, register: Optional[Callable[[], Any]] = None) -> Anyraise ValueError(f"unknown GPU owner: {owner!r}")with _lock:if _owner is not None and _owner != owner:+ if not allow_evict:+ raise GpuOwnerBusyError(_owner)logger.info("gpu_arbiter: evicting %s for %s", _owner, owner)_EVICTORS[_owner]()_owner = ownerdiff --git a/studio/backend/core/inference/llama_keepwarm.py b/studio/backend/core/inference/llama_keepwarm.pyindex 0470e84a0d6..7abbcb1149b 100644--- a/studio/backend/core/inference/llama_keepwarm.py+++ b/studio/backend/core/inference/llama_keepwarm.py@@ -16,6 +16,7 @@ from __future__ import annotationsimport asyncioimport contextlib+import contextvarsimport threadingimport timefrom pathlib import Path@@ -26,29 +27,43 @@ logger = get_logger(__name__)_lock = threading.Lock()_inflight = 0-# Requests blocked on the unload gate but not yet counted in _inflight: the idle-# loop must not unload while one is waiting (it would unload out from under it).+# Subset of _inflight that is /p/ preview traffic.+_preview_inflight = 0+# Blocked on the unload gate, not yet in _inflight: the idle loop must not unload while one waits._pending = 0+# Subset of _pending that is /p/ preview traffic, so the busy guard can tell a queued+# Studio request from a queued preview.+_preview_pending = 0+# Non-preview requests past FastAPI auth at the local-inference choke point. The preview+# busy guard counts these, not raw _inflight, so a pre-auth/unauthenticated tracked request+# that never touches the model can't starve public previews.+_admitted_inference = 0+# Bumped when a preview swap loads a new checkpoint. A non-preview request captures it before+# the lifecycle gate; if it advanced by the time the gate is held, a preview swapped the model+# out from under it and the request is rejected (see the middleware).+_preview_swap_generation = 0+# Non-zero while a preview swap is loading (before it takes the lifecycle gate until after it+# releases). Catches a request that captures the counter AFTER the bump but BEFORE the gate+# releases: the middleware snapshots this flag at entry and rejects if a swap was in progress.+_preview_swap_inflight = 0_last_active = time.monotonic()-# The (id, quant) idle-unload last freed, so an alias/unknown request that would-# otherwise 503 against an empty backend can reload it (set on unload, cleared on-# reload). Storing the quant means the reload restores the exact freed variant.+# The (id, quant) idle-unload last freed, so an alias/unknown request that would otherwise+# 503 against an empty backend can reload it (set on unload, cleared on reload). The quant+# lets the reload restore the exact freed variant._last_unloaded_model = None# Slot KV manifest saved by the idle unload; whoever pops it owns deleting its files._kv_resume = None-# Guards inflight bumps against the idle-check-then-unload race, and blocks new-# inference from starting mid-swap. Process-wide, not per-loop: the backend slot is-# shared across every event loop in the process, so a per-loop gate would let a-# request on loop B start inference while a swap on loop A tears the model down.+# Guards inflight bumps against the idle-check-then-unload race and blocks new inference+# mid-swap. Process-wide, not per-loop: the backend slot is shared across every event loop,+# so a per-loop gate would let a request on loop B start while a swap on loop A tears it down._lifecycle_lock = threading.Lock()@contextlib.asynccontextmanagerasync def _unload_gate():- # Acquire off the loop: non-blocking first (the common uncontended case), else- # poll a non-blocking acquire off a short sleep. Polling keeps the wait off this- # loop AND cancellation-safe -- a cancel lands during the sleep, when the gate is- # not held, so it never leaks (mirrors the auto-switch swap gate).+ # Non-blocking acquire first (common uncontended case), else poll off a short sleep.+ # Polling keeps the wait off this loop AND cancellation-safe: a cancel lands during the+ # sleep, when the gate is not held, so it never leaks (mirrors the auto-switch swap gate).while not _lifecycle_lock.acquire(blocking = False):await asyncio.sleep(0.02)try:@@ -77,50 +92,76 @@ _INFERENCE_SUFFIXES = ("/video/generate", # /api/inference/video/generate)+# Tracked above (they hold the GPU, so the in-flight count must see them) but served by the+# diffusion/video engines, never the llama slot. A successful one therefore did NOT run against+# the resident chat model and must not adopt it for Studio: clearing the marker on an image or+# video generation would leave a still-preview-owned checkpoint looking Studio-owned, and the+# next preview for a different checkpoint would 503 on the slot guard.+_NON_LLM_SLOT_SUFFIXES = (+ "/images/generate",+ "/images/generations",+ "/video/generate",+)+++def _is_preview_path(path: str) -> bool:+ # Public checkpoint preview delegates to the chat handler on the same backend,+ # so protect it from idle unload.+ return path.startswith("/p/") and path.endswith("/v1/chat/completions")+def _is_inference_path(path: str) -> bool:if path.startswith(_INFERENCE_PREFIXES) and path.endswith(_INFERENCE_SUFFIXES):return True- # Public checkpoint preview (/p/{run}/v1/chat/completions) delegates to the- # chat handler and streams from the same backend, so protect it from idle unload.- return path.startswith("/p/") and path.endswith("/v1/chat/completions")+ return _is_preview_path(path)-def _note_pending() -> None:- global _pending+def _note_pending(is_preview: bool = False) -> None:+ global _pending, _preview_pendingwith _lock:_pending += 1+ if is_preview:+ _preview_pending += 1-def _note_unpending() -> None:- global _pending+def _note_unpending(is_preview: bool = False) -> None:+ global _pending, _preview_pendingwith _lock:_pending = max(0, _pending - 1)+ if is_preview:+ _preview_pending = max(0, _preview_pending - 1)-def _note_start() -> None:- # Do not stamp _last_active here: while _inflight > 0 the model is already- # protected (see _is_idle), and stamping on start lets an external-provider- # request that is later untracked still reset the local idle timer.- global _inflight, _pending+def _note_start(is_preview: bool = False) -> None:+ # Don't stamp _last_active here: while _inflight > 0 the model is already protected+ # (see _is_idle), and stamping on start would let a later-untracked external-provider+ # request still reset the local idle timer.+ global _inflight, _pending, _preview_inflight, _preview_pendingwith _lock:_pending = max(0, _pending - 1)_inflight += 1+ if is_preview:+ _preview_pending = max(0, _preview_pending - 1)+ _preview_inflight += 1-def _note_end() -> None:- global _inflight, _last_active+def _note_end(is_preview: bool = False) -> None:+ global _inflight, _last_active, _preview_inflightwith _lock:_inflight = max(0, _inflight - 1)_last_active = time.monotonic()+ if is_preview:+ _preview_inflight = max(0, _preview_inflight - 1)-def _note_untracked_end() -> None:- # Drop a request that never used the local GGUF without stamping local- # activity, so periodic external-provider traffic can't keep the model warm.- global _inflight+def _note_untracked_end(is_preview: bool = False) -> None:+ # Drop a request that never used the local GGUF without stamping activity, so+ # external-provider traffic can't keep the model warm.+ global _inflight, _preview_inflightwith _lock:_inflight = max(0, _inflight - 1)+ if is_preview:+ _preview_inflight = max(0, _preview_inflight - 1)def _is_idle(ttl_seconds: float) -> bool:@@ -140,11 +181,10 @@ def other_inference_request_count() -> int:"""Tracked inference requests other than the current route call.- The middleware counts OpenAI-compatible requests before route code runs, so- the caller is excluded by default. Idle-unload counts pending waiters too (a- swap holding the gate would unload out from under them). The swap guard passes- include_pending=False: a pending request is blocked in the middleware and has- not started inference, so it can't be the request a swap would interrupt.+ The middleware counts requests before route code runs, so the caller is excluded by+ default. Idle-unload counts pending waiters too (a swap holding the gate would unload+ out from under them); the swap guard passes include_pending=False since a pending+ request is blocked in the middleware and can't be the one a swap would interrupt."""with _lock:active = _inflight@@ -153,20 +193,244 @@ def other_inference_request_count(return max(0, active) + (_pending if include_pending else 0)-# Set on the ASGI scope by a route that proved this request won't touch-# llama.cpp (e.g. it proxied to an external provider), so the keep-warm count-# excludes it and the middleware skips its own end-decrement.+def other_preview_inflight_count(current_request_counted: bool = True) -> int:+ """Preview (/p/) requests in flight other than the current route call."""+ with _lock:+ active = _preview_inflight+ if current_request_counted and active > 0:+ active -= 1+ return max(0, active)+++def other_admitted_inference_count() -> int:+ """Non-preview requests admitted to local inference (passed auth, reached the+ _maybe_auto_switch_model / generate_stream choke point). The preview busy guard counts+ these instead of raw _inflight, so a pre-auth/unauthenticated tracked request can't+ block a preview. The current request is always a preview (never admitted), so no+ self-exclusion is needed."""+ with _lock:+ return _admitted_inference+++def other_non_preview_pending_count() -> int:+ """Non-preview requests queued on the lifecycle gate (_pending, not yet in flight).+ The preview swap guard must count these: a queued Studio request would otherwise start+ against the model a preview swapped in while it waited. The current request is a preview+ already in flight, so not in _pending."""+ with _lock:+ return max(0, _pending - _preview_pending)+++def note_preview_swap() -> None:+ """Record that a preview swap loaded a new checkpoint. A non-preview request blocked on+ the lifecycle gate through the swap sees this counter advance and is rejected rather than+ running against the swapped-in preview checkpoint."""+ global _preview_swap_generation+ with _lock:+ _preview_swap_generation += 1+++def _preview_swap_gen() -> int:+ with _lock:+ return _preview_swap_generation+++def note_preview_swap_begin() -> None:+ """Mark a preview swap in progress. Call before taking the lifecycle gate to load, pair+ with note_preview_swap_end() after the gate releases, so a non-preview request arriving+ at any point during the swap (including after the counter bumps but before the gate+ releases) is rejected."""+ global _preview_swap_inflight+ with _lock:+ _preview_swap_inflight += 1+++def note_preview_swap_end() -> None:+ global _preview_swap_inflight+ with _lock:+ _preview_swap_inflight = max(0, _preview_swap_inflight - 1)+++def _preview_swap_active() -> bool:+ with _lock:+ return _preview_swap_inflight > 0+++def preview_swapped_since_entry(scope) -> bool:+ """True if a preview swap ran, or is running, since this request entered the middleware.+ Extends the gate-wait reject flag to catch a non-preview request that passed the gate+ BEFORE a swap (so it never set _PREVIEW_SWAP_REJECT_SCOPE_KEY) but is still pre-admission+ when a preview swaps the model out from under it. entry_gen is None only when the+ middleware never snapshotted it (non-dict/non-inference scope), so fall back to the+ swap-in-progress flag alone."""+ if not isinstance(scope, dict):+ return False+ # A preview carries its own ownership and may swap the model in (load_model_for_preview+ # bumps the generation before serving its own chat), so it must never reject itself.+ # Mirrors the middleware, which only flags non-preview scopes.+ if _is_preview_path(scope.get("path") or ""):+ return False+ if scope.get(_PREVIEW_SWAP_REJECT_SCOPE_KEY):+ return True+ entry_gen = scope.get(_SWAP_GEN_AT_ENTRY_KEY)+ with _lock:+ if _preview_swap_inflight > 0:+ return True+ return entry_gen is not None and _preview_swap_generation != entry_gen+++def _claim_non_preview_slot() -> None:+ """A non-preview request that ran against the local model (2xx) adopts it for Studio,+ so clear preview ownership -- a later preview for another checkpoint then 503s instead+ of swapping the model out from under an active Studio conversation. Claiming on success+ (not before) means a per-route-rejected request never strands a preview-owned model.+ Lazily imported: routes.inference imports this module."""+ try:+ from routes.inference import _set_preview_resident+ _set_preview_resident(None)+ except Exception as exc: # never let ownership bookkeeping break a response+ logger.debug("preview-slot claim on completion failed: %s", exc)+++# Set on the scope by a route that proved this request won't touch llama.cpp (e.g. it+# proxied to an external provider), so the keep-warm count excludes it and the middleware+# skips its end-decrement._UNTRACKED_SCOPE_KEY = "_unsloth_keepwarm_untracked"+# Set after middleware admission so the preview route can distinguish a real tracked+# request from direct unit/helper calls that have no counters to move.+_TRACKED_SCOPE_KEY = "_unsloth_keepwarm_tracked"++# A preview route waits on its own serializer after middleware admission. While queued it+# must be pending, not active: a Studio swap holds the lifecycle gate while draining active+# requests, and the queued preview needs that same gate after it gets the serializer.+_PREVIEW_SERIALIZER_WAIT_SCOPE_KEY = "_unsloth_keepwarm_preview_serializer_wait"++# Set by the middleware on a non-preview scope when a preview swap advanced the counter+# while it waited on the gate; _maybe_auto_switch_model then rejects it rather than serve+# the swapped-in checkpoint. Deferred to the route (not a middleware 503) so an external-+# provider request that untracks and returns before that check is never rejected.+_PREVIEW_SWAP_REJECT_SCOPE_KEY = "_unsloth_keepwarm_preview_swap_reject"++# The swap generation snapshot at middleware entry, on the scope so local-inference+# admission can also reject a request that passed the gate BEFORE a swap (never got the+# gate-wait reject flag) but is still pre-auth when a preview swaps in.+_SWAP_GEN_AT_ENTRY_KEY = "_unsloth_keepwarm_swap_gen_at_entry"++# Set on the scope by a streaming route that failed after its 200 headers (an SSE error+# chunk, a passthrough relaying a mid-stream error while HTTP stays 200). The claim keys+# off HTTP status alone, so without this a failed stream would adopt a preview-owned model+# for Studio; the claim skips a flagged response.+_RESPONSE_FAILED_SCOPE_KEY = "_unsloth_keepwarm_response_failed"+++def mark_response_failed(scope) -> None:+ """Flag a response that returned 2xx headers but then failed, so the middleware doesn't+ treat it as a successful non-preview completion and claim the slot for Studio. Safe to+ call repeatedly; a no-op on a non-dict scope."""+ if isinstance(scope, dict):+ scope[_RESPONSE_FAILED_SCOPE_KEY] = True+++# The current request's ASGI scope, set by the middleware so deep streaming error+# helpers can flag a failure without threading the scope through every yield site. The+# middleware shares the streaming body's task, so the contextvar reaches those generators.+_current_response_scope: contextvars.ContextVar = contextvars.ContextVar(+ "_unsloth_current_response_scope", default = None+)+++def set_current_response_scope(scope) -> None:+ _current_response_scope.set(scope if isinstance(scope, dict) else None)+++def mark_current_response_failed() -> None:+ """Flag the current response failed via the contextvar the middleware set, so an+ OpenAI-family streaming error emitted deep in a generator (no direct scope handle)+ still prevents the successful-response slot claim."""+ mark_response_failed(_current_response_scope.get())+def untrack_current_request(scope) -> None:- """Drop this request from the in-flight count once the route knows it won't- use the local GGUF, so unrelated external-provider traffic can't trip the- swap busy guard. Idempotent; the middleware then skips its end-decrement."""+ """Drop this request from the in-flight count once the route knows it won't use the+ local GGUF, so external-provider traffic can't trip the swap busy guard. Idempotent;+ the middleware then skips its end-decrement."""if not isinstance(scope, dict) or scope.get(_UNTRACKED_SCOPE_KEY):returnscope[_UNTRACKED_SCOPE_KEY] = True- _note_untracked_end()+ # Keep the preview subset aligned with _inflight: a /p/ request must drop from both+ # counters, or the busy guard sees phantom traffic.+ _note_untracked_end(_is_preview_path(scope.get("path") or ""))+++_ADMITTED_SCOPE_KEY = "_unsloth_keepwarm_admitted"+++def note_admitted_inference(scope) -> None:+ """Mark a non-preview request as admitted local inference (passed auth, reached the+ _maybe_auto_switch_model / generate_stream choke point), so the preview busy guard+ counts it. Idempotent per scope; a no-op for preview (/p/) paths (own ownership) and+ non-dict scopes."""+ global _admitted_inference+ if not isinstance(scope, dict) or scope.get(_ADMITTED_SCOPE_KEY):+ return+ if _is_preview_path(scope.get("path") or ""):+ return+ scope[_ADMITTED_SCOPE_KEY] = True+ with _lock:+ _admitted_inference += 1+++def _note_admitted_end() -> None:+ global _admitted_inference+ with _lock:+ _admitted_inference = max(0, _admitted_inference - 1)+++def begin_preview_serializer_wait(scope) -> bool:+ """Move a tracked preview from active to pending while it waits on the route lock."""+ global _inflight, _pending, _preview_inflight, _preview_pending+ if (+ not isinstance(scope, dict)+ or not _is_preview_path(scope.get("path") or "")+ or not scope.get(_TRACKED_SCOPE_KEY)+ or scope.get(_UNTRACKED_SCOPE_KEY)+ or scope.get(_PREVIEW_SERIALIZER_WAIT_SCOPE_KEY)+ ):+ return False+ with _lock:+ scope[_PREVIEW_SERIALIZER_WAIT_SCOPE_KEY] = True+ _inflight = max(0, _inflight - 1)+ _preview_inflight = max(0, _preview_inflight - 1)+ _pending += 1+ _preview_pending += 1+ return True+++async def resume_preview_after_serializer(scope) -> None:+ """Re-admit a serialized preview under the lifecycle gate before it touches the model."""+ if not isinstance(scope, dict) or not scope.get(_PREVIEW_SERIALIZER_WAIT_SCOPE_KEY):+ return+ try:+ async with _unload_gate():+ if not scope.get(_PREVIEW_SERIALIZER_WAIT_SCOPE_KEY):+ return+ _note_start(is_preview = True)+ scope.pop(_PREVIEW_SERIALIZER_WAIT_SCOPE_KEY, None)+ except BaseException:+ cancel_preview_serializer_wait(scope)+ raise+++def cancel_preview_serializer_wait(scope) -> None:+ """Balance a preview cancelled before it can be re-admitted after serialization."""+ if not isinstance(scope, dict) or not scope.get(_PREVIEW_SERIALIZER_WAIT_SCOPE_KEY):+ return+ scope.pop(_PREVIEW_SERIALIZER_WAIT_SCOPE_KEY, None)+ _note_unpending(is_preview = True)+ # Middleware must not run the normal active-request decrement after this pending+ # request was removed, or it would stamp activity for a preview that never ran.+ scope[_UNTRACKED_SCOPE_KEY] = Truedef inference_lifecycle_gate():@@ -189,10 +453,10 @@ def note_model_loaded(backend = None) -> None:def note_model_unloaded() -> None:- """Record a deliberate (user/API) unload: drop any idle reload stash so the next- request can't resurrect the just-unloaded model. The idle loop unloads via the- backend directly and then stashes the freed model for an alias reload; an- explicit unload instead means "stay unloaded", so it must not stamp activity."""+ """Record a deliberate (user/API) unload: drop any idle reload stash so the next request+ can't resurrect the just-unloaded model. Unlike the idle loop (which stashes the freed+ model for an alias reload), an explicit unload means "stay unloaded", so it must not+ stamp activity."""_set_last_unloaded(None)@@ -345,22 +609,34 @@ class LlamaKeepWarmMiddleware:if not chat_tracked and media_owner is None:await self.app(scope, receive, send)return- # Always track in-flight on inference paths, even when the feature is off,- # so a stream that starts before idle-unload is enabled can't be unloaded- # mid-response if the operator turns it on during that stream. Counting is- # cheap and invisible to clients (the response is proxied unchanged).- # Mark pending before the gate so the idle loop (which holds the gate while- # unloading) can't free the model while this request is waiting to start.+ # Always track in-flight on inference paths, even when the feature is off, so a+ # stream that starts before idle-unload is enabled can't be unloaded mid-response if+ # the operator turns it on. Mark pending before the gate so the idle loop (which+ # holds the gate while unloading) can't free the model while this request waits.+ is_preview = _is_preview_path(path)if chat_tracked:- _note_pending()+ set_current_response_scope(scope)+ _note_pending(is_preview)+ swap_gen_at_entry = _preview_swap_gen()+ swap_active_at_entry = _preview_swap_active()+ if isinstance(scope, dict):+ scope[_SWAP_GEN_AT_ENTRY_KEY] = swap_gen_at_entrystarted = Falsetry:async with _unload_gate():- _note_start()+ _note_start(is_preview)started = True+ if isinstance(scope, dict):+ scope[_TRACKED_SCOPE_KEY] = True+ if (+ not is_preview+ and (_preview_swap_gen() != swap_gen_at_entry or swap_active_at_entry)+ and isinstance(scope, dict)+ ):+ scope[_PREVIEW_SWAP_REJECT_SCOPE_KEY] = Truefinally:if not started:- _note_unpending()+ _note_unpending(is_preview)if media_owner is not None:try:await media_keepwarm.begin_request(media_owner)@@ -371,41 +647,84 @@ class LlamaKeepWarmMiddleware:# stays positive for the life of the process: chat idle unload would never# fire again and every training start would see an inference request.if chat_tracked:- _note_untracked_end()+ _note_untracked_end(is_preview)raiseended = {"done": False}status = {"code": None}+ # Set once the terminal body frame (more_body False) is sent: only a response that+ # completed cleanly adopts the model for Studio. A client disconnect after the 200+ # headers raises before that frame (an OSError that _SameTaskStreamingResponse turns+ # into a CancelledError for the body generator, which finishes the monitor and+ # re-raises without flagging the scope), so a cancelled stream never claims the slot.+ completed = {"done": False}def _finish() -> None:# A route that untracked itself already decremented; don't double-count.if ended["done"]:returnended["done"] = True- # Before the untracked early return below: that marks a request as not using the- # local GGUF, which says nothing about the media backend it was counted against.+ code = status["code"]if media_owner is not None:- media_keepwarm.end_request(media_owner, counted = status["code"] not in (401, 403))- if not chat_tracked or scope.get(_UNTRACKED_SCOPE_KEY):+ media_keepwarm.end_request(media_owner, counted = code not in (401, 403))+ if not chat_tracked:+ return+ # A non-preview 2xx that completed cleanly ran against the local model and adopts+ # it for Studio, so clear preview ownership. Skip on a per-route 4xx/5xx (never+ # strand a preview-owned model), count_tokens (tokenize only), a failed/cancelled+ # stream, and an untracked balance-only request. Claim BEFORE dropping the admitted+ # count (and the in-flight count) below: load_model_for_preview's busy guard keys on+ # other_admitted_inference_count(), so decrementing first opens a window where a+ # preview sees no admitted Studio traffic and a still-preview-owned slot, swaps in,+ # and this delayed claim then clears the wrong checkpoint; while still counted the+ # guard refuses that swap.+ if (+ not is_preview+ and isinstance(code, int)+ and 200 <= code < 300+ and completed["done"]+ # Both count endpoints (/messages/count_tokens, /chat/count_tokens).+ and not path.endswith("count_tokens")+ # Image/video generation runs on the diffusion/video engine, not the llama slot.+ and not path.endswith(_NON_LLM_SLOT_SUFFIXES)+ and not scope.get(_RESPONSE_FAILED_SCOPE_KEY)+ and not scope.get(_UNTRACKED_SCOPE_KEY)+ ):+ _claim_non_preview_slot()+ # Balance note_admitted_inference here (runs in the finally, so it can't leak on any+ # exit path), after the claim above and before the untracked / 401 early returns.+ if scope.get(_ADMITTED_SCOPE_KEY):+ _note_admitted_end()+ if scope.get(_UNTRACKED_SCOPE_KEY):+ return+ # This middleware runs before FastAPI auth, so a 401/403 reaches here without+ # touching llama.cpp. Balance _note_start but do NOT stamp activity, or+ # repeated unauthenticated probes would keep the model warm forever.+ if code in (401, 403):+ _note_untracked_end(is_preview)return- # This middleware runs before FastAPI auth, so a 401/403 reaches here- # without ever touching llama.cpp. Decrement the in-flight count (to- # balance _note_start) but do NOT stamp activity, or repeated- # unauthenticated probes on an exposed server would keep the model warm- # and never let idle-unload free VRAM.- if status["code"] in (401, 403):- _note_untracked_end()- else:- _note_end()+ # A preview that did not return 2xx never served tokens (429, bad-token 404,+ # body-validation 4xx all exit before load_model_for_preview). Drop it like+ # an untracked end so rejected public POSTs can't refresh the idle timer and+ # pin the model in VRAM (a loaded-then-failed preview already stamped at load).+ if is_preview and not (isinstance(code, int) and 200 <= code < 300):+ _note_untracked_end(is_preview)+ return+ _note_end(is_preview)async def send_wrapper(message):if message.get("type") == "http.response.start":status["code"] = message.get("status")- # Final body frame marks the end of a (possibly streaming) response.- elif message.get("type") == "http.response.body" and not message.get(+ # Terminal body frame marks a clean end of a (possibly streaming) response.+ is_terminal = message.get("type") == "http.response.body" and not message.get("more_body", False- ):- _finish()+ )await send(message)+ # Claim only after the terminal frame is actually delivered: a client that+ # disconnects on the final write makes send() above raise, so completed stays+ # False and the cut-off stream is not mistaken for a clean completion.+ if is_terminal:+ completed["done"] = True+ _finish()try:await self.app(scope, receive, send_wrapper)diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 375b8190822..ea65ffcde00 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -667,6 +667,10 @@ def _openai_stream_error_chunk(exc) -> dict:def _openai_stream_error_sse(error: dict) -> str:+ # Every OpenAI-family streaming error flows through here after the 200 headers, so flag+ # the response failed: the middleware must not claim a preview-owned model on a failed stream.+ from core.inference.llama_keepwarm import mark_current_response_failed+ mark_current_response_failed()return f"data: {json.dumps(error)}\n\ndata: [DONE]\n\n"@@ -945,6 +949,12 @@ def _apply_measured_overflow_truncation(body: dict, err_text: str, policy: str)def _anthropic_stream_error_event(exc, *, force: bool = False):"""Return an Anthropic in-band stream error event when one is useful."""+ # Called only from stream except-handlers after the 200 headers, so flag failed up front+ # even when we return None (the caller then swallows and finishes normally): the middleware+ # must not claim a preview-owned model on a failed stream.+ from core.inference.llama_keepwarm import mark_current_response_failed++ mark_current_response_failed()_cls = _classify_llama_generation_error(exc)if _cls is None and not force:return None@@ -1804,10 +1814,17 @@ def _openai_admission_cancelled_error(async def _raise_if_openai_admission_cancelled(reservation: LlamaAdmissionReservation, *, request: Optional[Request], cancel_event) -> None:+ # Cancelled before leasing an upstream, so the model was never used. A streaming caller+ # has flushed the 200 headers and its `except LlamaAdmissionCancelled` just returns, so+ # flag failed: the middleware must not treat that empty 200 as a successful generation and+ # claim a preview-owned slot. Harmless for non-streaming callers (they surface a non-2xx).+ from core.inference.llama_keepwarm import mark_current_response_failedif reservation.is_cancelled:+ mark_current_response_failed()raise _openai_admission_cancelled_error(reservation)if await _preheader_cancelled(cancel_event, request):reservation.cancel()+ mark_current_response_failed()raise _openai_admission_cancelled_error(reservation)@@ -2302,6 +2319,13 @@ async def _preheader_cancelled(cancel_event = None, request: Optional[Request] =return False+def _mark_cancelled_json_response_failed(request: Request, cancel_event: threading.Event) -> None:+ """Keep a partial JSON response from claiming a preview-owned resident model."""+ if cancel_event.is_set():+ from core.inference.llama_keepwarm import mark_response_failed+ mark_response_failed(getattr(request, "scope", None))++async def _wait_preheader_cancel(cancel_event = None, request: Optional[Request] = None) -> None:while not await _preheader_cancelled(cancel_event, request):await asyncio.sleep(0.05)@@ -2316,7 +2340,16 @@ async def _send_stream_with_preheader_cancel() -> Optional[httpx.Response]:if cancel_event is None and request is None:return await client.send(req, stream = True)+ from core.inference.llama_keepwarm import mark_response_failed++ def _mark_preheader_cancel() -> None:+ # Cancelled before the upstream response started: the caller ends its 200+ # stream without serving tokens, so flag it failed or the middleware claims+ # a preview-owned slot for a request that never used the model.+ mark_response_failed(getattr(request, "scope", None))+if await _preheader_cancelled(cancel_event, request):+ _mark_preheader_cancel()return Nonesend_task = asyncio.create_task(client.send(req, stream = True))@@ -2351,6 +2384,7 @@ async def _send_stream_with_preheader_cancel(return await send_taskawait _stop_send_task()+ _mark_preheader_cancel()return Noneexcept asyncio.CancelledError:if mark_cancel_on_cancel and cancel_event is not None:@@ -4761,9 +4795,38 @@ def _monitor_openai_sse_event(monitor_id: Optional[str],event: bytes,context_length = None,-) -> None:+) -> Optional[str]:+ # Returns "error" if any line was an upstream error payload (an HTTP-200 SSE+ # `data: {"error": ...}`), so a relay caller can mark the response failed and stop the+ # keep-warm middleware claiming the slot on a failed stream.+ status = Nonefor line in event.decode("utf-8", errors = "ignore").splitlines():- _monitor_openai_sse_line(monitor_id, line.strip(), context_length)+ stripped = line.strip()+ result = _monitor_openai_sse_line(monitor_id, stripped, context_length)+ if result is None and not monitor_id:+ # Monitoring off returns early above; the relay still needs the+ # error/done verdict or a failed stream claims the preview slot.+ result = _sse_line_stream_status(stripped)+ if result == "error":+ status = "error"+ elif result == "done" and status is None:+ status = "done"+ return status+++def _sse_line_stream_status(raw_line: str) -> Optional[str]:+ if not raw_line.startswith("data:"):+ return None+ data_str = raw_line[5:].lstrip()+ if data_str == "[DONE]":+ return "done"+ try:+ data = json.loads(data_str)+ except json.JSONDecodeError:+ return None+ if isinstance(data, dict) and _monitor_openai_error_message(data):+ return "error"+ return Nonedef _monitor_anthropic_usage(@@ -6609,6 +6672,7 @@ async def _maybe_auto_switch_model(require_vision: bool = False,require_image: bool = True,modality_label: str = "image or audio",+ claim_resident: bool = True,) -> None:"""Load a downloaded local GGUF named by an OpenAI request when auto-switch is on.@@ -6617,7 +6681,12 @@ async def _maybe_auto_switch_model(compat); a miss only reaches the network when auto-download is also on, andeven then only for ``namespace/name`` ids. ``require_vision`` rejects a swapto a text-only target before it runs, so an image request can't evict the- resident vision model only to 400 afterwards; ``require_image`` is what makes+ resident vision model only to 400 afterwards. ``claim_resident`` claims a+ resident model the request adopts (clears the preview marker) at the no-load+ exits; a route that still has its own capability/backend checks that can reject+ (e.g. GGUF-only /v1/completions, /audio/generate) passes ``False`` and claims+ itself only after those checks pass, so a later rejection can't strand a+ preview-owned model as Studio-owned. ``require_image`` makes the vision checkthat rejection modality-aware, since an audio request needs the projector butnot a vision tower. ``modality_label`` names the inputs actually attached, sothe rejection does not report a modality the request never carried.@@ -6636,11 +6705,34 @@ async def _maybe_auto_switch_model(from core.inference.llama_keepwarm import (get_last_unloaded_model,inference_lifecycle_gate,+ note_admitted_inference,+ preview_swapped_since_entry,)+ # Passed auth and reached local inference, so count it in the admitted-inference tally+ # the preview busy guard uses instead of raw _inflight (no-op for preview scopes).+ _swap_scope = getattr(fastapi_request, "scope", None)+ note_admitted_inference(_swap_scope)+ # A preview swapped a different checkpoint in since this request entered; running now+ # would serve the preview's model to Studio, so reject and let the client retry. Covers a+ # request that waited on the gate through the swap AND one that passed the gate before it+ # but is still pre-admission. Deferred here (not a middleware 503) so an external-provider+ # request that untracks and returns before this hook is never rejected for a swap it never+ # touched; over-rejecting a local request is acceptable, serving the wrong checkpoint is not.+ if preview_swapped_since_entry(_swap_scope):+ raise HTTPException(+ status_code = 503,+ detail = "A preview is loading a model. Please retry shortly.",+ headers = {"Retry-After": "1"},+ )+# Treat a non-string model (e.g. {"model": 123} on a raw-body endpoint) as# absent so it falls through instead of raising in the membership checks below.if not isinstance(requested_model, str) or not requested_model:+ # Omitted/default model on a non-preview call runs against the resident model,+ # so claim it for Studio (a preview keeps its own ownership).+ if claim_resident:+ _claim_slot_for_non_preview(fastapi_request)return# The public preview route opts out so a caller cannot switch away from the# pinned preview checkpoint it just loaded.@@ -6656,7 +6748,11 @@ async def _maybe_auto_switch_model(# has to be restorable after it is turned on.if not auto_switch_on and not idle_unload_is_configured():# No switching to do, but a named model must still not be answered by another.+ # Reject first: a request that is turned away here must not claim the slot.await _reject_unservable_model(requested_model, fastapi_request)+ # Auto-switch off: this non-preview turn uses the resident model, claim it.+ if claim_resident:+ _claim_slot_for_non_preview(fastapi_request)return# The common Studio path names the model that is already serving. Resolve that@@ -6664,6 +6760,8 @@ async def _maybe_auto_switch_model(# multi-root index here used to hold the request for seconds before streaming.if auto_switch_on and await asyncio.to_thread(_loaded_identity_satisfies, requested_model):warm_index_soon()+ if claim_resident:+ _claim_slot_for_non_preview(fastapi_request)returnfrom auth.authentication import request_admitted_without_credential@@ -6707,9 +6805,9 @@ async def _maybe_auto_switch_model(# (path + quant + advertised id) so an alias/unknown name stays servable# and keeps the override keyed by the advertised id, not the load path.last = get_last_unloaded_model()- # A non-GGUF (Unsloth/Transformers) model loaded after the idle-unload- # leaves the GGUF slot empty but is the live model, so don't resurrect- # the stale GGUF over it (that load would tear the active model down).+ # A non-GGUF (Unsloth/Transformers) model loaded after the idle-unload leaves the+ # GGUF slot empty but is the live model; don't resurrect the stale GGUF over it+ # (that load would tear the active model down).if (not lastor get_llama_cpp_backend().is_loaded@@ -6717,6 +6815,10 @@ async def _maybe_auto_switch_model(await asyncio.to_thread(get_inference_backend), "active_model_name", None)):+ # Unknown name, model already resident: the non-preview call uses it,+ # so claim it for Studio.+ if claim_resident:+ _claim_slot_for_non_preview(fastapi_request)returnif len(last) == 3:target_id, variant, override_id = last@@ -6771,13 +6873,12 @@ async def _maybe_auto_switch_model(return Truedef _record_serving_alias() -> None:- # When an advertised alias already resolves to the loaded model (e.g. a- # model loaded by local path, requested by its repo/LM Studio id), record- # the alias as the public id so /v1/models and responses report it (and- # mark it loaded) instead of the path-derived basename. Resolver branch- # only: the reload-stash override_id can be the bare path, not a repo id.- # Lock-free is safe here: an in-flight request blocks any concurrent swap- # (single-slot busy guard), so the loaded model can't change under this.+ # When an advertised alias already resolves to the loaded model (e.g. loaded by+ # local path, requested by its repo/LM Studio id), record the alias as the public+ # id so /v1/models and responses report it (marked loaded) instead of the path+ # basename. Resolver branch only: the reload-stash override_id can be a bare path.+ # Lock-free is safe: an in-flight request blocks any concurrent swap (single-slot+ # busy guard), so the loaded model can't change under this.if resolved is None or not override_id:returnb = get_llama_cpp_backend()@@ -6785,6 +6886,10 @@ async def _maybe_auto_switch_model(b._openai_advertised_id = override_idif _already_serving():+ # A non-preview request adopting this model claims it for Studio, so a later+ # preview can't swap it out from under an active OpenAI caller.+ if claim_resident:+ _set_preview_resident(None)_record_serving_alias()return# An image/audio request naming a different text-only GGUF would load it@@ -6820,6 +6925,8 @@ async def _maybe_auto_switch_model(# start on the model while it is being torn down and replaced.async with inference_lifecycle_gate():if _already_serving():+ if claim_resident:+ _set_preview_resident(None)_record_serving_alias()return# Apply the saved launch config so an API swap loads as the picker@@ -6863,35 +6970,54 @@ async def _maybe_auto_switch_model(# Reuse the load impl so its dedup, tensor fallback, and threading# apply. Call the impl directly: we already hold the lifecycle gate# the /load route would otherwise take, so the route would deadlock.+ # Deferred claim (claim_resident=False): _load_model_impl clears the+ # preview marker mid-load and can make the new model resident and then+ # raise while building the load response, so base ownership on what is+ # actually resident, in a finally that runs on that post-load failure+ # too. If the new target is resident, mark it preview-owned (a later+ # route 4xx leaves it evictable; a 2xx turn clears it via the claim,+ # and the in-flight busy guard blocks a concurrent preview swap);+ # otherwise restore the prior owner. claim_resident=True adopts the+ # model outright, so _load_model_impl's own marker clear stands.+ _switch_prior_marker = _get_preview_resident()+ _switch_loaded_ok = Falsetry:- await _load_model_impl(- LoadRequest(**load_kwargs),- fastapi_request,- current_subject,- current_request_counted = True,- )- except HTTPException as exc:- # The pre-flight check cannot mirror every loader gpu_ids rule,- # and a stale pin must never block a request, so retry without it.- if not (- exc.status_code == 400- and load_kwargs.get("gpu_ids")- and "gpu" in str(exc.detail).lower()- ):- raise- logger.warning(- "Retrying %s without saved gpu_ids %s: %s",- override_id,- load_kwargs.get("gpu_ids"),- exc.detail,- )- load_kwargs.pop("gpu_ids", None)- await _load_model_impl(- LoadRequest(**load_kwargs),- fastapi_request,- current_subject,- current_request_counted = True,- )+ try:+ await _load_model_impl(+ LoadRequest(**load_kwargs),+ fastapi_request,+ current_subject,+ current_request_counted = True,+ )+ except HTTPException as exc:+ # The pre-flight check cannot mirror every loader gpu_ids rule,+ # and a stale pin must never block a request, so retry without it.+ if not (+ exc.status_code == 400+ and load_kwargs.get("gpu_ids")+ and "gpu" in str(exc.detail).lower()+ ):+ raise+ logger.warning(+ "Retrying %s without saved gpu_ids %s: %s",+ override_id,+ load_kwargs.get("gpu_ids"),+ exc.detail,+ )+ load_kwargs.pop("gpu_ids", None)+ await _load_model_impl(+ LoadRequest(**load_kwargs),+ fastapi_request,+ current_subject,+ current_request_counted = True,+ )+ _switch_loaded_ok = True+ finally:+ if not claim_resident:+ if _switch_loaded_ok or _loaded_slot_ident() == target_id:+ _set_preview_resident(_loaded_slot_ident())+ else:+ _set_preview_resident(_switch_prior_marker)# Advertise the repo id (not the concrete load path) as the loaded# model's public id and override key for /v1/models and idle stash.get_llama_cpp_backend()._openai_advertised_id = override_id@@ -6930,13 +7056,313 @@ async def _auto_switch_from_request_body(request: Request, current_subject: str)model = body.get("model") or _RELOAD_ONLY_MODELelse:model = None- await _maybe_auto_switch_model(model, request, current_subject)+ # Serves the GGUF-only /v1/completions and /v1/embeddings routes, which still 503 "No+ # GGUF model loaded" after this returns. Don't claim here (claim_resident=False); the+ # caller claims only once it confirms a GGUF is loaded, so that 503 can't strand a+ # preview-owned non-GGUF model as Studio-owned.+ await _maybe_auto_switch_model(model, request, current_subject, claim_resident = False)return body+_preview_slot_lock = threading.Lock()+_preview_resident_ident: Optional[str] = None+++def _set_preview_resident(ident: Optional[str]) -> None:+ global _preview_resident_ident+ with _preview_slot_lock:+ _preview_resident_ident = ident+++def _is_preview_resident(ident: str) -> bool:+ with _preview_slot_lock:+ marked = _preview_resident_ident+ return marked is not None and marked.lower() == ident.lower()+++def _preview_slot_is_owned() -> bool:+ """True when the resident slot is currently preview-owned, so a non-preview turn+ adopting it would clear that ownership."""+ with _preview_slot_lock:+ return _preview_resident_ident is not None+++def _get_preview_resident() -> Optional[str]:+ """The current preview-ownership marker, for callers that must restore it (e.g. a+ preview reload that fails after _load_model_impl already cleared it)."""+ with _preview_slot_lock:+ return _preview_resident_ident+++def _same_loaded_identifier(loaded: Optional[str], requested: str) -> bool:+ """Whether a loaded model identifier is the exact one requested, for the+ already-loaded dedup.++ Local filesystem paths are compared filesystem-aware via os.path.normcase: on a+ case-sensitive filesystem two checkpoint paths differing only by case are+ different models, so they must not dedup to the already-loaded fast path (which+ would keep serving the wrong checkpoint). Hugging Face repo IDs (e.g. unsloth/Foo)+ are resolved case-insensitively elsewhere in the loader, so compare those+ case-insensitively to avoid an unnecessary unload/reload of the same repo."""+ if not loaded:+ return False++ # Local checkpoint == absolute path OR an existing relative path (ModelConfig resolves an+ # existing relative path as a local file). Only genuine repo ids take the lower() compare.+ def _is_local_path(ident: str) -> bool:+ return os.path.isabs(ident) or os.path.exists(ident)++ if _is_local_path(loaded) or _is_local_path(requested):+ return os.path.normcase(loaded) == os.path.normcase(requested)+ return loaded.lower() == requested.lower()+++def _should_validate_before_switch() -> bool:+ """Whether a route must run its shape validation before _maybe_auto_switch_model.++ True when an automatic load could run (resolver auto-switch or an idle-reload),+ and also when the slot is preview-owned: with both features off no load runs, but+ _maybe_auto_switch_model still claims the slot (clears the preview marker) for a+ non-preview turn. A request rejected after that claim would have converted the+ preview-owned model into a Studio-owned one for nothing, stranding the next+ preview for a different checkpoint on the 503 slot guard, so validate first.+ """+ return _automatic_model_load_may_run() or _preview_slot_is_owned()+++def _loaded_slot_ident() -> Optional[str]:+ backend = _peek_inference_backend()+ active = getattr(backend, "active_model_name", None) if backend is not None else None+ if active:+ return str(active)+ llama_backend = get_llama_cpp_backend()+ if llama_backend.is_loaded and llama_backend.model_identifier:+ return str(llama_backend.model_identifier)+ return None+++def _preview_same_checkpoint(loaded: str, requested: str) -> bool:+ """True when the resident slot already serves the preview's checkpoint. Exact string+ match first: it is the fast path and the only comparison that makes sense for a non-path+ identifier (an HF repo id like ``org/model``). Otherwise compare resolved filesystem+ paths, so a checkpoint Studio loaded through an equivalent spelling -- a relative+ ``outputs/run`` vs the absolute path the preview resolver produces -- still borrows the+ slot instead of 503'ing. realpath preserves case-sensitive distinct paths (it never+ lowercases, so /outputs/Run and /outputs/run stay distinct); a non-path identifier just+ resolves to a location under the cwd that cannot match the preview's checkpoint."""+ if loaded == requested:+ return True+ try:+ return Path(loaded).resolve() == Path(requested).resolve()+ except OSError:+ return False+++def _claim_slot_for_non_preview(fastapi_request) -> None:+ """Non-preview local generation adopts the resident model for Studio.++ Clearing the preview marker means a later preview for another checkpoint gets a+ 503 instead of swapping the model out from under an active Studio/OpenAI turn. A+ ``/p`` preview request keeps its own ownership (it may still be swapped by the+ next preview), so skip when the request is a preview -- audio previews reach+ generate_audio through openai_chat_completions, so the path check, not the+ handler, decides ownership.+ """+ from core.inference.llama_keepwarm import _is_preview_path++ scope = getattr(fastapi_request, "scope", None)+ path = scope.get("path") if isinstance(scope, dict) else None+ if _is_preview_path(path or ""):+ return+ _set_preview_resident(None)+++async def load_model_for_preview(+ request: LoadRequest, fastapi_request: Request, current_subject: str+) -> None:+ from core.inference.llama_keepwarm import (+ inference_lifecycle_gate,+ note_preview_swap,+ note_preview_swap_begin,+ note_preview_swap_end,+ other_admitted_inference_count,+ untrack_current_request,+ )+ from utils.transformers_version import sidecar_swap_in_progress++ # A refused preview never touches the model, so it must not stamp keep-warm+ # activity (public /p spam could otherwise pin an idle Studio model in VRAM);+ # untrack also balances the preview in-flight counter for the dropped request.+ scope = getattr(fastapi_request, "scope", None)+ async with _auto_switch_lock():+ await _acquire_swap_gate()+ _swap_begun = False+ try:+ async with inference_lifecycle_gate():+ # Preview loads bypass load_model(), so re-apply its sidecar guard:+ # a public preview must not complete a load while a transformers+ # install has reserved the swap, or the installer later aborts.+ if sidecar_swap_in_progress():+ untrack_current_request(scope)+ raise HTTPException(+ status_code = 409,+ detail = "A transformers installation is in progress. Retry when it completes.",+ headers = {"Retry-After": "10"},+ )+ loaded = _loaded_slot_ident()+ # Borrow the resident model when it already serves this checkpoint, matching+ # an equivalent spelling (relative vs the resolved absolute path) via realpath+ # while keeping case-sensitive distinct paths distinct (never lowercased).+ same_target = loaded is not None and _preview_same_checkpoint(+ loaded, request.model_path+ )++ def _refuse_studio_owned_model() -> None:+ if loaded is None or _is_preview_resident(loaded):+ return+ # A LoRA preview forces adapters on. Borrowing a Studio-owned LoRA+ # would mutate its shared adapter state, so require an unload instead.+ if (+ same_target+ and not (Path(request.model_path) / "adapter_config.json").is_file()+ ):+ return+ untrack_current_request(scope)+ raise HTTPException(+ status_code = 503,+ detail = "Studio already has a different model loaded. Unload it before using this preview.",+ headers = {"Retry-After": "10"},+ )++ _refuse_studio_owned_model()+ # For a real load (not a same-target borrow) mark the swap in progress BEFORE+ # the admitted-count check below so the two are atomic against a concurrent+ # non-preview request: preview_swapped_since_entry() keys on the live+ # _preview_swap_inflight, so a Studio request reaching _maybe_auto_switch_model+ # after this marker is rejected, while one admitted before it is caught by the+ # busy check. Setting it only after the check left a gap where a Studio request+ # admitted between the check and the marker ran against the slot this preview+ # is about to replace. Skip it for a same-target borrow: that changes nothing+ # (no counter bump), so marking would 503 concurrent Studio requests for no+ # reason. Cleared only after the lifecycle gate releases.+ if not same_target:+ note_preview_swap_begin()+ _swap_begun = True+ # A same-checkpoint request would still restart a Studio-owned GGUF whose+ # live settings differ from these bare defaults (#5401), so admitted+ # (post-auth) Studio inference blocks first. Only admitted local inference+ # is counted, not raw _inflight: the middleware tracks a POST before+ # FastAPI auth, so a pre-auth or unauthenticated non-preview request would+ # otherwise starve previews. Queued (pending) requests are likewise not+ # counted; a genuinely queued Studio request is protected by the swap+ # reject (it wakes to a retryable 503 rather than the swapped-in model).+ if other_admitted_inference_count() > 0:+ untrack_current_request(scope)+ raise HTTPException(+ status_code = 503,+ detail = "The preview model is busy. Please try again shortly.",+ headers = {"Retry-After": "10"},+ )+ # recheck after the admitted count because another loop may have claimed the slot.+ _refuse_studio_owned_model()+ if same_target:+ # The resident model already serves this exact checkpoint, so+ # borrow it as-is instead of reloading with bare preview settings+ # (which would reconfigure/restart an idle Studio-owned GGUF,+ # #5401). Ownership is unchanged: Studio's model stays Studio's, a+ # preview-owned one stays preview-owned.+ return+ # A real load reclaims the GPU for chat (_load_model_impl's acquire_for(CHAT)),+ # which evicts a resident Images/Video pipeline -- unloading the engine out from+ # under an in-flight Studio generation. Those routes never reach+ # note_admitted_inference (they don't touch the llama slot), and a video clip+ # generates in the background after its POST returns, so the admitted-count guard+ # above sees nothing; gate on GPU ownership instead, which is exactly what the+ # eviction keys on (a CPU-only image/video load releases its claim and evicts+ # nothing, so it never refuses a preview for free). Only the real-load path is+ # gated: a same-target borrow returns above without acquiring anything.+ from core.inference.gpu_arbiter import (+ DIFFUSION,+ VIDEO,+ GpuOwnerBusyError,+ current_owner,+ )++ if current_owner() in (DIFFUSION, VIDEO):+ untrack_current_request(scope)+ raise HTTPException(+ status_code = 503,+ detail = (+ "Studio is using the GPU for image or video generation. "+ "Unload that model before using this preview."+ ),+ headers = {"Retry-After": "10"},+ )+ # _load_model_impl clears the preview marker mid-load (it reclaims the+ # slot for Studio). If the load then fails while the prior model is+ # still resident (e.g. a GPU-selection or pre-spawn error), leaving the+ # marker cleared would make the next preview for another checkpoint see+ # that still-preview model as Studio-owned and 503. Restore the prior+ # ownership on failure; only a successful load takes the new marker.+ prior_marker = _get_preview_resident()+ loaded_ok = False+ try:+ await _load_model_impl(+ request,+ fastapi_request,+ current_subject,+ # The preview request is itself tracked in-flight (a /p path is an+ # inference path), so exclude it from the swap drain or the load waits+ # on itself forever.+ current_request_counted = True,+ # Same active-generation gate load_model_gated applies, which the+ # preview would otherwise bypass by calling the impl directly. Never+ # forced: a public preview must refuse rather than stop Studio chats.+ on_reload_confirmed = lambda *, cancel: _raise_or_cancel_active_generations(+ force = False,+ action = "Loading a model",+ cancel = cancel,+ ),+ allow_gpu_owner_eviction = False,+ )+ loaded_ok = True+ except GpuOwnerBusyError as exc:+ untrack_current_request(scope)+ raise HTTPException(+ status_code = 503,+ detail = (+ "Studio is using the GPU for image or video generation. "+ "Unload that model before using this preview."+ ),+ headers = {"Retry-After": "10"},+ ) from exc+ finally:+ resident_after = _loaded_slot_ident()+ # Base ownership on what is actually resident now: the load can make+ # this preview's checkpoint resident and then raise while assembling+ # the load response, leaving loaded_ok false. If the slot now holds+ # this preview's model, mark it preview-owned (it was loaded only by+ # this preview); only when the resident model was not replaced do we+ # restore the prior owner.+ if loaded_ok or resident_after == request.model_path:+ _set_preview_resident(request.model_path)+ else:+ _set_preview_resident(prior_marker)+ # A failed atomic GPU acquisition changes no chat model state. Only+ # publish a swap when a load succeeded or the resident identifier+ # actually changed during a partial failure.+ if loaded_ok or resident_after != loaded:+ note_preview_swap()+ finally:+ # Cleared only here, after the lifecycle gate above has been released, so a+ # non-preview request that arrived in the post-bump/pre-release window still+ # saw the swap in progress at entry and is rejected.+ if _swap_begun:+ note_preview_swap_end()+ _auto_switch_process_lock.release()++def _effective_load_in_4bit(config: ModelConfig, requested: bool) -> bool:- """Effective quantization the loader will use: a LoRA adapter can flip 4-bit to- 16-bit via adapter_config.json, so the guard sizes this, not the raw request."""load_in_4bit = requestedif not getattr(config, "is_lora", False) or not getattr(config, "path", None):return load_in_4bit@@ -9479,6 +9905,7 @@ async def _load_model_impl(*,current_request_counted: bool = False,on_reload_confirmed = None,+ allow_gpu_owner_eviction: bool = True,load_cancel_event: Optional[threading.Event] = None,):from core.inference.llama_cpp import LlamaServerNotFoundError@@ -9601,12 +10028,19 @@ async def _load_model_impl(intent: GgufLoadIntent, *, display_name: Optional[str] = None) -> Optional[LoadResponse]:if not (- llama_backend.adopt_load_intent_if_matched(intent)+ # Case-sensitive filesystems keep two checkpoint paths that differ only by+ # case distinct, so they must not dedup onto the already-loaded fast path+ # (the intent match lowercases the identifier). Checked before the adopt so+ # a mismatch never adopts the caller's placement.+ _same_loaded_identifier(llama_backend.model_identifier, model_identifier)+ and llama_backend.adopt_load_intent_if_matched(intent)and getattr(llama_backend, "_audio_probed", True)):return Noneapi_monitor.discard(_load_event)logger.info("Model already loaded (GGUF): %s, skipping reload", model_log_label)+ # A no-op Studio load of a preview-owned checkpoint still claims it.+ _set_preview_resident(None)return _gguf_load_response(llama_backend,"already_loaded",@@ -9638,13 +10072,13 @@ async def _load_model_impl(await asyncio.to_thread(acquire_for, CHAT)return reusedif not (request.gguf_variant or is_direct_gguf_request):- if (- backend.active_model_name- and backend.active_model_name.lower() == model_identifier.lower()- and _mlx_runtime_settings_match(backend, request)- ):+ if _same_loaded_identifier(+ backend.active_model_name, model_identifier+ ) and _mlx_runtime_settings_match(backend, request):api_monitor.discard(_load_event) # nothing loaded, no monitor rowlogger.info(f"Model already loaded (Unsloth): {model_log_label}, skipping reload")+ # A no-op Studio load of a preview-owned checkpoint still claims it.+ _set_preview_resident(None)inference_config = load_inference_config(backend.active_model_name)_model_info = backend.models.get(backend.active_model_name, {})_chat_template = None@@ -9956,15 +10390,29 @@ async def _load_model_impl(raise HTTPException(status_code = 400, detail = _host_offload)if chat_load_needs_gpu:+ gpu_acquire_kwargs = {} if allow_gpu_owner_eviction else {"allow_evict": False}await asyncio.to_thread(acquire_for,CHAT,lambda: gguf_load_stack.enter_context(chat_load_in_flight()),+ **gpu_acquire_kwargs,)else:# The marker still goes up (the download-manager handshake reads it, and it keeps this load cancellable). A stale CHAT claim is dropped AFTER the load.gguf_load_stack.enter_context(chat_load_in_flight())+ # capture the prior marker before either load path reaches its point of no return.+ _prior_preview_marker = _get_preview_resident()++ def _restore_marker_if_prior_preview_still_resident() -> None:+ # A failed load can leave the prior preview checkpoint resident though the marker+ # was cleared before teardown (a non-GGUF load unloads only the new entry; a GGUF load can+ # raise before tearing down the old llama-server). Restore its ownership so a later+ # preview isn't 503'd against a model Studio never adopted. Guarded on the prior+ # model still being resident, so it never mis-marks a torn-down/replaced model.+ if _prior_preview_marker is not None and _loaded_slot_ident() == _prior_preview_marker:+ _set_preview_resident(_prior_preview_marker)+# ── GGUF path: load via llama-server ──────────────────────if config.is_gguf:llama_backend = get_llama_cpp_backend()@@ -9998,14 +10446,24 @@ async def _load_model_impl(timeout_s = _POST_CANCEL_DRAIN_TIMEOUT_S,)+ # every rejection and drain has completed. the load now owns the slot for studio.+ _set_preview_resident(None)+# Unload any active Unsloth model only after every hub conflict check.if unsloth_backend.active_model_name:logger.info(f"Unloading Unsloth model '{unsloth_backend.active_model_name}' before loading GGUF")- await asyncio.to_thread(- unsloth_backend.unload_model, unsloth_backend.active_model_name- )+ try:+ await asyncio.to_thread(+ unsloth_backend.unload_model, unsloth_backend.active_model_name+ )+ except Exception:+ # This teardown runs after the marker was cleared above; if it raises+ # with the prior preview-owned Unsloth model still resident, restore its+ # ownership so a later preview for another checkpoint is not 503'd.+ _restore_marker_if_prior_preview_still_resident()+ raise# Every rejection and source check has completed. The immutable# intent resolved before teardown is now the only launch input.@@ -10039,18 +10497,27 @@ async def _load_model_impl(# falls back to layer split so the checkbox never blocks a model from# loading; the response reports the backend's actual tensor_parallel# state so the UI toggle reflects the fallback.- success = await load_with_tensor_fallback(- _attempt_gguf_load,- requested_tensor = request.tensor_parallel,- extra_args = extra_llama_args,- label = config.identifier,- cancelled = lambda: (- llama_backend.load_cancelled()- or bool(load_cancel_event and load_cancel_event.is_set())- ),- )+ try:+ success = await load_with_tensor_fallback(+ _attempt_gguf_load,+ requested_tensor = request.tensor_parallel,+ extra_args = extra_llama_args,+ label = config.identifier,+ cancelled = lambda: (+ llama_backend.load_cancelled()+ or bool(load_cancel_event and load_cancel_event.is_set())+ ),+ )+ except Exception:+ # A GGUF load can raise before tearing down the old llama-server (e.g. an+ # update-in-progress guard fires before _kill_process), leaving the prior+ # preview-owned GGUF resident. Restore its marker so a later preview for+ # another checkpoint is not 503'd against it.+ _restore_marker_if_prior_preview_still_resident()+ raiseif not success:+ _restore_marker_if_prior_preview_still_resident()raise HTTPException(status_code = 500,detail = f"Failed to load GGUF model: {model_log_label if native_grant_backed else config.display_name}",@@ -10135,11 +10602,20 @@ async def _load_model_impl(current_request_counted = current_request_counted,timeout_s = _POST_CANCEL_DRAIN_TIMEOUT_S,)+ # every rejection and drain has completed. the load now owns the slot for studio.+ _set_preview_resident(None)# Unload any active GGUF model first, off-loop: a 600 GB teardown measures# 160s and on-loop would block _tunnel_safe_json's own padding.if llama_backend.is_loaded:logger.info("Unloading GGUF model before loading Unsloth model")- await asyncio.to_thread(llama_backend.unload_model)+ try:+ await asyncio.to_thread(llama_backend.unload_model)+ except Exception:+ # This teardown runs after the marker was cleared above; if it raises with+ # the prior preview-owned GGUF still resident, restore its ownership so a+ # later preview for another checkpoint is not 503'd against it.+ _restore_marker_if_prior_preview_still_resident()+ raise# Shut down any export subprocess to free VRAMtry:@@ -10159,22 +10635,27 @@ async def _load_model_impl(# Load in a thread so the event loop stays free for download progress# polling and other requests.- success = await asyncio.to_thread(- backend.load_model,- config = config,- max_seq_length = request.max_seq_length,- load_in_4bit = load_in_4bit,- hf_token = request.hf_token,- trust_remote_code = request.trust_remote_code,- approved_remote_code_fingerprint = request.approved_remote_code_fingerprint,- gpu_ids = placement.requested_gpu_ids,- subject = current_subject,- mlx_kv_bits = request.mlx_kv_bits,- chat_template_override = request.chat_template_override,- load_cancel_event = load_cancel_event,- )+ try:+ success = await asyncio.to_thread(+ backend.load_model,+ config = config,+ max_seq_length = request.max_seq_length,+ load_in_4bit = load_in_4bit,+ hf_token = request.hf_token,+ trust_remote_code = request.trust_remote_code,+ approved_remote_code_fingerprint = request.approved_remote_code_fingerprint,+ gpu_ids = placement.requested_gpu_ids,+ subject = current_subject,+ mlx_kv_bits = request.mlx_kv_bits,+ chat_template_override = request.chat_template_override,+ load_cancel_event = load_cancel_event,+ )+ except Exception:+ _restore_marker_if_prior_preview_still_resident()+ raiseif not success:+ _restore_marker_if_prior_preview_still_resident()# Check if YAML says this model needs trust_remote_code.if not request.trust_remote_code:model_defaults = load_model_defaults(config.identifier)@@ -10314,8 +10795,11 @@ async def _load_model_impl(logger.warning("GGUF runtime missing while loading '%s': %s", model_log_label, e)raise HTTPException(status_code = 400, detail = str(e))except Exception as e:+ from core.inference.gpu_arbiter import GpuOwnerBusyErrorfrom utils.transformers_version import SidecarSwapInProgress+ if isinstance(e, GpuOwnerBusyError):+ raiseif isinstance(e, SidecarSwapInProgress):# Lost the spawn-time race to a sidecar install/repair: retryable 409.raise HTTPException(status_code = 409, detail = str(e))@@ -11657,13 +12141,37 @@ async def generate_stream(For vision models, provide image_base64 (base64-encoded image)."""+ # Enforce the preview-swap reject FIRST, before reading any backend state. If a public+ # preview loaded a different checkpoint while this native Studio request waited on the+ # keep-warm gate, the middleware flagged the scope; the loaded-model and image-capability+ # checks below would otherwise run against the swapped-in model and return a hard 400+ # instead of the intended retryable 503. generate_stream skips _maybe_auto_switch_model,+ # where this guard otherwise runs. No claim needed: the middleware claims on a 2xx.+ from core.inference.llama_keepwarm import (+ mark_response_failed,+ note_admitted_inference,+ preview_swapped_since_entry,+ )++ _gs_scope = getattr(fastapi_request, "scope", None)+ # Passed auth and reached local inference, so count it in the admitted-inference+ # tally the preview busy guard uses instead of raw _inflight.+ note_admitted_inference(_gs_scope)+ # Reject if a preview swapped in since this request entered (waited on the gate+ # through the swap, or passed the gate before it but is still pre-admission).+ if preview_swapped_since_entry(_gs_scope):+ raise HTTPException(+ status_code = 503,+ detail = "A preview is loading a model. Please retry shortly.",+ headers = {"Retry-After": "1"},+ )+backend = await asyncio.to_thread(get_inference_backend)if not backend.active_model_name:raise HTTPException(status_code = 400, detail = "No model loaded. Call POST /inference/load first.")-# Decode image if provided (vision models)image = Noneif request.image_base64:@@ -11732,12 +12240,21 @@ async def generate_stream(# the generator does not signal a subprocess backend, so it would# keep decoding. The finally's reset is guarded, so no double-run.backend.reset_generation_state(cancel_event)+ # 200 stream ends with no completion (client disconnected), so flag+ # failed: the middleware must not treat this cancelled stream as a+ # success and claim the model.+ mark_response_failed(_gs_scope)breakchunk = await asyncio.to_thread(next, gen, _DONE)if chunk is _DONE:completed = Truebreakif isinstance(chunk, GenStreamError):+ # A backend sentinel (subprocess down, no active model, model being+ # unloaded) delivered in-band under the already-sent 200. The stream ends+ # cleanly, so flag it failed or the middleware reads this failed generation+ # as a successful Studio turn and claims a preview-owned model.+ mark_response_failed(_gs_scope)yield f"data: {json.dumps({'error': _friendly_gen_stream_error(chunk)})}\n\n"yield "data: [DONE]\n\n"return@@ -11753,6 +12270,10 @@ async def generate_stream(cancel_event.set()backend.reset_generation_state(cancel_event)logger.error(f"Error during generation: {e}", exc_info = True)+ # The stream already sent HTTP 200, so signal the failure out-of-band: the+ # middleware must not treat this errored stream as a success and claim a+ # preview-owned model.+ mark_response_failed(_gs_scope)yield f"data: {json.dumps({'error': _friendly_error(e)})}\n\n"yield "data: [DONE]\n\n"finally:@@ -12153,7 +12674,9 @@ async def _generate_tts_wav(# the client model through the resolver could load a text- or vision-only target# and evict the working audio model before the audio backend check fails. Only# the idle-stash restore runs here; switching TTS models is an explicit /load.- await _maybe_auto_switch_model(_RELOAD_ONLY_MODEL, request, current_subject)+ await _maybe_auto_switch_model(+ _RELOAD_ONLY_MODEL, request, current_subject, claim_resident = False+ )# Again, now that a context exists to measure against. The check above runs before the# restore so an invalid request never triggers a reload, but with nothing loaded it has# no context length and passes everything, so the first request after an idle eviction@@ -12216,6 +12739,9 @@ async def _generate_tts_wav(detail = f"Active model does not support text-to-speech (audio_type={audio_type or 'unknown'}).",)+ # Audio-capable backend confirmed. The middleware claims the slot on a 2xx, so no claim+ # here: claiming before the audio backend runs could strand a preview-owned checkpoint+ # as Studio-owned if generation then fails.# Apply per-model recommended sampling + any operator UNSLOTH_SAMPLING_* pin before# generating, so `unsloth run --temperature` (and the other pins) and per-model# recommendations reach audio (TTS) generation too, not just chat. The gen lambdas read@@ -15160,16 +15686,17 @@ async def openai_chat_completions(),)- # Reject a system-only chat before any automatic load so an invalid request- # never swaps or reloads the resident model (as /responses and /messages- # already validate before switching). Gate on every automatic-load trigger,- # not just auto-switch, since a standalone idle TTL can also reload here.- # Parse once and reuse below.+ # Reject a system-only chat before any automatic load so an invalid request never swaps or+ # reloads the resident model (as /responses and /messages already validate before+ # switching). Gate on every automatic-load trigger (not just auto-switch: a standalone idle+ # TTL can also reload here), and on a preview-owned slot: even with both features off the+ # switch helper claims the slot, so a later-rejected request must not clear that ownership+ # first. Parse once and reuse below._pre_parsed = None_needs_vision = False_needs_image = False_modality_label = "image or audio"- if _automatic_model_load_may_run():+ if _should_validate_before_switch():_pre_parsed = _extract_content_parts(payload.messages)if not _pre_parsed[1]:raise HTTPException(@@ -15297,6 +15824,11 @@ async def openai_chat_completions(if _video_rejection is not None:raise HTTPException(status_code = _video_rejection[0], detail = _video_rejection[1])+ # Defer the resident claim: chat has several post-switch capability checks that can still+ # reject (Whisper without audio, n>1 on a non-GGUF backend, tool or response_format+ # passthrough), so claiming here could strand a preview-owned model for a request that+ # never generates. The middleware instead claims the slot on a successful 2xx non-preview+ # response.await _maybe_auto_switch_model(_switch_model_for_payload(payload),request,@@ -15304,6 +15836,7 @@ async def openai_chat_completions(require_vision = _needs_vision,require_image = _needs_image,modality_label = _modality_label,+ claim_resident = False,)llama_backend = get_llama_cpp_backend()@@ -15500,6 +16033,8 @@ async def openai_chat_completions(_await_disconnect_then_cancel(request, cancel_event))try:+ from core.inference.llama_keepwarm import mark_current_response_failed+yield _chat_role_chunk(completion_id, created, model_name)gen = audio_input_generate()@@ -15508,10 +16043,14 @@ async def openai_chat_completions(while True:if cancel_event.is_set():cancelled = True+ # Cancelled before completion: flag failed so the middleware+ # does not claim a preview-owned model.+ mark_current_response_failed()breakif await request.is_disconnected():cancel_event.set()api_monitor.finish(monitor_id, "cancelled")+ mark_current_response_failed()returnchunk_text = await asyncio.to_thread(next, gen, _DONE)if chunk_text is _DONE:@@ -15554,6 +16093,9 @@ async def openai_chat_completions(logger.error(f"Error during audio input streaming: {e}", exc_info = True)_msg = _friendly_error(e)api_monitor.fail(monitor_id, _msg)+ # _openai_stream_error_sse flags the response failed (in-band error+ # after the 200 headers), so the middleware does not claim a+ # preview-owned model.yield _openai_stream_error_sse({"error": {"message": _msg, "type": "server_error"}})@@ -15614,6 +16156,7 @@ async def openai_chat_completions(_audio_json_finish = ("stop" if cancel_event.is_set() else _stats_finish_reason(_audio_json_stats))+ _mark_cancelled_json_response_failed(request, cancel_event)if isinstance(_audio_json_stats, dict):_monitor_usage(monitor_id,@@ -16195,6 +16738,8 @@ async def openai_chat_completions(_await_disconnect_then_cancel(request, cancel_event))try:+ from core.inference.llama_keepwarm import mark_current_response_failed+yield _chat_role_chunk(completion_id, created, model_name)# In this generator's own context, before the per-event task and@@ -16233,9 +16778,11 @@ async def openai_chat_completions(while True:if cancel_event.is_set():+ mark_current_response_failed()breakif await request.is_disconnected():cancel_event.set()+ mark_current_response_failed()api_monitor.finish(monitor_id, "cancelled")return@@ -16401,6 +16948,8 @@ async def openai_chat_completions(timings = _stream_timings,stop_reason = _clamp_finish_reason(_stream_finish),)+ if cancel_event.is_set():+ mark_current_response_failed()api_monitor.finish(monitor_id, "cancelled" if cancel_event.is_set() else "completed")@@ -16736,6 +17285,12 @@ async def openai_chat_completions(timings = completion_timings,stop_reason = _clamp_finish_reason(completion_finish),)+ # An explicit /inference/cancel breaks this tool drain mid-generation but the+ # route still returns a JSON 200, so flag the response failed here or the+ # middleware claims a preview-owned slot for a cancelled completion.+ if cancel_event.is_set():+ from core.inference.llama_keepwarm import mark_current_response_failed+ mark_current_response_failed()api_monitor.finish(monitor_id, "cancelled" if cancel_event.is_set() else "completed")@@ -16880,6 +17435,8 @@ async def openai_chat_completions(next_task = Nonestream_completed = Falsetry:+ from core.inference.llama_keepwarm import mark_current_response_failed+yield _chat_role_chunk(completion_id, created, model_name)# Iterate the sync generator in a thread so the event loop@@ -16892,9 +17449,11 @@ async def openai_chat_completions(_stream_finish = Nonewhile True:if cancel_event.is_set():+ mark_current_response_failed()breakif await request.is_disconnected():cancel_event.set()+ mark_current_response_failed()api_monitor.finish(monitor_id, "cancelled")returnnext_task = asyncio.create_task(@@ -17001,6 +17560,8 @@ async def openai_chat_completions(timings = _stream_timings,stop_reason = _clamp_finish_reason(_stream_finish),)+ if cancel_event.is_set():+ mark_current_response_failed()api_monitor.finish(monitor_id, "cancelled" if cancel_event.is_set() else "completed")@@ -17399,6 +17960,8 @@ async def openai_chat_completions(_context_truncation,) = await asyncio.shield(drain_task)+ _mark_cancelled_json_response_failed(request, cancel_event)+response = ChatCompletion(id = completion_id,created = created,@@ -17762,6 +18325,8 @@ async def openai_chat_completions(_await_disconnect_then_cancel(request, cancel_event))try:+ from core.inference.llama_keepwarm import mark_current_response_failed+yield _chat_role_chunk(completion_id, created, model_name)gen = sf_generate_with_tools()@@ -17785,10 +18350,12 @@ async def openai_chat_completions(while True:if cancel_event.is_set():backend.reset_generation_state(cancel_event)+ mark_current_response_failed()breakif await request.is_disconnected():cancel_event.set()backend.reset_generation_state(cancel_event)+ mark_current_response_failed()api_monitor.finish(monitor_id, "cancelled")return@@ -17922,6 +18489,8 @@ async def openai_chat_completions(_stats.get("usage"),timings = _stats.get("timings"),)+ if cancel_event.is_set():+ mark_current_response_failed()api_monitor.finish(monitor_id, "cancelled" if cancel_event.is_set() else "completed")@@ -18034,6 +18603,9 @@ async def openai_chat_completions(_stats.get("usage"),timings = _stats.get("timings"),)+ if cancel_event.is_set():+ from core.inference.llama_keepwarm import mark_current_response_failed+ mark_current_response_failed()api_monitor.finish(monitor_id, "cancelled" if cancel_event.is_set() else "completed")_sf_msg_kwargs = {"content": _visible_text}if _reasoning_text:@@ -18268,6 +18840,8 @@ async def openai_chat_completions(_await_disconnect_then_cancel(request, cancel_event))try:+ from core.inference.llama_keepwarm import mark_current_response_failed+yield _chat_role_chunk(completion_id, created, model_name)# Client-tool passthrough: heal text-form calls on the fly@@ -18286,6 +18860,7 @@ async def openai_chat_completions(while True:if cancel_event.is_set():backend.reset_generation_state(cancel_event)+ mark_current_response_failed()break# Stall keepalive (see safetensors tool stream) each window while# next(gen) runs in a worker. next(gen, _DONE) returns _DONE rather@@ -18315,6 +18890,7 @@ async def openai_chat_completions(if await request.is_disconnected():cancel_event.set()backend.reset_generation_state(cancel_event)+ mark_current_response_failed()api_monitor.finish(monitor_id, "cancelled")returnnew_text = cumulative[len(prev_text) :]@@ -18420,6 +18996,8 @@ async def openai_chat_completions(_stats.get("usage"),timings = _stats.get("timings"),)+ if cancel_event.is_set():+ mark_current_response_failed()api_monitor.finish(monitor_id, "cancelled" if cancel_event.is_set() else "completed")@@ -18644,6 +19222,7 @@ async def openai_chat_completions(# the nudge rebuilds a longer prompt for some choices._prompt_details = _choice_usage.get("prompt_tokens_details")_sum_completion += _choice_usage.get("completion_tokens") or 0+ _mark_cancelled_json_response_failed(request, cancel_event)_msg, _finish = _monitor_replies[-1], _choices[-1].finish_reason# Built once, so what the monitor is told below is this same object and@@ -19360,6 +19939,12 @@ def _flatten_monitor_prompt(value) -> str:return str(value)+# Distinguishes an unparseable raw body (defer to the post-switch re-read, preserving the+# pre-feature malformed-body error) from a valid JSON body that is simply not an object+# (e.g. [] or null), which is rejected before the switch.+_UNPARSEABLE_BODY = object()++def _completions_prompt_present(body: dict) -> bool:"""Whether a completions body carries a usable ``prompt`` (non-empty)."""prompt = body.get("prompt")@@ -19380,14 +19965,15 @@ async def openai_completions(request: Request, current_subject: str = Depends(ge"""llama_backend = get_llama_cpp_backend()- # Reject a request with no prompt before any automatic load so an invalid- # request never swaps or reloads the resident model (as chat/embeddings already- # validate before switching). Gate on every automatic-load trigger.- if _automatic_model_load_may_run():+ # Reject a request with no prompt before any automatic load so an invalid request never+ # swaps or reloads the resident model (as chat/embeddings already validate before+ # switching). Gate on every automatic-load trigger, and on a preview-owned slot the switch+ # helper would claim even with both features off.+ if _should_validate_before_switch():try:_pre = await request.json()except (json.JSONDecodeError, ValueError):- _pre = None+ _pre = _UNPARSEABLE_BODYif isinstance(_pre, dict):_pre_prompt = _pre.get("prompt")if _pre_prompt is not None and not isinstance(_pre_prompt, (str, list, tuple)):@@ -19397,6 +19983,12 @@ async def openai_completions(request: Request, current_subject: str = Depends(geraise HTTPException(status_code = 400, detail = "'prompt' must be a string or array.")if not _completions_prompt_present(_pre):raise HTTPException(status_code = 400, detail = "'prompt' is required for completions.")+ elif _pre is not _UNPARSEABLE_BODY:+ # A valid JSON body that is not an object (e.g. [] or null) is rejected below as+ # "Request body must be a JSON object"; reject it here, before the switch, so the+ # slot claim can't convert a preview-owned model to Studio-owned for a request+ # that never runs.+ raise HTTPException(status_code = 400, detail = "Request body must be a JSON object")# Opt-in: load the requested local GGUF before the loaded-state check.body = await _auto_switch_from_request_body(request, current_subject)@@ -19415,6 +20007,11 @@ async def openai_completions(request: Request, current_subject: str = Depends(geif not isinstance(body, dict):raise HTTPException(status_code = 400, detail = "Request body must be a JSON object")+ # GGUF is loaded and the body is valid. The middleware claims the slot on a successful+ # 2xx, so no claim here: llama-server can still return a non-2xx for a valid body (e.g. a+ # no-pooling error on /v1/embeddings against a non-embedding GGUF), so claiming before the+ # upstream response would strand a preview-owned checkpoint as Studio-owned.+_resolved_max_tokens = _effective_openai_max_tokens_from_values(body.get("max_tokens"))body["max_tokens"] = (_resolved_max_tokens@@ -19453,6 +20050,8 @@ async def openai_completions(request: Request, current_subject: str = Depends(ge# honor stream_options.include_usage per event, while keeping SSE# framing and token bytes intact._include_usage = bool((body.get("stream_options") or {}).get("include_usage"))+ from core.inference.llama_keepwarm import mark_response_failed+client = httpx.AsyncClient(timeout = _llama_streaming_generation_timeout(),trust_env = False,@@ -19504,20 +20103,31 @@ async def openai_completions(request: Request, current_subject: str = Depends(gebuffer += chunkwhile b"\n\n" in buffer:event, buffer = buffer.split(b"\n\n", 1)- _monitor_openai_sse_event(- monitor_id,- event,- llama_backend.context_length,- )+ if (+ _monitor_openai_sse_event(+ monitor_id,+ event,+ llama_backend.context_length,+ )+ == "error"+ ):+ # Upstream forwarded an HTTP-200 SSE error event: the stream failed,+ # so don't let the middleware claim the slot and evict a+ # preview-owned model.+ mark_response_failed(getattr(request, "scope", None))out = _cmpl_stream_event_out(event, _include_usage)if out is not None:yield out + b"\n\n"if not disconnect_event.is_set() and buffer:- _monitor_openai_sse_event(- monitor_id,- buffer,- llama_backend.context_length,- )+ if (+ _monitor_openai_sse_event(+ monitor_id,+ buffer,+ llama_backend.context_length,+ )+ == "error"+ ):+ mark_response_failed(getattr(request, "scope", None))out = _cmpl_stream_event_out(buffer, _include_usage)if out is not None:# Re-add the SSE separator the split consumed, so a final@@ -19525,6 +20135,7 @@ async def openai_completions(request: Request, current_subject: str = Depends(ge# terminated for the client's parser.yield out + b"\n\n"if disconnect_event.is_set():+ mark_response_failed(getattr(request, "scope", None))api_monitor.finish(monitor_id, "cancelled")returnapi_monitor.finish(monitor_id)@@ -19535,6 +20146,7 @@ async def openai_completions(request: Request, current_subject: str = Depends(geerror_chunk = _openai_stream_error_chunk(e)yield _openai_stream_error_sse_bytes(error_chunk)return+ mark_response_failed(getattr(request, "scope", None))api_monitor.finish(monitor_id, "cancelled")returnexcept asyncio.CancelledError:@@ -19543,6 +20155,7 @@ async def openai_completions(request: Request, current_subject: str = Depends(geraiseexcept Exception as e:if disconnect_event.is_set():+ mark_response_failed(getattr(request, "scope", None))api_monitor.finish(monitor_id, "cancelled")returnlogger.error("openai_completions stream error: %s", e)@@ -19655,15 +20268,16 @@ async def openai_embeddings(request: Request, current_subject: str = Depends(geterror (expected)."""llama_backend = get_llama_cpp_backend()- # Reject a request with no input before any automatic load so an invalid- # request never swaps or reloads the resident model (as chat/responses/messages- # already validate before switching). Gate on every automatic-load trigger,- # not just auto-switch, since a standalone idle TTL can also reload here.- if _automatic_model_load_may_run():+ # Reject a request with no input before any automatic load so an invalid request never+ # swaps or reloads the resident model (as chat/responses/messages already validate before+ # switching). Gate on every automatic-load trigger (not just auto-switch: a standalone idle+ # TTL can also reload here), and on a preview-owned slot the switch helper would claim even+ # with both features off.+ if _should_validate_before_switch():try:_pre = await request.json()except (json.JSONDecodeError, ValueError):- _pre = None+ _pre = _UNPARSEABLE_BODYif isinstance(_pre, dict):_pre_input = _pre.get("input")if _pre_input is not None and not isinstance(_pre_input, (str, list, tuple)):@@ -19673,7 +20287,17 @@ async def openai_embeddings(request: Request, current_subject: str = Depends(getraise HTTPException(status_code = 400, detail = "'input' must be a string or array.")if not _embeddings_input_present(_pre):raise HTTPException(status_code = 400, detail = "'input' is required for embeddings.")- # Auto-switch applies here too; the target launches embedding-enabled only if it pools.+ elif _pre is not _UNPARSEABLE_BODY:+ # A valid JSON body that is not an object (e.g. [] or null) is rejected below as+ # "Request body must be a JSON object"; reject it here, before the switch, so the+ # slot claim can't convert a preview-owned model to Studio-owned for a request+ # that never runs.+ raise HTTPException(status_code = 400, detail = "Request body must be a JSON object")+ # Embeddings is a model-bearing inference path too, so honor auto-switch. Unlike+ # vision (cheaply pre-checked via a companion mmproj), GGUF pooling capability has+ # no reliable pre-load probe -- is_embedding_model keys on a sentence-transformers+ # modules.json a bare .gguf never has -- so embeddings auto-switch is best-effort:+ # a non-embedding target switches, then llama-server returns a no-pooling error.body = await _auto_switch_from_request_body(request, current_subject)if not llama_backend.is_loaded:_status, _detail = await _no_model_loaded_error(@@ -19690,6 +20314,11 @@ async def openai_embeddings(request: Request, current_subject: str = Depends(getif not isinstance(body, dict):raise HTTPException(status_code = 400, detail = "Request body must be a JSON object")+ # GGUF is loaded and the body is valid. The middleware claims the slot on a successful+ # 2xx, so no claim here: llama-server can still return a non-2xx for a valid body (e.g. a+ # no-pooling error on /v1/embeddings against a non-embedding GGUF), so claiming before the+ # upstream response would strand a preview-owned checkpoint as Studio-owned.+target_url = f"{llama_backend.base_url}/v1/embeddings"prompt_text = _flatten_monitor_prompt(body.get("input", ""))monitor_id = None@@ -20492,6 +21121,8 @@ async def _responses_stream((Codex, OpenAI Python SDK) can reconstruct the call incrementally and replywith a ``function_call_output`` item next turn."""+ from core.inference.llama_keepwarm import mark_response_failed+resp_id = f"resp_{uuid.uuid4().hex[:12]}"created_at = int(time.time())@@ -20561,6 +21192,9 @@ async def _responses_stream(raise _openai_admission_http_exception(exc, status_code = 429)def _responses_admission_failed_sse(exc: Exception, *, status_code: int) -> str:+ # Emitted in-band after the 200 headers, so flag failed: the middleware must not+ # treat this failed stream as a success and claim a preview-owned model.+ mark_response_failed(getattr(request, "scope", None))return ("event: response.failed\n""data: "@@ -20947,6 +21581,9 @@ async def _responses_stream(return [item for _, item in sorted(indexed_items, key = lambda pair: pair[0])]def _failed_response_payload(exc: Exception, status_code: int) -> dict:+ # Built only for in-band response.failed events after the 200 headers, so+ # flag failed: the middleware must not treat a failed stream as a success.+ mark_response_failed(getattr(request, "scope", None))return {"type": "response.failed","response": {@@ -21017,6 +21654,9 @@ async def _responses_stream(except httpx.RequestError as e:logger.error("responses stream: upstream unreachable: %s", e)api_monitor.fail(monitor_id, _friendly_error(e))+ # 200 headers already flushed; this is an in-band failure, so the+ # middleware must not claim a preview-owned model for it.+ mark_response_failed(getattr(request, "scope", None))yield _sse("response.failed",{@@ -21043,6 +21683,9 @@ async def _responses_stream(err_text[:500],)api_monitor.fail(monitor_id, err_text[:500])+ # 200 headers already flushed; an upstream non-200 is an in-band+ # failure, so the middleware must not claim a preview-owned model.+ mark_response_failed(getattr(request, "scope", None))yield _sse("response.failed",{@@ -21090,6 +21733,18 @@ async def _responses_stream(choices = chunk_data.get("choices", [])if not choices:+ error_message = _monitor_openai_error_message(chunk_data)+ if error_message:+ # Upstream HTTP-200 SSE error payload (data: {"error": ...}) is a failed+ # generation, not a usage-only frame. Fail the monitor and convert to+ # response.failed (which flags the scope) so a later response.completed+ # can't fire and the middleware can't claim a preview-owned slot.+ api_monitor.fail(monitor_id, error_message)+ yield _sse(+ "response.failed",+ _failed_response_payload(RuntimeError(error_message), 502),+ )+ return_apply_usage(chunk_data.get("usage"), chunk_data.get("timings"))continueif choices[0].get("finish_reason"):@@ -21192,6 +21847,7 @@ async def _responses_stream(returnexcept Exception as e:if disconnect_event.is_set():+ mark_response_failed(getattr(request, "scope", None))api_monitor.finish(monitor_id, "cancelled")returnlogger.error("responses stream error: %s", e)@@ -21211,6 +21867,9 @@ async def _responses_stream()if disconnect_event.is_set():+ # Client disconnected after the 200 headers: a cancelled generation, not a+ # success. Flag failed so the middleware doesn't clear preview ownership.+ mark_response_failed(getattr(request, "scope", None))api_monitor.finish(monitor_id, "cancelled")return@@ -21610,6 +22269,10 @@ async def openai_responses(request,current_subject,require_vision = _messages_have_image(messages),+ # Streaming Responses require a GGUF backend and 400 in _responses_stream after this+ # switch; claiming here would strand a preview-owned model as Studio-owned for a+ # request that never generates. Defer to the middleware, which claims on a 2xx.+ claim_resident = False,)if payload.stream:@@ -22071,6 +22734,9 @@ async def anthropic_count_tokens(request,current_subject,require_vision = _anthropic_request_has_image(payload),+ # count_tokens only tokenizes (no generation), so it must not adopt the resident+ # model; the middleware likewise excludes count_tokens from its claim.+ claim_resident = False,)llama_backend = get_llama_cpp_backend()@@ -22273,6 +22939,10 @@ async def anthropic_messages(request,current_subject,require_vision = _anthropic_request_has_image(payload),+ # The image normalization below can still 400 after this switch, so defer the claim:+ # the middleware claims on a 2xx, so a rejected request never strands a preview-owned+ # model.+ claim_resident = False,)if not llama_backend.is_loaded:_status, _detail = await _no_model_loaded_error(@@ -22914,6 +23584,8 @@ async def _anthropic_tool_stream()async def _stream():+ from core.inference.llama_keepwarm import mark_response_failed+# The server-tool loop decodes on llama-server for its whole body, so without an entry a# non-forced /unload saw zero generations and tore the server down mid-response. Entered# inside the body generator so a response whose body never starts leaves nothing behind.@@ -22953,6 +23625,9 @@ async def _anthropic_tool_stream(while True:if cancel_event.is_set() or await request.is_disconnected():cancel_event.set()+ # Cancelled before completion: flag failed so the middleware does not+ # claim a preview-owned model for a stream that never finished.+ mark_response_failed(getattr(request, "scope", None))return# Stall keepalive (see GGUF tool stream): silent backend segments must not# leave the SSE stream idle past proxy timeouts.@@ -23078,6 +23753,8 @@ async def _anthropic_plain_stream()async def _stream():+ from core.inference.llama_keepwarm import mark_response_failed+# Registered like the tool stream above: this default /v1/messages path decodes on# llama-server, so without an entry a non-forced /unload tore it down mid-response._tracker = _TrackedCancel(cancel_event, model = model_name, kind = "messages")@@ -23102,6 +23779,9 @@ async def _anthropic_plain_stream(while True:if cancel_event.is_set() or await request.is_disconnected():cancel_event.set()+ # Cancelled before completion: flag failed so the middleware does not+ # claim a preview-owned model for a stream that never finished.+ mark_response_failed(getattr(request, "scope", None))return# Stall keepalive each window while next(gen) runs in a worker._next_task = asyncio.create_task(asyncio.to_thread(next, gen, _sentinel))@@ -23976,6 +24656,12 @@ async def _anthropic_passthrough_stream(resp.status_code,_err_text,)+ # The outer 200 stream headers are already flushed, so flag the failure: the+ # middleware must not claim a preview-owned model on a passthrough whose+ # upstream errored before any SSE.+ from core.inference.llama_keepwarm import mark_response_failed++ mark_response_failed(getattr(request, "scope", None))yield build_anthropic_sse_event("error",anthropic_error_body(@@ -24008,6 +24694,24 @@ async def _anthropic_passthrough_stream(chunk = json.loads(data_str)except json.JSONDecodeError:continue+ if isinstance(chunk, dict):+ error_message = _monitor_openai_error_message(chunk)+ if error_message:+ # Upstream HTTP-200 SSE error payload (data: {"error": ...}):+ # emitter.feed_chunk ignores chunks without choices, so the stream+ # would finish cleanly and the middleware would claim a preview-owned+ # model. Flag failed and surface an Anthropic error event instead of a+ # silent message_stop (mirrors the OpenAI passthrough / Responses).+ from core.inference.llama_keepwarm import mark_response_failed++ mark_response_failed(getattr(request, "scope", None))+ event = _anthropic_stream_error_event(+ RuntimeError(error_message),+ force = True,+ )+ if event is not None:+ yield event+ returnif disable_parallel_tool_use:_drop_parallel_tool_call_deltas(chunk)for line in emitter.feed_chunk(chunk):@@ -24016,6 +24720,12 @@ async def _anthropic_passthrough_stream(if not cancel_event.is_set():logger.error("anthropic_messages passthrough stream error: %s", e)get_llama_cpp_backend()._maybe_recover_from_mtp_crash(e)+ # The stream already sent HTTP 200, so flag the failure: the middleware must+ # not claim a preview-owned model on a passthrough stream that errored+ # mid-response.+ from core.inference.llama_keepwarm import mark_response_failed++ mark_response_failed(getattr(request, "scope", None))event = _anthropic_stream_error_event(e,force = True,@@ -24024,6 +24734,9 @@ async def _anthropic_passthrough_stream(yield eventreturnfinally:+ if cancel_event.is_set():+ from core.inference.llama_keepwarm import mark_response_failed+ mark_response_failed(getattr(request, "scope", None))# Same shape as the OpenAI passthrough: the tracker exits after the closes,# and the bounded teardown awaits cannot hold it indefinitely.try:@@ -24989,6 +25702,9 @@ async def _openai_passthrough_stream_admitted(_tracker = trackertarget_url = f"{llama_backend.base_url}/v1/chat/completions"upstream_headers = _openai_passthrough_upstream_headers(llama_backend = llama_backend)+ # A mid-stream llama-server error keeps HTTP 200, so flag the scope when one is seen: the+ # middleware must not claim a preview-owned model on a failed passthrough stream.+ from core.inference.llama_keepwarm import mark_response_failedclient = Noneresp = None@@ -25583,6 +26299,7 @@ async def _openai_passthrough_stream_admitted(# finish would fire after a failed stream.if _monitor_openai_error_message(chunk_data):saw_stream_error = True+ mark_response_failed(getattr(request, "scope", None))# With healing active, a content-bearing line may be replaced by# held/promoted chunks; otherwise the single (already# normalized) line relays unchanged (monitored exactly as@@ -25631,6 +26348,7 @@ async def _openai_passthrough_stream_admitted()if monitor_event == "error":saw_stream_error = True+ mark_response_failed(getattr(request, "scope", None))# Relay to preserve llama-server's native id,# finish_reason, delta.tool_calls, and usage chunks.yield out_line + "\n\n"@@ -25723,6 +26441,10 @@ async def _openai_passthrough_stream_admitted(if not cancel_event.is_set():api_monitor.fail(monitor_id, "Stream interrupted")get_llama_cpp_backend()._maybe_recover_from_mtp_crash(e)+ # 200 headers already flushed and we re-raise without an error SSE, so flag+ # the failure: the middleware must not claim a preview-owned model on an+ # interrupted stream.+ mark_response_failed(getattr(request, "scope", None))raiseapi_monitor.finish(monitor_id, "cancelled")except HTTPException as exc:@@ -25746,6 +26468,8 @@ async def _openai_passthrough_stream_admitted(err = _openai_stream_error_chunk(e)yield _openai_stream_error_sse(err)finally:+ if cancel_event.is_set():+ mark_response_failed(getattr(request, "scope", None))# Close the upstream stream first: on disconnect llama-server keeps decoding# until resp is closed, so releasing the slot earlier admits a second request# past --parallel. Safe to hold the slot across these closes because everydiff --git a/studio/backend/routes/preview.py b/studio/backend/routes/preview.pyindex 0ef732220cc..34cae033aff 100644--- a/studio/backend/routes/preview.py+++ b/studio/backend/routes/preview.py@@ -19,7 +19,7 @@ from auth.storage import DEFAULT_ADMIN_USERNAMEfrom models.inference import ChatCompletionRequest, LoadRequestfrom routes.inference import (disable_openai_auto_switch_for_request,- load_model_gated,+ load_model_for_preview,openai_chat_completions,)from state.tool_policy import tools_force_disabled@@ -33,18 +33,15 @@ logger = get_logger(__name__)router = APIRouter()-# A shared preview link is a public bearer capability; cap per-request generation-# so a single call can't tie up the (serialized) preview GPU indefinitely.+# A shared preview link is a public bearer capability; cap per-request generation so a+# single call can't tie up the (serialized) preview GPU indefinitely._PREVIEW_MAX_OUTPUT_TOKENS = 1024-# Capability-gated (signed ref required); resolve_preview_checkpoint pins `run`-# under outputs_root. One model loads at a time, so serialize load+generate.+# One model loads at a time, so serialize load+generate._preview_lock = asyncio.Lock()def _extract_token(request: Request) -> str | None:- """Capability token from the ``?k=`` query (browser link + preview page) or an- ``Authorization: Bearer`` header (OpenAI-compatible clients using it as api_key)."""token = request.query_params.get("k")if token:return token@@ -55,18 +52,6 @@ def _extract_token(request: Request) -> str | None:def _verify_or_404(run: str, checkpoint: str | None, request: Request) -> None:- """Require a valid preview capability BEFORE any checkpoint resolve / model load.-- Missing or invalid tokens get a generic 404 -- identical to a non-existent ref --- so the public surface never confirms whether a run/checkpoint exists. When an- admin has switched public sharing off, every public request 404s regardless of- token.-- Verify the (cheap, no-I/O) capability first: an unauthenticated caller with a- bad/missing token is rejected without the kill-switch DB read, so spamming- ``/p/...`` can't be used as an unbounded settings-DB sink, and the response is- identical whether or not sharing is enabled (no on/off oracle).- """ref = run if not checkpoint else f"{run}/{checkpoint}"if not verify_preview_ref(ref, _extract_token(request)):raise HTTPException(status_code = 404, detail = "Not found")@@ -75,7 +60,6 @@ def _verify_or_404(run: str, checkpoint: str | None, request: Request) -> None:def _enforce_rate_limit(request: Request) -> None:- """Throttle the GPU-backed preview chat per client IP (429 on exceed)."""retry_after = check_rate_limit(client_ip(request))if retry_after:raise HTTPException(@@ -100,15 +84,6 @@ def _resolve_or_4xx(run: str, checkpoint: str | None):def _sanitize_preview_payload(payload: ChatCompletionRequest, is_lora: bool) -> ChatCompletionRequest:- # Public surface: strip tools/MCP + provider routing (no host code / open proxy).- # Normalize use_adapter (never trust the caller): pin True for LoRA, None for- # merged. _apply_adapter_state mutates the shared model without restoring, so an- # unpinned `false` would persist to later visitors who omit the field.- #- # Cap generation cost on this public, GPU-backed surface. Derive one effective- # limit (mirroring _effective_max_tokens: max_completion_tokens wins, else the- # legacy max_tokens) and pin BOTH fields to it, so a caller's lower limit is- # honored and neither field can exceed the ceiling.requested = (payload.max_completion_tokensif payload.max_completion_tokens is not None@@ -136,6 +111,9 @@ def _sanitize_preview_payload("external_model": None,"encrypted_api_key": None,"provider_base_url": None,+ "enable_thinking": False,+ "reasoning_effort": "none",+ "preserve_thinking": False,"use_adapter": True if is_lora else None,"max_tokens": capped_max_tokens,"max_completion_tokens": capped_max_tokens,@@ -145,7 +123,6 @@ def _sanitize_preview_payload(async def _unlock_after(body_iterator):- # Hold the lock until the stream drains so another checkpoint can't swap mid-stream.try:async for chunk in body_iterator:yield chunk@@ -159,17 +136,29 @@ async def _serve_chat(path = _resolve_or_4xx(run, checkpoint)is_lora = (path / "adapter_config.json").exists()payload = _sanitize_preview_payload(payload, is_lora)- # Preview always serves the pinned checkpoint it loads below; a public caller's- # `model` field must never trigger an OpenAI auto-switch to another GGUF.- disable_openai_auto_switch_for_request(getattr(request, "scope", None))- await _preview_lock.acquire()+ scope = getattr(request, "scope", None)+ disable_openai_auto_switch_for_request(scope)+ from core.inference.llama_keepwarm import (+ begin_preview_serializer_wait,+ cancel_preview_serializer_wait,+ resume_preview_after_serializer,+ )++ serializer_waiting = begin_preview_serializer_wait(scope)keep_locked = False+ locked = Falsetry:- # The gated coroutine, not the /load route: the route's padding returns a+ await _preview_lock.acquire()+ locked = True+ if serializer_waiting:+ await resume_preview_after_serializer(scope)+ serializer_waiting = False+ # The in-process coroutine, not the /load route: the route's padding returns a# StreamingResponse while the checkpoint is still loading, so the chat below# would run against the previous model (or none).- await load_model_gated(LoadRequest(model_path = str(path)), request, DEFAULT_ADMIN_USERNAME)- # Beats a process-wide `--enable-tools` (enable_tools=False alone wouldn't).+ await load_model_for_preview(+ LoadRequest(model_path = str(path)), request, DEFAULT_ADMIN_USERNAME+ )with tools_force_disabled():response = await openai_chat_completions(payload, request, DEFAULT_ADMIN_USERNAME)if isinstance(response, StreamingResponse):@@ -177,7 +166,9 @@ async def _serve_chat(keep_locked = Truereturn responsefinally:- if not keep_locked:+ if serializer_waiting:+ cancel_preview_serializer_wait(scope)+ if not keep_locked and locked:_preview_lock.release()@@ -192,10 +183,6 @@ async def list_previews(previews = []for target in list_preview_targets():ref = quote(target["ref"], safe = "/")- # Mint the capability for the authenticated owner: ``key`` for OpenAI- # clients (Bearer / api_key), ``share_url`` for the browser link. When- # public sharing is off, every public /p request 404s, so don't hand out- # dead credentials -- omit the capability and signal the disabled state.token = sign_preview_ref(target["ref"]) if sharing_on else Nonepreviews.append({diff --git a/studio/backend/tests/test_gpu_arbiter.py b/studio/backend/tests/test_gpu_arbiter.pyindex 0d9f62ad7ed..de553b9de41 100644--- a/studio/backend/tests/test_gpu_arbiter.py+++ b/studio/backend/tests/test_gpu_arbiter.py@@ -43,6 +43,15 @@ def test_chat_load_evicts_diffusion(calls):assert arb.current_owner() == arb.CHAT+def test_chat_load_can_refuse_to_evict_diffusion(calls):+ arb.acquire_for(arb.DIFFUSION)+ with pytest.raises(arb.GpuOwnerBusyError) as excinfo:+ arb.acquire_for(arb.CHAT, allow_evict = False)+ assert excinfo.value.owner == arb.DIFFUSION+ assert calls == []+ assert arb.current_owner() == arb.DIFFUSION++def test_reacquiring_same_owner_does_not_evict(calls):arb.acquire_for(arb.CHAT)arb.acquire_for(arb.CHAT)@@ -332,9 +341,7 @@ def test_the_safetensors_load_yields_a_gpu_it_lost_while_loading():encoding = "utf-8")load_impl = route_src[route_src.index("async def _load_model_impl") :]- unsloth_load = load_impl.index(- "success = await asyncio.to_thread(\n backend.load_model,"- )+ unsloth_load = load_impl.index("success = await asyncio.to_thread(")tail = load_impl[unsloth_load:]guard = tail.index("if current_owner() != CHAT:")assert "await asyncio.to_thread(backend.unload_model, config.identifier)" in tail[guard:]diff --git a/studio/backend/tests/test_openai_audio_speech_route.py b/studio/backend/tests/test_openai_audio_speech_route.pyindex 5b98f85b696..05a27e77a9c 100644--- a/studio/backend/tests/test_openai_audio_speech_route.py+++ b/studio/backend/tests/test_openai_audio_speech_route.py@@ -221,7 +221,7 @@ def test_the_budget_is_rechecked_after_an_idle_model_is_restored():restore = next(ifor i, line in enumerate(source.splitlines())- if "_maybe_auto_switch_model(_RELOAD_ONLY_MODEL" in line+ if "_RELOAD_ONLY_MODEL, request, current_subject" in line)assert len(guards) == 2, "one check before the restore, one after"assert guards[0] < restore < guards[1]diff --git a/studio/backend/tests/test_openai_auto_download.py b/studio/backend/tests/test_openai_auto_download.pyindex 313d6aa87ed..0a88a1ef0db 100644--- a/studio/backend/tests/test_openai_auto_download.py+++ b/studio/backend/tests/test_openai_auto_download.py@@ -15,6 +15,7 @@ import pytestfrom fastapi import HTTPExceptionimport routes.inference as inference_route+from core.inference import llama_keepwarmfrom core.inference import openai_auto_download as auto_dlfrom core.inference.local_model_resolver import warm_index_soon as _real_warm_index_soonfrom utils import openai_auto_switch_settings as settings@@ -66,10 +67,14 @@ def _clean_slot():from core.inference import local_model_resolverauto_dl.reset_for_tests()+ with llama_keepwarm._lock:+ llama_keepwarm._admitted_inference = 0# The hook warms the index in the background; drop it so a scan never leaks between tests.local_model_resolver.invalidate_index()yieldauto_dl.reset_for_tests()+ with llama_keepwarm._lock:+ llama_keepwarm._admitted_inference = 0local_model_resolver.invalidate_index()diff --git a/studio/backend/tests/test_openai_auto_switch.py b/studio/backend/tests/test_openai_auto_switch.pyindex b6e9b7d7dc2..5be321ba599 100644--- a/studio/backend/tests/test_openai_auto_switch.py+++ b/studio/backend/tests/test_openai_auto_switch.py@@ -3258,11 +3258,13 @@ def test_chat_audio_input_guards_target_before_switch(monkeypatch):require_vision = False,require_image = True,modality_label = "image or audio",+ claim_resident = True,):captured.update(require_vision = require_vision,require_image = require_image,modality_label = modality_label,+ claim_resident = claim_resident,)raise _Reached()@@ -3276,6 +3278,7 @@ def test_chat_audio_input_guards_target_before_switch(monkeypatch):"require_vision": True,"require_image": False,"modality_label": "audio",+ "claim_resident": False,}# An image in the same request does need the vision tower.@@ -3291,6 +3294,7 @@ def test_chat_audio_input_guards_target_before_switch(monkeypatch):"require_vision": True,"require_image": True,"modality_label": "image or audio",+ "claim_resident": False,}@@ -3481,8 +3485,9 @@ def test_require_vision_probes_the_quant_the_load_will_open(monkeypatch):monkeypatch.setattr(inference_route,"_target_is_vision",- lambda path, variant = None, need_image = True: probed.append((path, variant, need_image))- or True,+ lambda path, variant = None, need_image = True: (+ probed.append((path, variant, need_image)) or True+ ),)asyncio.run(inference_route._maybe_auto_switch_model("org/B-GGUF", object(), "t", require_vision = True)@@ -3646,8 +3651,10 @@ def test_count_tokens_forwards_vision_guard_to_switch(monkeypatch):subject,*,require_vision = False,+ claim_resident = True,):captured["require_vision"] = require_vision+ captured["claim_resident"] = claim_residentraise _Reached()monkeypatch.setattr(inference_route, "_anthropic_request_has_image", lambda p: True)@@ -3656,6 +3663,7 @@ def test_count_tokens_forwards_vision_guard_to_switch(monkeypatch):with pytest.raises(_Reached):asyncio.run(inference_route.anthropic_count_tokens(payload, object(), "tester"))assert captured["require_vision"] is True+ assert captured["claim_resident"] is False# ── /chat/count_tokens: what the recount prices ───────────────────@@ -4767,8 +4775,10 @@ def test_audio_generate_is_reload_only(monkeypatch):subject,*,require_vision = False,+ claim_resident = True,):captured["model"] = model+ captured["claim_resident"] = claim_residentraise _Reached()monkeypatch.setattr(inference_route, "_maybe_auto_switch_model", _capture)@@ -4778,6 +4788,7 @@ def test_audio_generate_is_reload_only(monkeypatch):with pytest.raises(_Reached):asyncio.run(inference_route.generate_audio(payload, object(), "tester"))assert captured["model"] == inference_route._RELOAD_ONLY_MODEL+ assert captured["claim_resident"] is Falsedef test_note_model_unloaded_clears_reload_stash(monkeypatch):@@ -8158,11 +8169,13 @@ def test_a_video_request_labels_the_switch_refusal_video(monkeypatch):require_vision = False,require_image = True,modality_label = "image or audio",+ claim_resident = True,):captured.update(require_vision = require_vision,require_image = require_image,modality_label = modality_label,+ claim_resident = claim_resident,)raise _Reached()@@ -8176,4 +8189,73 @@ def test_a_video_request_labels_the_switch_refusal_video(monkeypatch):"require_vision": True,"require_image": False,"modality_label": "video",+ "claim_resident": False,}+++# Preview ownership regressions.+++def test_count_tokens_switch_marks_new_model_preview_owned(monkeypatch):+ backend = _FakeBackend("org/A-GGUF")+ recorder = _LoadRecorder(backend)+ _wire(+ monkeypatch,+ enabled = True,+ resolves_to = ("org/B-GGUF", None, "org/B-GGUF"),+ backend = backend,+ recorder = recorder,+ )+ inference_route._set_preview_resident("org/A-GGUF")+ asyncio.run(+ inference_route._maybe_auto_switch_model(+ "org/B-GGUF", object(), "tester", claim_resident = False+ )+ )+ assert len(recorder.calls) == 1+ assert inference_route._is_preview_resident("org/B-GGUF")+ inference_route._set_preview_resident(None) # cleanup+++def test_count_tokens_does_not_own_an_independent_load(monkeypatch):+ state = {"slot": "/outputs/preview-a"}+ identity_checked = threading.Event()+ independent_load_done = threading.Event()++ def loaded_identity_satisfies(_requested):+ identity_checked.set()+ assert independent_load_done.wait(timeout = 2)+ return True++ async def no_model_error(*_args, **_kwargs):+ return 503, "No GGUF model loaded"++ monkeypatch.setattr(inference_route, "_loaded_slot_ident", lambda: state["slot"])+ monkeypatch.setattr(inference_route, "_loaded_identity_satisfies", loaded_identity_satisfies)+ monkeypatch.setattr(inference_route, "_no_model_loaded_error", no_model_error)+ monkeypatch.setattr(settings, "get_openai_auto_switch_enabled", lambda: True)+ monkeypatch.setattr(resolver, "warm_index_soon", lambda: None)+ monkeypatch.setattr(+ inference_route,+ "get_llama_cpp_backend",+ lambda: types.SimpleNamespace(is_loaded = False),+ )++ inference_route._set_preview_resident(state["slot"])+ payload = _anthropic_payload_with_tools(None)+ request = types.SimpleNamespace(scope = {"path": "/v1/messages/count_tokens"})++ async def drive():+ task = asyncio.create_task(+ inference_route.anthropic_count_tokens(payload, request, "tester")+ )+ assert await asyncio.to_thread(identity_checked.wait, 2)+ state["slot"] = "/outputs/studio-b"+ inference_route._set_preview_resident(None)+ independent_load_done.set()+ with pytest.raises(HTTPException) as exc:+ await task+ assert exc.value.status_code == 503++ asyncio.run(drive())+ assert not inference_route._is_preview_resident("/outputs/studio-b")diff --git a/studio/backend/tests/test_preview_routes.py b/studio/backend/tests/test_preview_routes.pyindex bad8ac2032e..50903c2a8a8 100644--- a/studio/backend/tests/test_preview_routes.py+++ b/studio/backend/tests/test_preview_routes.py@@ -4,7 +4,7 @@"""Security smoke for the public /p preview routes.Exercises the route layer with a real ``preview_router`` while stubbing the-expensive model calls (``load_model_gated`` / ``openai_chat_completions``). Covers the+expensive model calls (``load_model_for_preview`` / ``openai_chat_completions``). Covers thepublic-surface guarantees: HMAC capability gating (a valid ``?k=`` token orBearer credential is required; missing/invalid/wrong-ref tokens 404 before anymodel load), path-traversal rejection, request sanitization (tools / provider@@ -96,7 +96,7 @@ def client(tmp_path, monkeypatch, captured):captured["payload"] = payloadreturn {"ok": True}- monkeypatch.setattr(preview, "load_model_gated", _fake_load_model)+ monkeypatch.setattr(preview, "load_model_for_preview", _fake_load_model)monkeypatch.setattr(preview, "openai_chat_completions", _fake_chat)app = FastAPI()@@ -122,11 +122,17 @@ def test_page_renders_with_csp(client):assert "messages: msgs,\n stream: true," in r.text+def test_page_renders_friendly_busy_message(client):+ response = client.get(f"/p/demorun?k={_sig('demorun')}")+ assert "Studio is currently using another model" in response.text++def test_page_escapes_title(tmp_path, monkeypatch, captured):outputs = tmp_path / "outputs"# Run dir name carries an HTML-special char; the page must escape it._make_run(outputs, name = "a<b")_use_test_secret(monkeypatch)+ monkeypatch.setattr(preview, "get_preview_sharing_enabled", lambda: True)from utils.paths import storage_roots as _srmonkeypatch.setattr(_sr, "outputs_root", lambda: outputs)@@ -256,6 +262,9 @@ def test_chat_payload_sanitized(client, captured):"confirm_tool_calls": True,"session_id": "abc","rag_scope": {"project_id": "x"},+ "enable_thinking": True,+ "reasoning_effort": "high",+ "preserve_thinking": True,},)assert r.status_code == 200@@ -276,6 +285,9 @@ def test_chat_payload_sanitized(client, captured):assert p.provider_type is Noneassert p.provider_base_url is Noneassert p.external_model is None+ assert p.enable_thinking is False+ assert p.reasoning_effort == "none"+ assert p.preserve_thinking is False# Adapter pinned on for LoRA: a caller can't flip the shared backend to base.assert p.use_adapter is True# Generation cost capped on this public surface (no override sent -> ceiling).@@ -294,6 +306,7 @@ def test_merged_checkpoint_strips_use_adapter(tmp_path, monkeypatch, captured):(merged / "config.json").write_text(json.dumps({"_name_or_path": "some/base"}))_use_test_secret(monkeypatch)+ monkeypatch.setattr(preview, "get_preview_sharing_enabled", lambda: True)from utils.paths import storage_roots as _srmonkeypatch.setattr(_sr, "outputs_root", lambda: outputs)@@ -305,7 +318,7 @@ def test_merged_checkpoint_strips_use_adapter(tmp_path, monkeypatch, captured):captured["payload"] = payloadreturn {"ok": True}- monkeypatch.setattr(preview, "load_model_gated", _fake_load)+ monkeypatch.setattr(preview, "load_model_for_preview", _fake_load)monkeypatch.setattr(preview, "openai_chat_completions", _fake_chat)app = FastAPI()@@ -339,7 +352,7 @@ def test_streaming_holds_lock_until_drained(tmp_path, monkeypatch, captured):async def _fake_chat(payload, request, subject):return StreamingResponse(_gen())- monkeypatch.setattr(preview, "load_model_gated", _fake_load_model)+ monkeypatch.setattr(preview, "load_model_for_preview", _fake_load_model)monkeypatch.setattr(preview, "openai_chat_completions", _fake_chat)async def _run():@@ -508,3 +521,418 @@ def test_chat_rate_limited_returns_429(client, monkeypatch):r = client.post(url, json = body)assert r.status_code == 429assert r.headers.get("retry-after")+++# Model-slot ownership regressions.+import threading+from types import SimpleNamespace++from fastapi import HTTPException++import routes.inference as inference+from core.inference import llama_keepwarm+from models.inference import LoadRequest++[email protected](autouse = True)+def reset_admitted_inference():+ with llama_keepwarm._lock:+ llama_keepwarm._admitted_inference = 0+ yield+ with llama_keepwarm._lock:+ llama_keepwarm._admitted_inference = 0+++def slot_state():+ def _reset():+ with inference._preview_slot_lock:+ inference._preview_resident_ident = None++ _reset()+ yield+ _reset()+++def fake_slot(slot_state, monkeypatch):+ state = {"ident": None, "loads": [], "load_kwargs": []}++ async def _fake_impl(load_req, fastapi_request, subject, **kwargs):+ state["loads"].append(load_req.model_path)+ state["load_kwargs"].append(kwargs)+ if state.get("fail_load"):+ state["ident"] = None+ raise HTTPException(status_code = 500, detail = "load failed")+ state["ident"] = load_req.model_path++ monkeypatch.setattr(inference, "_load_model_impl", _fake_impl)+ monkeypatch.setattr(inference, "_loaded_slot_ident", lambda: state["ident"])+ monkeypatch.setattr(+ llama_keepwarm, "other_admitted_inference_count", lambda: state.get("busy", 0)+ )+ return state+++def _run_middleware(app, path):+ mw = llama_keepwarm.LlamaKeepWarmMiddleware(app)+ scope = {"type": "http", "method": "POST", "path": path}+ sent = []++ async def _receive():+ return {"type": "http.request", "body": b"", "more_body": False}++ async def _send(msg):+ sent.append(msg)++ asyncio.run(mw(scope, _receive, _send))+ return sent+++def _reset_keepwarm_counters():+ llama_keepwarm._pending = 0+ llama_keepwarm._preview_pending = 0+ llama_keepwarm._inflight = 0+ llama_keepwarm._preview_inflight = 0+++def test_preview_load_refused_when_studio_model_is_loaded(fake_slot):+ fake_slot["ident"] = "owner-model"++ async def _run():+ with pytest.raises(HTTPException) as exc:+ await inference.load_model_for_preview(+ LoadRequest(model_path = "/outputs/run/ckpt"),+ SimpleNamespace(app = None),+ "admin",+ )+ return exc.value++ exc = asyncio.run(_run())+ assert exc.status_code == 503+ assert exc.headers.get("Retry-After")+ assert fake_slot["loads"] == []+ assert fake_slot["ident"] == "owner-model"+++def test_preview_does_not_borrow_studio_owned_lora(fake_slot, tmp_path):+ checkpoint = tmp_path / "lora-checkpoint"+ checkpoint.mkdir()+ (checkpoint / "adapter_config.json").write_text("{}", encoding = "utf-8")+ fake_slot["ident"] = str(checkpoint)++ async def _run():+ with pytest.raises(HTTPException) as exc:+ await inference.load_model_for_preview(+ LoadRequest(model_path = str(checkpoint)),+ SimpleNamespace(app = None),+ "admin",+ )+ return exc.value++ exc = asyncio.run(_run())+ assert exc.status_code == 503+ assert fake_slot["loads"] == []+ assert not inference._is_preview_resident(str(checkpoint))+++def test_preview_can_swap_out_prior_preview_model(fake_slot):+ for path in ("/outputs/run/ckpt-a", "/outputs/run/ckpt-b"):+ asyncio.run(+ inference.load_model_for_preview(+ LoadRequest(model_path = path), SimpleNamespace(app = None), "admin"+ )+ )+ assert fake_slot["loads"] == ["/outputs/run/ckpt-a", "/outputs/run/ckpt-b"]+ assert fake_slot["ident"] == "/outputs/run/ckpt-b"++[email protected]("owner", ["diffusion", "video"])+def test_preview_load_refused_while_image_or_video_owns_gpu(fake_slot, monkeypatch, owner):+ from core.inference import gpu_arbiter++ monkeypatch.setattr(gpu_arbiter, "current_owner", lambda: owner)++ async def _run():+ with pytest.raises(HTTPException) as exc:+ await inference.load_model_for_preview(+ LoadRequest(model_path = "/outputs/run/ckpt"),+ SimpleNamespace(app = None),+ "admin",+ )+ return exc.value++ exc = asyncio.run(_run())+ assert exc.status_code == 503+ assert exc.headers.get("Retry-After")+ assert fake_slot["loads"] == [] # never reached the load, so nothing was evicted+++def test_preview_maps_atomic_gpu_refusal_to_503(fake_slot, monkeypatch):+ from core.inference import gpu_arbiter++ monkeypatch.setattr(gpu_arbiter, "current_owner", lambda: None)+ swap_notes = []+ monkeypatch.setattr(llama_keepwarm, "note_preview_swap", lambda: swap_notes.append(True))++ async def _lose_gpu_ownership(*args, **kwargs):+ assert kwargs["allow_gpu_owner_eviction"] is False+ raise gpu_arbiter.GpuOwnerBusyError(gpu_arbiter.DIFFUSION)++ monkeypatch.setattr(inference, "_load_model_impl", _lose_gpu_ownership)++ async def _run():+ with pytest.raises(HTTPException) as excinfo:+ await inference.load_model_for_preview(+ LoadRequest(model_path = "/outputs/run/ckpt-a"),+ SimpleNamespace(scope = {"path": "/p/a/v1/chat/completions"}),+ "admin",+ )+ return excinfo.value++ exc = asyncio.run(_run())+ assert exc.status_code == 503+ assert "image or video" in exc.detail+ assert inference._get_preview_resident() is None+ assert swap_notes == []+++def test_preview_reload_failure_restores_prior_ownership(slot_state, monkeypatch):+ resident = {"ident": "/outputs/run/ckpt-A"}+ monkeypatch.setattr(inference, "_loaded_slot_ident", lambda: resident["ident"])+ monkeypatch.setattr(llama_keepwarm, "other_admitted_inference_count", lambda: 0)+ llama_keepwarm._pending = 0+ llama_keepwarm._preview_pending = 0+ inference._set_preview_resident("/outputs/run/ckpt-A") # A is preview-owned++ async def _clear_then_fail(load_req, fastapi_request, subject, **kwargs):+ inference._set_preview_resident(None) # mirror _load_model_impl reclaiming slot+ raise HTTPException(status_code = 500, detail = "spawn failed") # A still resident++ monkeypatch.setattr(inference, "_load_model_impl", _clear_then_fail)++ async def _run():+ with pytest.raises(HTTPException) as exc:+ await inference.load_model_for_preview(+ LoadRequest(model_path = "/outputs/run/ckpt-B"),+ SimpleNamespace(app = None, scope = {"path": "/p/b/v1/chat/completions"}),+ "admin",+ )+ return exc.value++ exc = asyncio.run(_run())+ assert exc.status_code == 500+ assert inference._is_preview_resident("/outputs/run/ckpt-A")+++def test_cancelled_json_response_does_not_claim_slot(slot_state):+ import inspect+ import threading++ src = inspect.getsource(inference.openai_chat_completions)+ assert src.count("_mark_cancelled_json_response_failed(request, cancel_event)") == 3++ _reset_keepwarm_counters()+ inference._set_preview_resident("/outputs/run/ckpt")++ async def _app(scope, receive, send):+ cancelled = threading.Event()+ cancelled.set()+ inference._mark_cancelled_json_response_failed(+ _types.SimpleNamespace(scope = scope), cancelled+ )+ await send({"type": "http.response.start", "status": 200, "headers": []})+ await send({"type": "http.response.body", "body": b"{}", "more_body": False})++ _run_middleware(_app, "/v1/chat/completions")+ assert inference._is_preview_resident("/outputs/run/ckpt")+ _reset_keepwarm_counters()+++def test_queued_preview_does_not_deadlock_studio_switch():+ from core.inference import llama_keepwarm as kw+ async def _run():+ _reset_keepwarm_counters()+ kw._admitted_inference = 0+ preview._preview_lock = asyncio.Lock()+ assert not inference._auto_switch_process_lock.locked()++ studio_holds_gate = asyncio.Event()+ queued_has_serializer = asyncio.Event()+ await preview._preview_lock.acquire()+ kw._note_start(is_preview = True)++ async def _receive():+ return {"type": "http.request", "body": b"", "more_body": False}++ async def _send(_message):+ return None++ async def queued_preview_app(scope, receive, send):+ serializer_waiting = kw.begin_preview_serializer_wait(scope)+ locked = False+ try:+ await preview._preview_lock.acquire()+ locked = True+ queued_has_serializer.set()+ await kw.resume_preview_after_serializer(scope)+ serializer_waiting = False+ await inference._acquire_swap_gate()+ try:+ await send({"type": "http.response.start", "status": 200})+ await send({"type": "http.response.body", "body": b""})+ finally:+ inference._auto_switch_process_lock.release()+ finally:+ if serializer_waiting:+ kw.cancel_preview_serializer_wait(scope)+ if locked:+ preview._preview_lock.release()++ async def studio_switch_app(scope, receive, send):+ kw.note_admitted_inference(scope)+ await inference._acquire_swap_gate()+ try:+ async with kw.inference_lifecycle_gate():+ studio_holds_gate.set()+ await inference._wait_for_model_switch_idle(current_request_counted = True)+ finally:+ inference._auto_switch_process_lock.release()+ await send({"type": "http.response.start", "status": 200})+ await send({"type": "http.response.body", "body": b""})++ preview_scope = {+ "type": "http",+ "method": "POST",+ "path": "/p/run/ckpt/v1/chat/completions",+ "headers": [],+ }+ studio_scope = {+ "type": "http",+ "method": "POST",+ "path": "/v1/chat/completions",+ "headers": [(b"authorization", b"Bearer valid")],+ }+ queued_preview = asyncio.create_task(+ kw.LlamaKeepWarmMiddleware(queued_preview_app)(preview_scope, _receive, _send)+ )+ while kw._preview_pending != 1:+ await asyncio.sleep(0)+ assert kw._preview_inflight == 1 # only active preview A, not queued B++ studio_switch = asyncio.create_task(+ kw.LlamaKeepWarmMiddleware(studio_switch_app)(studio_scope, _receive, _send)+ )+ await asyncio.wait_for(studio_holds_gate.wait(), 1)++ preview._preview_lock.release()+ await asyncio.wait_for(queued_has_serializer.wait(), 1)+ kw._note_end(is_preview = True)++ await asyncio.wait_for(asyncio.gather(queued_preview, studio_switch), 2)+ assert kw._inflight == 0+ assert kw._pending == 0+ assert kw._preview_inflight == 0+ assert kw._preview_pending == 0+ assert kw._admitted_inference == 0++ asyncio.run(_run())+++def test_admitted_inference_counter_excludes_previews():+ from core.inference import llama_keepwarm as kw++ kw._admitted_inference = 0+ kw._inflight += 1 # non-preview request tracked pre-auth (never reached the hook)+ try:+ assert kw.other_admitted_inference_count() == 0 # unadmitted in-flight not counted+ scope = {"path": "/v1/chat/completions"}+ kw.note_admitted_inference(scope) # passed auth, reached the inference hook+ assert kw.other_admitted_inference_count() == 1+ kw.note_admitted_inference(scope) # idempotent per scope+ assert kw.other_admitted_inference_count() == 1+ kw.note_admitted_inference({"path": "/p/run/v1/chat/completions"})+ assert kw.other_admitted_inference_count() == 1+ kw._note_admitted_end() # middleware _finish balances the admit+ assert kw.other_admitted_inference_count() == 0+ finally:+ kw._inflight = 0+ kw._admitted_inference = 0++[email protected]("status, claimed", [(200, True), (400, False)])+def test_middleware_claims_slot_only_on_success(slot_state, status, claimed):+ _reset_keepwarm_counters()+ checkpoint = "/outputs/run/ckpt-a"+ inference._set_preview_resident(checkpoint)++ async def _app(scope, receive, send):+ await send({"type": "http.response.start", "status": status, "headers": []})+ await send({"type": "http.response.body", "body": b"{}", "more_body": False})++ _run_middleware(_app, "/v1/chat/completions")+ assert inference._is_preview_resident(checkpoint) is (not claimed)+ _reset_keepwarm_counters()+++def test_slot_claim_happens_before_admitted_decrement(slot_state, monkeypatch):+ _reset_keepwarm_counters()+ llama_keepwarm._admitted_inference = 0+ inference._set_preview_resident("/outputs/run/ckpt-a")+ observed = {}+ real_claim = llama_keepwarm._claim_non_preview_slot++ def _spy():+ observed["admitted_at_claim"] = llama_keepwarm._admitted_inference+ real_claim()++ monkeypatch.setattr(llama_keepwarm, "_claim_non_preview_slot", _spy)++ async def _app(scope, receive, send):+ llama_keepwarm.note_admitted_inference(scope) # passed auth, reached the inference hook+ await send({"type": "http.response.start", "status": 200, "headers": []})+ await send({"type": "http.response.body", "body": b"{}", "more_body": False})++ _run_middleware(_app, "/v1/chat/completions")+ assert observed["admitted_at_claim"] == 1+ assert llama_keepwarm._admitted_inference == 0 # decremented afterwards+ assert not inference._is_preview_resident("/outputs/run/ckpt-a") # claimed for Studio+ _reset_keepwarm_counters()+ llama_keepwarm._admitted_inference = 0+++def test_preview_rechecks_ownership_after_admitted_count(fake_slot, monkeypatch):+ fake_slot["ident"] = "/outputs/run/ckpt-a"+ inference._set_preview_resident("/outputs/run/ckpt-a")++ def _finish_studio_request() -> int:+ thread = threading.Thread(target = inference._set_preview_resident, args = (None,))+ thread.start()+ thread.join()+ return 0++ monkeypatch.setattr(llama_keepwarm, "other_admitted_inference_count", _finish_studio_request)++ async def _run():+ with pytest.raises(HTTPException) as excinfo:+ await inference.load_model_for_preview(+ LoadRequest(model_path = "/outputs/run/ckpt-b"),+ SimpleNamespace(scope = {"path": "/p/b/v1/chat/completions"}),+ "admin",+ )+ return excinfo.value++ exc = asyncio.run(_run())+ assert exc.status_code == 503+ assert fake_slot["loads"] == []+++def test_preview_swap_marker_skipped_for_same_target_borrow():+ import inspect++ src = inspect.getsource(inference.load_model_for_preview)+ guard = src.index("if not same_target:")+ begin = src.index("note_preview_swap_begin()", guard)+ check = src.index("other_admitted_inference_count()")+ assert guard < begin < check+ assert "note_preview_swap_begin()" in src[guard : guard + 200]diff --git a/studio/backend/tests/test_tunnel_safe_long_post.py b/studio/backend/tests/test_tunnel_safe_long_post.pyindex 72b59816eff..089034ca19e 100644--- a/studio/backend/tests/test_tunnel_safe_long_post.py+++ b/studio/backend/tests/test_tunnel_safe_long_post.py@@ -228,7 +228,8 @@ def test_only_the_route_pads(route):def test_preview_awaits_the_gated_load(route):"""preview.py is the one in-process caller; it must bypass the padding."""src = (_backend_root / "routes" / "preview.py").read_text(encoding = "utf-8")- assert "load_model_gated(" in src+ # Preview has its own gated coroutine (slot-ownership guards + the same lifecycle gate).+ assert "load_model_for_preview(" in srcassert re.search(r"\bawait load_model\(", src) is None, ("preview must not await the padded /load route: its StreamingResponse ""returns before the checkpoint is loaded"