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
Studio: per-request perf stats and slot usage in the API monitor (#8045)
Nilay90d7a3c73170
diff --git a/studio/backend/core/inference/api_monitor.py b/studio/backend/core/inference/api_monitor.pyindex 52665a699b9..cf08dfb9860 100644--- a/studio/backend/core/inference/api_monitor.py+++ b/studio/backend/core/inference/api_monitor.py@@ -5,12 +5,13 @@from __future__ import annotations+import mathimport osimport threadingimport timeimport uuidfrom collections import deque-from dataclasses import dataclass+from dataclasses import dataclass, fieldfrom typing import Any, Optional@@ -18,6 +19,8 @@ _MAX_ENTRIES = 50_MAX_PROMPT_CHARS = 12000_MAX_REPLY_CHARS = 12000_PREVIEW_CHARS = 360+# Far above any real context window; larger means a broken upstream payload.+_MAX_TOKEN_COUNT = 1 << 40# Opt-in startup kill switch for Studio's in-memory API monitor._DISABLE_ENV = "UNSLOTH_STUDIO_DISABLE_API_MONITOR"@@ -28,6 +31,26 @@ def _api_monitor_disabled() -> bool:return os.environ.get(_DISABLE_ENV, "").strip().lower() in _TRUE_VALUES+def _token_count_or_none(value: Any) -> Optional[int]:+ try:+ count = int(value)+ except (TypeError, ValueError, OverflowError):+ return None+ # snapshot() divides by these; an unbounded int makes that division raise too.+ if count < 0 or count > _MAX_TOKEN_COUNT:+ return None+ return count+++def _finite_float_or_none(value: Any) -> Optional[float]:+ # float() on a huge upstream int raises OverflowError, not ValueError/TypeError.+ try:+ number = float(value)+ except (TypeError, ValueError, OverflowError):+ return None+ return number if math.isfinite(number) else None++def _trim(text: Optional[str], limit: int) -> str:if not text:return ""@@ -71,6 +94,18 @@ class ApiMonitorEntry:shared: bool = False# 0-100 for a running download row; None when not applicable.progress: Optional[float] = None+ # Stamped on the first reply text; snapshot() prefers it over engine timings.+ first_token_monotonic: Optional[float] = None+ # The same instant, but only for output the model decoded. A tool card is client+ # output that TTFT should count and the token-rate clock must not: the tool run+ # between it and the first token is not decoding.+ first_decode_monotonic: Optional[float] = None+ prompt_ms: Optional[float] = None+ tok_per_sec: Optional[float] = None+ stop_reason: Optional[str] = None+ # Every finish reason seen so far. An n > 1 stream reports each choice in its own+ # chunk, so agreement can only be judged across the whole request. Not serialized.+ stop_reasons_seen: set[str] = field(default_factory = set)def snapshot(self,@@ -89,6 +124,26 @@ class ApiMonitorEntry:context_usage = Noneif self.total_tokens is not None and self.context_length:context_usage = min(1.0, max(0.0, self.total_tokens / self.context_length))+ ttft_ms = None+ if self.first_token_monotonic is not None:+ # Preferred over the prompt_ms fallback: that is prefill only, so it misses+ # the admission-queue wait before llama-server sees the request.+ ttft_ms = max(0, int((self.first_token_monotonic - self.started_monotonic) * 1000))+ elif self.prompt_ms is not None:+ ttft_ms = max(0, int(self.prompt_ms))+ tok_per_sec = self.tok_per_sec+ if (+ tok_per_sec is None+ and self.completion_tokens+ # The clock starts at the first token, so it spans only the gaps that+ # followed it: one token has no gap to measure, hence no rate at all.+ and self.completion_tokens > 1+ and self.finished_monotonic is not None+ and self.first_decode_monotonic is not None+ ):+ gen_s = self.finished_monotonic - self.first_decode_monotonic+ if gen_s > 0.05:+ tok_per_sec = (self.completion_tokens - 1) / gen_spayload = {"id": self.id,"endpoint": self.endpoint,@@ -116,6 +171,9 @@ class ApiMonitorEntry:"event": self.event,"reason": self.reason,"progress": self.progress,+ "ttft_ms": ttft_ms,+ "tok_per_sec": round(tok_per_sec, 2) if tok_per_sec is not None else None,+ "stop_reason": self.stop_reason,}if include_details:payload["prompt"] = self.prompt@@ -258,13 +316,26 @@ class ApiMonitor:if entry is not None:self._entries.remove(entry)- def append_reply(self, entry_id: Optional[str], text: str) -> None:+ def append_reply(+ self,+ entry_id: Optional[str],+ text: str,+ *,+ stamp_first_token: bool = True,+ ) -> None:if not entry_id or not text:returnwith self._lock:entry = self._find_locked(entry_id)if entry is None:return+ # Only a streaming delta stamps TTFT; a full-response append is end-to-end latency.+ if stamp_first_token:+ now = time.monotonic()+ if entry.first_token_monotonic is None:+ entry.first_token_monotonic = now+ if entry.first_decode_monotonic is None:+ entry.first_decode_monotonic = now# Preview is capped: once the "..." marker is present the head is# frozen, so skip the per-chunk re-concat (avoids O(n^2) on long# generations). A reply that landed exactly on the cap has no marker@@ -277,6 +348,29 @@ class ApiMonitor:entry.reply = _trim(entry.reply + text, _MAX_REPLY_CHARS)entry.updated_at = time.time()+ def mark_first_token(+ self,+ entry_id: Optional[str],+ *,+ decoded: bool = True,+ ) -> None:+ """Stamp TTFT for deltas with no reply text, e.g. reasoning tokens.++ ``decoded = False`` for output the model did not generate (a tool card), which+ starts the clock the user sees but must not start the token-rate clock.+ """+ if not entry_id:+ return+ now = time.monotonic()+ with self._lock:+ entry = self._find_locked(entry_id)+ if entry is None:+ return+ if entry.first_token_monotonic is None:+ entry.first_token_monotonic = now+ if decoded and entry.first_decode_monotonic is None:+ entry.first_decode_monotonic = now+def set_reply(self, entry_id: Optional[str], text: str) -> None:if not entry_id:return@@ -287,6 +381,65 @@ class ApiMonitor:entry.reply = _trim(text, _MAX_REPLY_CHARS)entry.updated_at = time.time()+ def set_perf(+ self,+ entry_id: Optional[str],+ *,+ tok_per_sec: Optional[float] = None,+ prompt_ms: Optional[float] = None,+ stop_reason: Optional[str] = None,+ ) -> None:+ if not entry_id:+ return+ # Coerce before locking: arbitrary payloads, and a raise here (this runs inside+ # streaming generators) would truncate the user's response.+ tok_per_sec = _finite_float_or_none(tok_per_sec)+ prompt_ms = _finite_float_or_none(prompt_ms)+ with self._lock:+ entry = self._find_locked(entry_id)+ if entry is None:+ return+ if tok_per_sec is not None:+ entry.tok_per_sec = tok_per_sec+ if prompt_ms is not None:+ entry.prompt_ms = prompt_ms+ if stop_reason is not None:+ entry.stop_reason = str(stop_reason)+ entry.updated_at = time.time()++ def note_stop_reason(self, entry_id: Optional[str], reason: Optional[str]) -> None:+ """Record one choice's finish reason, without publishing it yet.++ The row carries a single stop reason, so it only describes the request once every+ choice has reported one. An n > 1 stream finishes its choices in separate chunks,+ so publishing here would state a request-level verdict from the first one and+ retract it when a later choice disagrees. :meth:`finish` resolves it instead.+ """+ if not entry_id or not reason:+ return+ with self._lock:+ entry = self._find_locked(entry_id)+ if entry is None:+ return+ entry.stop_reasons_seen.add(str(reason))+ entry.updated_at = time.time()++ @staticmethod+ def _settle_stop_reason_locked(entry: ApiMonitorEntry, completed: bool) -> None:+ """Fix the row's stop reason as it becomes terminal.++ Only a completed request has one: a cancelled or failed stream stopped for that+ reason, so any natural reason recorded on the way describes what it was doing+ rather than how it ended. Clearing here catches the direct ``set_perf`` writers+ too, which several streams reach before the cancellation is stamped.+ """+ if not completed:+ entry.stop_reason = None+ return+ seen = entry.stop_reasons_seen+ if seen:+ entry.stop_reason = next(iter(seen)) if len(seen) == 1 else None+def set_usage(self,entry_id: Optional[str],@@ -298,6 +451,11 @@ class ApiMonitor:) -> None:if not entry_id:return+ # Coerce first: snapshot() does math on these arbitrary payload values.+ prompt_tokens = _token_count_or_none(prompt_tokens)+ completion_tokens = _token_count_or_none(completion_tokens)+ total_tokens = _token_count_or_none(total_tokens)+ context_length = _token_count_or_none(context_length)with self._lock:entry = self._find_locked(entry_id)if entry is None:@@ -334,6 +492,7 @@ class ApiMonitor:# already ran) must not move finished_*.if entry.finished_at is not None:return+ self._settle_stop_reason_locked(entry, status == "completed")now = time.time()entry.status = statusentry.updated_at = now@@ -370,6 +529,7 @@ class ApiMonitor:self._fail_locked(entry, error)def _fail_locked(self, entry: ApiMonitorEntry, error: str) -> None:+ self._settle_stop_reason_locked(entry, False)now = time.time()entry.status = "error"entry.error = _trim(error, 1000)diff --git a/studio/backend/core/inference/external_provider.py b/studio/backend/core/inference/external_provider.pyindex 282bf6bbb64..6ce3dce5f31 100644--- a/studio/backend/core/inference/external_provider.py+++ b/studio/backend/core/inference/external_provider.py@@ -31,6 +31,14 @@ _TEMPLATE_APPLYING_PROVIDERS = frozenset({"vllm", "llama_cpp", "ollama", "custom# /v1/chat/completions._CONTINUATION_FLAG_PROVIDERS = frozenset({"vllm", "llama_cpp"})+# The subset documenting stream_options.include_usage. An OAI-compatible stream omits+# usage without it, and these providers report no llama.cpp timings either, so the+# monitor has no token count to derive a speed from. Same caution as the flag above:+# "custom" is any user-supplied base_url and a strict endpoint 400s on an unknown field.+# "openai" is absent because it never reaches this body: it routes to /v1/responses,+# which reports usage on its own.+_USAGE_STREAM_OPTION_PROVIDERS = frozenset({"vllm", "openrouter", "kimi"})+# structlog so INFO diagnostics reach the backend's JSON log stream (the# stdlib root logger defaults to WARNING with no handlers). It accepts the# existing printf-style positional args.@@ -998,6 +1006,9 @@ class ExternalProviderClient:"presence_penalty": presence_penalty,**_continue_body,}+ # Only alongside stream=True: the field is rejected on a non-streaming request.+ if stream and self.provider_type in _USAGE_STREAM_OPTION_PROVIDERS:+ body["stream_options"] = {"include_usage": True}if max_tokens is not None:# Newer OpenAI models (gpt-4o, gpt-5.x) reject max_tokensif self.provider_type == "openai":@@ -1479,6 +1490,9 @@ class ExternalProviderClient:)fallback_body = dict(body)fallback_body.pop("tools", None)+ # This path returns before the common body injection, and Kimi reports no+ # engine timings, so without this the row has neither tokens nor a speed.+ fallback_body["stream_options"] = {"include_usage": True}try:async with _http_client.stream("POST",diff --git a/studio/backend/core/inference/llama_admission.py b/studio/backend/core/inference/llama_admission.pyindex 7bf0dd74293..b893cfd4cde 100644--- a/studio/backend/core/inference/llama_admission.py+++ b/studio/backend/core/inference/llama_admission.py@@ -768,11 +768,16 @@ class LlamaAdmissionQueue:key = self.key,capacity = self._capacity,active = self._held,- queued = len(self._waiters),- # What another caller could actually take, so the admission log never- # shows free slots next to queued requests: after a shrink, ids below- # the new capacity can be free while holdovers still fill the ceiling.- free = min(len(self._free), max(0, self._capacity - self._held)),+ # Resume tickets are approved continuations holding no slot yet; omitting+ # them would show a full, idle-looking queue while one still waits.+ queued = len(self._waiters) + len(self._unpark_tickets),+ # What another caller could actually take, so free never shows next to queued:+ # after a shrink, ids below the new capacity can be free while holdovers fill+ # the ceiling, and tickets hold slots back exactly as _can_admit_locked does.+ free = min(+ len(self._free),+ max(0, self._capacity - self._held - len(self._unpark_tickets)),+ ),)@@ -795,6 +800,13 @@ def get_llama_admission_queue(key: str) -> LlamaAdmissionQueue:return queue+def peek_llama_admission_snapshot(key: str) -> Optional[LlamaAdmissionSnapshot]:+ """Read-only view of one queue's state; never creates a queue."""+ with _QUEUES_LOCK:+ queue = _QUEUES.get(key)+ return queue.snapshot() if queue is not None else None++def reset_llama_admission_queues() -> None:global _parked_totalwith _QUEUES_LOCK:diff --git a/studio/backend/core/rag/captioner.py b/studio/backend/core/rag/captioner.pyindex 8398506f212..ccc150c3c76 100644--- a/studio/backend/core/rag/captioner.py+++ b/studio/backend/core/rag/captioner.py@@ -11,6 +11,7 @@ non-causally and abort otherwise); Unsloth's vision chat already requires this."from __future__ import annotationsimport base64+import contextlibimport loggingfrom . import config@@ -89,6 +90,16 @@ def _vision_auth_headers() -> dict | None:return None+def _direct_llama_slot():+ """Count this call against the chat backend's slots for its duration: it reaches+ llama-server directly, so nothing else makes the slot readout show it as busy."""+ try:+ from routes.inference import _direct_llama_request+ return _direct_llama_request()+ except Exception: # noqa: BLE001 - accounting must never break ingestion+ return contextlib.nullcontext()++def _vision_complete(base_url: str,model: str,@@ -123,16 +134,17 @@ def _vision_complete("chat_template_kwargs": {"enable_thinking": False},}try:- r = httpx.post(- f"{base_url}/v1/chat/completions",- json = payload,- timeout = timeout,- headers = _vision_auth_headers(),- # trust_env=False: base_url is the loopback backend; skip any HTTP(S)_PROXY.- trust_env = False,- )- r.raise_for_status()- text = r.json()["choices"][0]["message"]["content"]+ with _direct_llama_slot():+ r = httpx.post(+ f"{base_url}/v1/chat/completions",+ json = payload,+ timeout = timeout,+ headers = _vision_auth_headers(),+ # trust_env=False: base_url is the loopback backend; skip any HTTP(S)_PROXY.+ trust_env = False,+ )+ r.raise_for_status()+ text = r.json()["choices"][0]["message"]["content"]return text.strip() or Noneexcept Exception: # noqa: BLE001 - a failed vision call is non-fatallogger.debug("vision request failed", exc_info = True)diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 2db64106083..5c22e362ac9 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -47,6 +47,7 @@ from core.inference.llama_admission import (LlamaAdmissionTimeout,get_llama_admission_queue,llama_admission_config_from_env,+ peek_llama_admission_snapshot,)@@ -783,6 +784,32 @@ def _wants_stream_usage(payload) -> bool:return bool((payload.stream_options or {}).get("include_usage"))+def _is_openai_usage_only_sse(line: str) -> bool:+ """Whether *line* is a standalone ``choices: []`` usage chunk.++ Only that shape: a content chunk carrying inline usage still has to reach the client.+ """+ if not isinstance(line, str) or not line.startswith("data:"):+ return False+ # This runs on every relayed line, so keep the parse off the common path: a usage+ # chunk always spells the key literally, and content deltas carry no usage at all.+ if '"usage"' not in line:+ return False+ body = line[len("data:") :].strip()+ if not body or body == "[DONE]":+ return False+ try:+ obj = json.loads(body)+ except Exception:+ return False+ return (+ isinstance(obj, dict)+ and obj.get("usage") is not None+ and isinstance(obj.get("choices"), list)+ and not obj["choices"]+ )++_OPENAI_PASSTHROUGH_TERMINAL_GRACE_S = 2.0_SSE_DONE_LINE = "data: [DONE]"_SSE_DONE_CHUNK = "data: [DONE]\n\n"@@ -3117,16 +3144,31 @@ def _monitor_usage(monitor_id: Optional[str],usage: Optional[dict],context_length = None,+ *,+ timings: Optional[dict] = None,+ stop_reason: Optional[str] = None,):- if not usage:- return- api_monitor.set_usage(- monitor_id,- prompt_tokens = usage.get("prompt_tokens") or usage.get("input_tokens"),- completion_tokens = usage.get("completion_tokens") or usage.get("output_tokens"),- total_tokens = usage.get("total_tokens"),- context_length = context_length,- )+ # isinstance, not truthiness: a non-dict usage would raise on .get() into the+ # streaming generator and abort the user's response.+ if isinstance(usage, dict) and usage:+ api_monitor.set_usage(+ monitor_id,+ prompt_tokens = usage.get("prompt_tokens") or usage.get("input_tokens"),+ completion_tokens = usage.get("completion_tokens") or usage.get("output_tokens"),+ total_tokens = usage.get("total_tokens"),+ context_length = context_length,+ )+ tok_per_sec = prompt_ms = None+ if isinstance(timings, dict):+ tok_per_sec = timings.get("predicted_per_second")+ prompt_ms = timings.get("prompt_ms")+ if tok_per_sec is not None or prompt_ms is not None or stop_reason is not None:+ api_monitor.set_perf(+ monitor_id,+ tok_per_sec = tok_per_sec,+ prompt_ms = prompt_ms,+ stop_reason = stop_reason,+ )def _monitor_call_text(name: Any, arguments: Any = None) -> str:@@ -3164,21 +3206,43 @@ def _monitor_openai_chunk(monitor_id: Optional[str],data: dict,context_length = None,+ streaming: bool = False,):if not monitor_id:return- _monitor_usage(monitor_id, data.get("usage"), context_length)# Defensive: ignore malformed shapes so the helper never raises into the# streaming generator and aborts the user's response.choices = data.get("choices")+ if isinstance(choices, list):+ # The row covers every choice, so one reason only describes the request when they+ # all agree. An n > 1 stream reports each choice in its own chunk, so the monitor+ # accumulates them across the request rather than judging a chunk in isolation.+ for choice in choices:+ if isinstance(choice, dict) and choice.get("finish_reason"):+ api_monitor.note_stop_reason(monitor_id, str(choice["finish_reason"]))+ timings = data.get("timings")+ _monitor_usage(+ monitor_id,+ data.get("usage"),+ context_length,+ timings = timings if isinstance(timings, dict) else None,+ )if not isinstance(choices, list) or not choices:return+ if isinstance(data, dict) and data.get("_toolEvent"):+ # Tool cards ride the chunk beside choices with an empty delta; already seen.+ # Not decoded output though: a tool run (or a human confirming one) between the+ # card and the first token would otherwise be counted as decoding time.+ api_monitor.mark_first_token(monitor_id, decoded = False)reply_parts: list[tuple[int, str]] = []for idx, choice in enumerate(choices):if not isinstance(choice, dict):continuedelta = choice.get("delta") or {}message = choice.get("message") or {}+ if isinstance(delta, dict) and delta.get("reasoning_content"):+ api_monitor.mark_first_token(monitor_id)+content = delta.get("content") if isinstance(delta, dict) else Noneif content:api_monitor.append_reply(monitor_id, content)@@ -3201,11 +3265,12 @@ def _monitor_openai_chunk(if not reply_parts:returnif len(choices) == 1:- api_monitor.append_reply(monitor_id, reply_parts[0][1])+ api_monitor.append_reply(monitor_id, reply_parts[0][1], stamp_first_token = streaming)returnapi_monitor.append_reply(monitor_id,"\n\n".join(f"Choice {idx + 1}:\n{text}" for idx, text in reply_parts),+ stamp_first_token = streaming,)@@ -3255,7 +3320,7 @@ def _monitor_openai_sse_line(if error_message:api_monitor.fail(monitor_id, error_message)return "error"- _monitor_openai_chunk(monitor_id, data, context_length)+ _monitor_openai_chunk(monitor_id, data, context_length, streaming = True)return None@@ -3319,6 +3384,8 @@ def _monitor_anthropic_payload(if event_type == "content_block_delta":delta = data.get("delta") or {}text = delta.get("text") if isinstance(delta, dict) else None+ if isinstance(delta, dict) and delta.get("type") == "thinking_delta":+ api_monitor.mark_first_token(monitor_id)if isinstance(text, str) and text:api_monitor.append_reply(monitor_id, text)elif isinstance(delta, dict) and delta.get("type") == "input_json_delta":@@ -3341,6 +3408,9 @@ def _monitor_anthropic_payload(_ANTHROPIC_MONITOR_TOOL_BLOCKS.pop(monitor_id, None)return Noneif event_type == "message_delta":+ delta = data.get("delta")+ if isinstance(delta, dict) and delta.get("stop_reason"):+ api_monitor.set_perf(monitor_id, stop_reason = str(delta["stop_reason"]))_monitor_anthropic_usage(monitor_id, data.get("usage"), context_length)return Noneif event_type == "error":@@ -3402,6 +3472,8 @@ def _monitor_anthropic_json_response(text = _monitor_anthropic_content_blocks(data.get("content"))if text:api_monitor.set_reply(monitor_id, text)+ if data.get("stop_reason"):+ api_monitor.set_perf(monitor_id, stop_reason = str(data["stop_reason"]))_monitor_anthropic_usage(monitor_id, data.get("usage"), context_length)api_monitor.finish(monitor_id)@@ -3516,6 +3588,90 @@ def _close_load_event(api_monitor.finish(entry_id)+# Direct calls skip admission but still occupy a slot: /completions, /embeddings,+# GGUF TTS and RAG vision (captioning/OCR) all reach llama-server without a lease.+_direct_llama_inflight = 0+_direct_llama_inflight_lock = threading.Lock()+++def _direct_llama_request_started() -> None:+ global _direct_llama_inflight+ with _direct_llama_inflight_lock:+ _direct_llama_inflight += 1+++def _direct_llama_request_finished() -> None:+ global _direct_llama_inflight+ with _direct_llama_inflight_lock:+ _direct_llama_inflight = max(0, _direct_llama_inflight - 1)+++@contextmanager+def _direct_llama_request(counted: bool = True):+ """Hold the direct-call count for the duration of the block.++ The increment is the last statement before the try that decrements it, so no+ caller can leak a permanent +1 by placing the pair itself. ``counted`` False is+ a no-op, for callers that pick their backend at runtime.+ """+ if not counted:+ yield+ return+ _direct_llama_request_started()+ try:+ yield+ finally:+ _direct_llama_request_finished()+++def _direct_llama_is_busy() -> bool:+ """Whether a direct llama call (RAG caption/OCR) holds the server right now.++ Tracked separately from the admission snapshot, so it still answers when admission+ control is off and :func:`_monitor_queue_state` reports nothing at all.+ """+ with _direct_llama_inflight_lock:+ return _direct_llama_inflight > 0+++def _monitor_queue_state() -> Optional[dict]:+ """Live slot/queue occupancy of the loaded llama-server, for the API monitor."""+ # Disabled admission takes no leases and stays at capacity 1, so a multi-slot+ # server would be misreported.+ if not llama_admission_config_from_env().enabled:+ return None+ llama_backend = get_llama_cpp_backend()+ if not getattr(llama_backend, "is_loaded", False) or getattr(+ llama_backend, "is_diffusion", False+ ):+ return None+ direct = _direct_llama_inflight+ snapshot = peek_llama_admission_snapshot(+ str(getattr(llama_backend, "base_url", "llama-server"))+ )+ if snapshot is not None:+ busy = snapshot.active + direct+ active = min(snapshot.capacity, busy)+ return {+ "capacity": snapshot.capacity,+ "active": active,+ # Direct calls hold no lease, so overflow is waiting inside llama-server:+ # queued, not clamped away into a readout that looks idle.+ "queued": snapshot.queued + max(0, busy - snapshot.capacity),+ # From the snapshot, not capacity - active: it already holds slots back for+ # approved resumes, so recomputing would show free next to queued.+ "free": max(0, snapshot.free - direct),+ }+ capacity = _positive_int_or_none(getattr(llama_backend, "effective_parallel_slots", None)) or 1+ active = min(capacity, direct)+ return {+ "capacity": capacity,+ "active": active,+ "queued": max(0, direct - capacity),+ "free": capacity - active,+ }++def _monitor_active_model() -> Optional[str]:"""The loaded model as a client-facing id, quant included when known.@@ -8158,11 +8314,22 @@ async def get_api_monitor(current_subject: str = Depends(get_current_subject)):"""Return recent OpenAI-compatible API activity for Unsloth."""# Off-loop: both helpers reach get_inference_backend(), whose first call waits on# hardware detection, and this is polled from first paint.- active_model, context_length = await asyncio.to_thread(- lambda: (_monitor_active_model(), _monitor_context_length())+ active_model, context_length, queue, direct_busy = await asyncio.to_thread(+ lambda: (+ _monitor_active_model(),+ _monitor_context_length(),+ _monitor_queue_state(),+ _direct_llama_is_busy(),+ ))active_requests = api_monitor.active_count(subject = current_subject)- if active_requests:+ # Slots the rows cannot see: direct llama calls (RAG caption/OCR) open no row, logging+ # may be off, and another subject's work is not counted here. The queue readout beside+ # this is already server-wide, so deriving from rows alone reports Ready next to busy.+ queue_busy = bool(queue) and bool(queue.get("active") or queue.get("queued"))+ # direct_busy stands alone: with admission control off the queue readout is None, and+ # deriving only from it would report Ready while a caption/OCR call holds the server.+ if active_requests or queue_busy or direct_busy:operating_status = "generating"elif active_model:operating_status = "ready"@@ -8179,6 +8346,7 @@ async def get_api_monitor(current_subject: str = Depends(get_current_subject)):"active_model": active_model,"context_length": context_length,"active_requests": active_requests,+ "queue": queue,"logging_enabled": api_monitor.enabled,"entries": api_monitor.snapshot(include_details = False, subject = current_subject),}@@ -8606,7 +8774,10 @@ async def generate_audio(# Pick backend — both return (wav_bytes, sample_rate)llama_backend = get_llama_cpp_backend()- if llama_backend.is_loaded and getattr(llama_backend, "_is_audio", False):+ # GGUF TTS goes straight to llama-server /completion, holding a slot with no+ # admission lease, so only the direct counter can show it in the slot readout.+ _direct_llama_tts = bool(llama_backend.is_loaded and getattr(llama_backend, "_is_audio", False))+ if _direct_llama_tts:# Advertised repo id after an auto-switch load, else a clean public id,# never the absolute .gguf path.model_name = _llama_public_model_id(llama_backend)@@ -8665,7 +8836,8 @@ async def generate_audio(# of the request timeout after the chat had already reported it stopped._audio_watcher = asyncio.create_task(_await_disconnect_then_cancel(request, _audio_cancel))try:- wav_bytes, sample_rate = await asyncio.to_thread(gen)+ with _direct_llama_request(_direct_llama_tts):+ wav_bytes, sample_rate = await asyncio.to_thread(gen)except Exception as e:if _audio_cancel.is_set():raise HTTPException(status_code = 499, detail = "Audio generation cancelled")@@ -9813,11 +9985,21 @@ async def _proxy_to_external_provider(monitor_event = _monitor_openai_sse_line(monitor_id, line)if monitor_event is None:try:- _monitor_openai_chunk(monitor_id, json.loads(line))+ # Only stamp a real delta stream: a stream:false response is one+ # full line, so end-to-end latency, not TTFT.+ _monitor_openai_chunk(+ monitor_id, json.loads(line), streaming = bool(payload.stream)+ )except Exception:passif monitor_event == "error":stream_failed = True+ # The monitor has read it by now. Providers are asked for usage on the+ # stream regardless of what the caller wanted, so honour OpenAI's contract+ # on the way out: a client that did not opt in never sees the standalone+ # choices: [] chunk. Same rule _cmpl_stream_event_out applies locally.+ if not _wants_stream_usage(payload) and _is_openai_usage_only_sse(line):+ continueyield f"{line}\n\n"# Parsed from the line itself, not from monitor_event: with the# monitor disabled the helper returns None for every line, and@@ -10496,15 +10678,22 @@ async def openai_chat_completions(completion_id, created, model_name, chunk_text)+ _audio_stats = _audio_stats_holder.get("stats")+ _audio_finish = "stop" if cancelled else _stats_finish_reason(_audio_stats)+ # The worker fills this in for both backends (MLX adds timings),+ # so the row has counts and a speed like every other request.+ if isinstance(_audio_stats, dict):+ _monitor_usage(+ monitor_id,+ _audio_stats.get("usage"),+ _monitor_context_length(),+ timings = _audio_stats.get("timings"),+ )+ # Before finish(): that is where the reason is settled, and a+ # later write would escape the clearing a cancelled row gets.+ api_monitor.set_perf(monitor_id, stop_reason = _audio_finish)api_monitor.finish(monitor_id, "cancelled" if cancelled else "completed")- yield _chat_final_chunk(- completion_id,- created,- model_name,- "stop"- if cancelled- else _stats_finish_reason(_audio_stats_holder.get("stats")),- )+ yield _chat_final_chunk(completion_id, created, model_name, _audio_finish)yield "data: [DONE]\n\n"except asyncio.CancelledError:cancel_event.set()@@ -10555,6 +10744,18 @@ async def openai_chat_completions(# Nested under the except arms too: api_monitor.fail() can throw, and a leaked entry 409s swaps._tracker.__exit__(None, None, None)api_monitor.set_reply(monitor_id, full_text)+ _audio_json_stats = _audio_stats_holder.get("stats")+ _audio_json_finish = (+ "stop" if cancel_event.is_set() else _stats_finish_reason(_audio_json_stats)+ )+ if isinstance(_audio_json_stats, dict):+ _monitor_usage(+ monitor_id,+ _audio_json_stats.get("usage"),+ _monitor_context_length(),+ timings = _audio_json_stats.get("timings"),+ )+ api_monitor.set_perf(monitor_id, stop_reason = _audio_json_finish)api_monitor.finish(monitor_id)response = ChatCompletion(id = completion_id,@@ -10563,11 +10764,7 @@ async def openai_chat_completions(choices = [CompletionChoice(message = CompletionMessage(content = full_text),- finish_reason = (- "stop"- if cancel_event.is_set()- else _stats_finish_reason(_audio_stats_holder.get("stats"))- ),+ finish_reason = _audio_json_finish,)],)@@ -11011,6 +11208,8 @@ async def openai_chat_completions(final_reasoning, final_visible = reasoning_extractor.finish()chunks = []if final_reasoning:+ # Held-back markers can make this the FIRST output of all.+ api_monitor.mark_first_token(monitor_id)chunks.append(_gguf_chat_delta_line(ChoiceDelta(reasoning_content = final_reasoning)@@ -11092,6 +11291,10 @@ async def openai_chat_completions(if event["type"] in ("tool_start", "tool_end"):if event["type"] == "tool_start":+ # Tool card is client-visible output; stamp the turn here.+ # Not decoded output: the tool run (or a human confirming+ # it) before the next turn is not decoding time.+ api_monitor.mark_first_token(monitor_id, decoded = False)for chunk in _flush_reasoning_extractor():yield chunkprev_text = ""@@ -11127,6 +11330,7 @@ async def openai_chat_completions(continuereasoning_delta, visible_delta = reasoning_extractor.feed(new_text)if reasoning_delta:+ api_monitor.mark_first_token(monitor_id)yield _gguf_chat_delta_line(ChoiceDelta(reasoning_content = reasoning_delta))@@ -11162,7 +11366,13 @@ async def openai_chat_completions()if usage_line is not None:yield usage_line- _monitor_usage(monitor_id, _stream_usage, _monitor_context_length())+ _monitor_usage(+ monitor_id,+ _stream_usage,+ _monitor_context_length(),+ timings = _stream_timings,+ stop_reason = _clamp_finish_reason(_stream_finish),+ )api_monitor.finish(monitor_id, "cancelled" if cancel_event.is_set() else "completed")@@ -11356,6 +11566,7 @@ async def openai_chat_completions(full_text = ""usage = Nonefinish = None+ timings = Nonegen = gguf_generate_with_tools()try:for event in gen:@@ -11364,6 +11575,7 @@ async def openai_chat_completions(if event.get("type") == "metadata":usage = event.get("usage")finish = event.get("finish_reason")+ timings = event.get("timings")elif event.get("type") == "content":# Content is cumulative within a turn and resets# between turns, so the last event holds the final@@ -11375,7 +11587,7 @@ async def openai_chat_completions(auto_heal_tool_calls = _gguf_auto_heal_tool_calls,enabled_tool_names = _gguf_display_tool_names,)- return full_text, usage, finish+ return full_text, usage, finish, timingsfinally:# Close the generator on early break/cancel so the underlying# llama-server stream socket is released, like the SSE path.@@ -11438,7 +11650,12 @@ async def openai_chat_completions(cancel_event = cancel_event,)drain_task = asyncio.create_task(asyncio.to_thread(_drain_gguf_tool_loop))- full_text, completion_usage, completion_finish = await asyncio.shield(drain_task)+ (+ full_text,+ completion_usage,+ completion_finish,+ completion_timings,+ ) = await asyncio.shield(drain_task)reasoning_text, visible_text = _extract_responses_reasoning(full_text,parse_think_markers = _responses_should_parse_think_markers(@@ -11479,6 +11696,8 @@ async def openai_chat_completions("total_tokens": _prompt_tokens + _completion_tokens,},_monitor_context_length(),+ timings = completion_timings,+ stop_reason = _clamp_finish_reason(completion_finish),)api_monitor.finish(monitor_id, "cancelled" if cancel_event.is_set() else "completed"@@ -11674,6 +11893,7 @@ async def openai_chat_completions(continuereasoning_delta, visible_delta = reasoning_extractor.feed(new_text)if reasoning_delta:+ api_monitor.mark_first_token(monitor_id)yield _gguf_chat_delta_line(ChoiceDelta(reasoning_content = reasoning_delta))@@ -11683,6 +11903,8 @@ async def openai_chat_completions(final_reasoning, final_visible = reasoning_extractor.finish()if final_reasoning:+ # Held-back markers can make this the FIRST output of all.+ api_monitor.mark_first_token(monitor_id)yield _gguf_chat_delta_line(ChoiceDelta(reasoning_content = final_reasoning))if final_visible:api_monitor.append_reply(monitor_id, final_visible)@@ -11714,7 +11936,13 @@ async def openai_chat_completions()if usage_line is not None:yield usage_line- _monitor_usage(monitor_id, _stream_usage, _monitor_context_length())+ _monitor_usage(+ monitor_id,+ _stream_usage,+ _monitor_context_length(),+ timings = _stream_timings,+ stop_reason = _clamp_finish_reason(_stream_finish),+ )api_monitor.finish(monitor_id, "cancelled" if cancel_event.is_set() else "completed")@@ -12025,6 +12253,8 @@ async def openai_chat_completions(_prompt_tokens = 0_sum_completion = 0_prompt_details = None+ _last_timings = None+ _last_finish = Nonefor _idx in range(_n):# Stop spawning the remaining choices once cancelled.if cancel_event.is_set():@@ -12037,6 +12267,8 @@ async def openai_chat_completions(if token.get("type") == "metadata":completion_usage = token.get("usage")completion_finish = token.get("finish_reason")+ _last_timings = token.get("timings")+ _last_finish = completion_finishcontinuefull_text = token@@ -12073,6 +12305,8 @@ async def openai_chat_completions(_prompt_tokens,_sum_completion,_prompt_details,+ _last_timings,+ _last_finish,)drain_task = asyncio.create_task(asyncio.to_thread(_drain_gguf_choices))@@ -12083,6 +12317,8 @@ async def openai_chat_completions(_prompt_tokens,_sum_completion,_prompt_details,+ _last_timings,+ _last_finish,) = await asyncio.shield(drain_task)response = ChatCompletion(@@ -12111,6 +12347,14 @@ async def openai_chat_completions("total_tokens": _prompt_tokens + _sum_completion,},_monitor_context_length(),+ # Omit both for n > 1: totals sum all choices while _last_timings and+ # _last_finish are only the final one's, so they describe neither.+ timings = _last_timings if len(_monitor_replies) <= 1 else None,+ stop_reason = (+ _clamp_finish_reason(_last_finish)+ if _last_finish and len(_monitor_replies) <= 1+ else None+ ),)api_monitor.finish(monitor_id)return _model_json_response(response)@@ -12400,6 +12644,8 @@ async def openai_chat_completions(fr, fv = reasoning_extractor.finish()out = []if fr:+ # Held-back markers can make this the FIRST output of all.+ api_monitor.mark_first_token(monitor_id)out.append(_chat_reasoning_chunk(completion_id, created, model_name, fr))if fv:api_monitor.append_reply(monitor_id, fv)@@ -12475,6 +12721,8 @@ async def openai_chat_completions(if event["type"] in ("tool_start", "tool_end"):if event["type"] == "tool_start":+ # Same as the GGUF loop: visible output, but not decoded.+ api_monitor.mark_first_token(monitor_id, decoded = False)# Flush reasoning before tool_start so the thinking block closes ahead of the card.for _c in _sf_flush_reasoning():yield _c@@ -12497,6 +12745,7 @@ async def openai_chat_completions(# Split reasoning vs visible; only visible reaches the monitor.reasoning_delta, visible_delta = reasoning_extractor.feed(new_text)if reasoning_delta:+ api_monitor.mark_first_token(monitor_id)yield _chat_reasoning_chunk(completion_id, created, model_name, reasoning_delta)@@ -12512,12 +12761,11 @@ async def openai_chat_completions(_stats = _sf_stats_holder.get("stats")# The last turn's own budget decides: an earlier turn stopping at the# cap does not truncate the answer this one went on to write.- yield _chat_final_chunk(- completion_id,- created,- model_name,- "stop" if cancel_event.is_set() else _stats_finish_reason(_stats),- )+ _sf_finish = "stop" if cancel_event.is_set() else _stats_finish_reason(_stats)+ yield _chat_final_chunk(completion_id, created, model_name, _sf_finish)+ # Reuse the reason already sent to the client. Outside the stats block+ # below: only MLX reports stats.+ api_monitor.set_perf(monitor_id, stop_reason = _sf_finish)if _stats:usage_line = _openai_stream_usage_chunk(payload,@@ -12529,7 +12777,11 @@ async def openai_chat_completions()if usage_line is not None:yield usage_line- _monitor_usage(monitor_id, _stats.get("usage"))+ _monitor_usage(+ monitor_id,+ _stats.get("usage"),+ timings = _stats.get("timings"),+ )api_monitor.finish(monitor_id, "cancelled" if cancel_event.is_set() else "completed")@@ -12632,8 +12884,16 @@ async def openai_chat_completions()api_monitor.set_reply(monitor_id, _visible_text)_stats = _sf_stats_holder.get("stats")+ # Reuse the reason this response carries. Outside the stats block below:+ # only MLX reports stats.+ _sf_json_finish = "stop" if cancel_event.is_set() else _stats_finish_reason(_stats)+ api_monitor.set_perf(monitor_id, stop_reason = _sf_json_finish)if _stats:- _monitor_usage(monitor_id, _stats.get("usage"))+ _monitor_usage(+ monitor_id,+ _stats.get("usage"),+ timings = _stats.get("timings"),+ )api_monitor.finish(monitor_id, "cancelled" if cancel_event.is_set() else "completed")_sf_msg_kwargs = {"content": _visible_text}if _reasoning_text:@@ -12645,9 +12905,7 @@ async def openai_chat_completions(choices = [CompletionChoice(message = CompletionMessage(**_sf_msg_kwargs),- finish_reason = (- "stop" if cancel_event.is_set() else _stats_finish_reason(_stats)- ),+ finish_reason = _sf_json_finish,)],)@@ -12904,6 +13162,7 @@ async def openai_chat_completions(# healer so tool markup inside a reasoning block is not promoted.reasoning_delta, visible_delta = reasoning_extractor.feed(new_text)if reasoning_delta:+ api_monitor.mark_first_token(monitor_id)yield _chat_reasoning_chunk(completion_id, created, model_name, reasoning_delta)@@ -12929,6 +13188,8 @@ async def openai_chat_completions(final_reasoning, final_visible = reasoning_extractor.finish()if final_reasoning:+ # Held-back markers can make this the FIRST output of all.+ api_monitor.mark_first_token(monitor_id)yield _chat_reasoning_chunk(completion_id, created, model_name, final_reasoning)if final_visible:if healer is None:@@ -12976,6 +13237,9 @@ async def openai_chat_completions(else ("stop" if _cancelled else _stats_finish_reason(_stats)))yield _chat_final_chunk(completion_id, created, model_name, _finish)+ # Reuse the reason already sent to the client. Outside the stats block+ # below: only MLX reports stats.+ api_monitor.set_perf(monitor_id, stop_reason = _finish)if _stats:usage_line = _openai_stream_usage_chunk(payload,@@ -12987,7 +13251,11 @@ async def openai_chat_completions()if usage_line is not None:yield usage_line- _monitor_usage(monitor_id, _stats.get("usage"))+ _monitor_usage(+ monitor_id,+ _stats.get("usage"),+ timings = _stats.get("timings"),+ )api_monitor.finish(monitor_id, "cancelled" if cancel_event.is_set() else "completed")@@ -13157,9 +13425,16 @@ async def openai_chat_completions(f"[tool_calls] {_calls_text}" if _calls_text else "")api_monitor.set_reply(monitor_id, _monitor_reply)+ # Reuse the response's finish_reason. Outside the stats block: only+ # MLX reports stats.+ api_monitor.set_perf(monitor_id, stop_reason = _finish)_stats = stats_holder.get("stats")if _stats:- _monitor_usage(monitor_id, _stats.get("usage"))+ _monitor_usage(+ monitor_id,+ _stats.get("usage"),+ timings = _stats.get("timings"),+ )api_monitor.finish(monitor_id)return _model_json_response(response)@@ -13676,6 +13951,9 @@ async def openai_completions(request: Request, current_subject: str = Depends(ge# nothing behind (see _responses_stream). No thread_id: public API surface, not a chat._tracker = _TrackedCancel(disconnect_event, model = monitor_model, kind = "completions")_tracker.__enter__()+ # Must stay the last statement before the try that decrements it: a raise in+ # between leaks a permanent +1, and there is no reset hook.+ _direct_llama_request_started()try:req = client.build_request("POST", target_url, json = body, headers = {"Connection": "close"}@@ -13765,6 +14043,7 @@ async def openai_completions(request: Request, current_subject: str = Depends(geclient = client,)finally:+ _direct_llama_request_finished()_tracker.__exit__(None, None, None)return _sse_streaming_response(_stream())@@ -13784,6 +14063,7 @@ async def openai_completions(request: Request, current_subject: str = Depends(geclient = _client,))+ _direct_llama_request_started()try:try:resp = await _client.post(@@ -13813,6 +14093,7 @@ async def openai_completions(request: Request, current_subject: str = Depends(geexcept Exception:passfinally:+ _direct_llama_request_finished()_tracker.__exit__(None, None, None)if resp.status_code != 200:@@ -13928,6 +14209,7 @@ async def openai_embeddings(request: Request, current_subject: str = Depends(getclient = _client,))+ _direct_llama_request_started()try:try:resp = await _client.post(@@ -13957,12 +14239,13 @@ async def openai_embeddings(request: Request, current_subject: str = Depends(getexcept Exception:passfinally:+ _direct_llama_request_finished()_tracker.__exit__(None, None, None)if resp.status_code != 200:api_monitor.fail(monitor_id, resp.text[:500])else:try:- _monitor_usage(monitor_id, resp.json().get("usage"), _monitor_context_length())+ _monitor_openai_chunk(monitor_id, resp.json(), _monitor_context_length())except Exception:passapi_monitor.finish(monitor_id)@@ -14613,7 +14896,14 @@ async def _responses_non_streaming(instructions = payload.instructions,)api_monitor.set_reply(monitor_id, text or _monitor_tool_calls_text(tool_calls))- _monitor_usage(monitor_id, usage_data, _monitor_context_length())+ _monitor_usage(+ monitor_id,+ usage_data,+ _monitor_context_length(),+ # Inner chat monitor is suppressed here, so perf stats must come off the body.+ timings = body.get("timings") if isinstance(body, dict) else None,+ stop_reason = (choices[0].get("finish_reason") if choices else None),+ )api_monitor.finish(monitor_id)return _model_json_response(response)except asyncio.CancelledError:@@ -14761,6 +15051,8 @@ async def _responses_stream(full_reasoning = ""input_tokens = 0output_tokens = 0+ # From the chat chunks; applied once before finish, so chunk order does not matter.+ stream_finish_reason: Optional[str] = Noneextractor = _ResponsesReasoningExtractor(parse_think_markers = _responses_should_parse_think_markers(chat_req, llama_backend))@@ -15248,6 +15540,8 @@ async def _responses_stream(if not choices:_apply_usage(chunk_data.get("usage"))continue+ if choices[0].get("finish_reason"):+ stream_finish_reason = choices[0]["finish_reason"]delta = choices[0].get("delta", {}) or {}reasoning_delta, visible_delta = extractor.feed(@@ -15255,6 +15549,9 @@ async def _responses_stream(delta.get("reasoning_content"),)if reasoning_delta:+ # Not on visible text: the client already has this, so waiting would+ # time from the end of the thinking block instead.+ api_monitor.mark_first_token(monitor_id)for event in _ensure_reasoning_open():yield eventfull_reasoning += reasoning_delta@@ -15285,6 +15582,10 @@ async def _responses_stream(elif visible_delta:healed_events = healer.feed(visible_delta)visible_delta = ""+ if healed_events:+ # Not append_reply below: this is where the client first sees+ # the promoted tool call or its surrounding text.+ api_monitor.mark_first_token(monitor_id)for event in _healed_event_sse(healed_events):yield eventif visible_delta:@@ -15304,6 +15605,9 @@ async def _responses_stream(},)+ if delta.get("tool_calls"):+ # A tool call is output the client already received; stamp it too.+ api_monitor.mark_first_token(monitor_id)for tc in delta.get("tool_calls") or []:if (payload.parallel_tool_calls is False@@ -15360,6 +15664,8 @@ async def _responses_stream(final_reasoning, final_visible = extractor.finish()if final_reasoning:+ # Held-back markers can make this the FIRST output of all.+ api_monitor.mark_first_token(monitor_id)for event in _ensure_reasoning_open():yield eventfull_reasoning += final_reasoning@@ -15379,6 +15685,10 @@ async def _responses_stream(if healer is not None:events = (healer.feed(final_visible) if final_visible else []) + healer.finalize()final_visible = ""+ if events:+ # Same as the in-loop stamp: this is where the client first sees+ # the promoted call, and the item only closes several yields later.+ api_monitor.mark_first_token(monitor_id)for event in _healed_event_sse(events):yield eventif final_visible:@@ -15558,6 +15868,13 @@ async def _responses_stream(},},}+ # A healed call reaches the client as a function_call item while the upstream chunk+ # still says "stop", so report what this adapter emitted -- same rule the chat+ # stream's synthetic finish line applies.+ if healer is not None and healer.healed:+ stream_finish_reason = "tool_calls"+ if stream_finish_reason:+ api_monitor.set_perf(monitor_id, stop_reason = stream_finish_reason)api_monitor.finish(monitor_id)yield _sse("response.completed", completed_response)diff --git a/studio/backend/tests/test_active_generations.py b/studio/backend/tests/test_active_generations.pyindex 13acf519b34..3b74a0a8799 100644--- a/studio/backend/tests/test_active_generations.py+++ b/studio/backend/tests/test_active_generations.py@@ -2731,3 +2731,97 @@ def test_claim_order_matches_send_order_under_concurrent_dispatch():t.join(timeout = 30)assert orch._active_cancel_events == sent, "claim order must equal send order"+++def test_responses_stream_reports_reasoning_ttft_and_stop_reason(monkeypatch):+ # This adapter parses SSE itself, so without its own stamp a reasoning-first+ # turn would time from the visible text instead.+ import asyncio++ from core.inference.api_monitor import api_monitor+ from models.inference import ChatMessage, ResponsesRequest++ inf_mod = _install_responses_stream_mock(+ monkeypatch,+ [+ {"choices": [{"delta": {"reasoning_content": "thinking"}}]},+ {"choices": [{"delta": {"content": "hi"}, "finish_reason": "length"}]},+ ],+ )+ payload = ResponsesRequest(input = "hi", stream = True, model = "org/M-GGUF")+ messages = [ChatMessage(role = "user", content = "hi")]++ monitor_id = api_monitor.start(+ endpoint = "/v1/responses", method = "POST", model = "org/M-GGUF", prompt = "hi"+ )++ async def run():+ response = await inf_mod._responses_stream(+ payload, messages, _NeverDisconnectedRequest(), monitor_id+ )+ async for _ in response.body_iterator:+ pass++ asyncio.run(run())++ rows = [r for r in api_monitor.snapshot() if r["id"] == monitor_id]+ assert rows, "the stream should have opened a monitor row"+ assert rows[0]["ttft_ms"] is not None+ assert rows[0]["stop_reason"] == "length"+++def test_responses_stream_stamps_tool_call_deltas(monkeypatch):+ # A tool-call-opening turn already sent client output, so TTFT must stamp there.+ import asyncio++ from core.inference.api_monitor import api_monitor+ from models.inference import ChatMessage, ResponsesRequest++ inf_mod = _install_responses_stream_mock(+ monkeypatch,+ [+ {+ "choices": [+ {+ "delta": {+ "tool_calls": [+ {+ "index": 0,+ "id": "call_1",+ "function": {"name": "f", "arguments": "{}"},+ }+ ]+ }+ }+ ]+ },+ {"choices": [{"delta": {}, "finish_reason": "tool_calls"}]},+ ],+ )+ payload = ResponsesRequest(input = "hi", stream = True, model = "org/M-GGUF")+ messages = [ChatMessage(role = "user", content = "hi")]+ monitor_id = api_monitor.start(+ endpoint = "/v1/responses", method = "POST", model = "org/M-GGUF", prompt = "hi"+ )+ # append_reply would stamp late; assert it happens at the delta instead.+ stamped: list[str] = []+ real_mark = api_monitor.mark_first_token+ monkeypatch.setattr(+ api_monitor,+ "mark_first_token",+ lambda mid: (stamped.append(mid), real_mark(mid))[1],+ )++ async def run():+ response = await inf_mod._responses_stream(+ payload, messages, _NeverDisconnectedRequest(), monitor_id+ )+ async for _ in response.body_iterator:+ pass++ asyncio.run(run())++ assert stamped, "the tool-call delta should stamp the first token"+ [row] = [r for r in api_monitor.snapshot() if r["id"] == monitor_id]+ assert row["ttft_ms"] is not None+ assert row["stop_reason"] == "tool_calls"diff --git a/studio/backend/tests/test_api_monitor.py b/studio/backend/tests/test_api_monitor.pyindex 55f30b9fa7a..dadf9dc06fe 100644--- a/studio/backend/tests/test_api_monitor.py+++ b/studio/backend/tests/test_api_monitor.py@@ -1,6 +1,10 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+import itertools+import json++import pytestfrom fastapi import FastAPIfrom fastapi.testclient import TestClient@@ -704,3 +708,819 @@ def test_monitor_route_disabled_still_hides_recorded_rows(monkeypatch):assert payload["logging_enabled"] is Falseassert payload["entries"] == []+++def test_set_perf_records_stats_and_snapshot_reports_them():+ monitor = ApiMonitor(max_entries = 3)+ entry_id = monitor.start(+ endpoint = "/v1/chat/completions",+ method = "POST",+ model = "local-model",+ prompt = "user: hello",+ )+ # set_reply never stamps TTFT; this is the case the prompt_ms fallback exists for.+ monitor.set_reply(entry_id, "hi")+ monitor.set_perf(entry_id, tok_per_sec = 42.5, prompt_ms = 123.4, stop_reason = "length")+ monitor.finish(entry_id)++ [entry] = monitor.snapshot()+ assert entry["tok_per_sec"] == 42.5+ assert entry["ttft_ms"] == 123+ assert entry["stop_reason"] == "length"+++def test_measured_ttft_wins_over_engine_prefill():+ # Queue wait precedes llama-server, so prefill-only prompt_ms under-reports TTFT.+ monitor = ApiMonitor(max_entries = 3)+ entry_id = monitor.start(+ endpoint = "/v1/chat/completions",+ method = "POST",+ model = "local-model",+ prompt = "user: hello",+ )+ entry = next(e for e in monitor._entries if e.id == entry_id)+ entry.started_monotonic -= 2.0+ monitor.append_reply(entry_id, "hi")+ monitor.set_perf(entry_id, tok_per_sec = 42.5, prompt_ms = 120.0)+ monitor.finish(entry_id)++ [snapshot] = monitor.snapshot()+ assert snapshot["ttft_ms"] >= 2000+++def test_set_perf_rejects_non_finite_values():+ monitor = ApiMonitor(max_entries = 3)+ entry_id = monitor.start(+ endpoint = "/v1/chat/completions",+ method = "POST",+ model = "local-model",+ prompt = "user: hello",+ )+ monitor.set_perf(entry_id, tok_per_sec = float("nan"), prompt_ms = float("inf"))+ monitor.set_perf(entry_id, tok_per_sec = "bogus", prompt_ms = None)+ monitor.finish(entry_id)++ [entry] = monitor.snapshot()+ assert entry["tok_per_sec"] is None+ assert entry["ttft_ms"] is None+++def test_full_response_reply_does_not_stamp_ttft():+ monitor = ApiMonitor(max_entries = 3)+ entry_id = monitor.start(+ endpoint = "/v1/chat/completions",+ method = "POST",+ model = "local-model",+ prompt = "user: hello",+ )+ monitor.set_reply(entry_id, "full response")+ monitor.append_reply(entry_id, " tail", stamp_first_token = False)+ monitor.finish(entry_id)++ [entry] = monitor.snapshot()+ assert entry["ttft_ms"] is None+ assert entry["tok_per_sec"] is None+++def test_set_usage_rejects_malformed_token_counts():+ monitor = ApiMonitor(max_entries = 3)+ entry_id = monitor.start(+ endpoint = "/v1/chat/completions",+ method = "POST",+ model = "local-model",+ prompt = "user: hello",+ )+ monitor.append_reply(entry_id, "hi")+ monitor.set_usage(+ entry_id,+ prompt_tokens = -3,+ completion_tokens = "bogus",+ total_tokens = 12,+ )+ monitor.finish(entry_id)++ [entry] = monitor.snapshot()+ assert entry["prompt_tokens"] is None+ assert entry["completion_tokens"] is None+ assert entry["total_tokens"] == 12+ assert entry["tok_per_sec"] is None+++def test_mark_first_token_stamps_ttft_for_reasoning_only_streams():+ monitor = ApiMonitor(max_entries = 3)+ entry_id = monitor.start(+ endpoint = "/v1/chat/completions",+ method = "POST",+ model = "local-model",+ prompt = "user: hello",+ )+ monitor.mark_first_token(entry_id)+ monitor.finish(entry_id)++ [entry] = monitor.snapshot()+ assert entry["ttft_ms"] is not None++ entry_id2 = monitor.start(+ endpoint = "/v1/chat/completions",+ method = "POST",+ model = "local-model",+ prompt = "user: hello",+ )+ monitor.mark_first_token(entry_id2)+ first = monitor._find_locked(entry_id2).first_token_monotonic+ monitor.append_reply(entry_id2, "visible")+ assert monitor._find_locked(entry_id2).first_token_monotonic == first+++def test_queue_state_counts_direct_overflow_as_queued(monkeypatch):+ # Direct calls hold no lease, so overflow past capacity must show as queued,+ # not get clamped out of the readout.+ from types import SimpleNamespace++ import routes.inference as inf++ monkeypatch.setattr(+ inf,+ "get_llama_cpp_backend",+ lambda: SimpleNamespace(+ is_loaded = True,+ is_diffusion = False,+ base_url = "http://llama.test",+ effective_parallel_slots = 1,+ ),+ )+ monkeypatch.setattr(inf, "peek_llama_admission_snapshot", lambda _base: None)+ monkeypatch.setattr(inf, "_direct_llama_inflight", 2)++ state = inf._monitor_queue_state()+ assert state == {"capacity": 1, "active": 1, "queued": 1, "free": 0}+++def test_non_streaming_responses_reports_its_finish_reason(monkeypatch):+ # Stop reason must be read off the choice, or the row shows a blank.+ import routes.inference as inf++ monitor = ApiMonitor(max_entries = 3)+ monkeypatch.setattr(inf, "api_monitor", monitor)+ entry_id = monitor.start(+ endpoint = "/v1/responses",+ method = "POST",+ model = "local-model",+ prompt = "user: hello",+ )+ body = {+ "choices": [{"message": {"content": "hi"}, "finish_reason": "length"}],+ "timings": {"predicted_per_second": 12.5, "prompt_ms": 80.0},+ }+ choices = body.get("choices", [])+ # Mirrors the call the route makes at the end of _responses_non_streaming.+ inf._monitor_usage(+ entry_id,+ {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2},+ None,+ timings = body.get("timings"),+ stop_reason = (choices[0].get("finish_reason") if choices else None),+ )+ monitor.finish(entry_id)++ [entry] = monitor.snapshot()+ assert entry["stop_reason"] == "length"+ assert entry["tok_per_sec"] == 12.5+ assert entry["ttft_ms"] == 80+++def test_parked_tool_resume_counts_as_queued():+ # Without resume tickets counted, the readout shows a full server with nothing queued.+ from core.inference.llama_admission import LlamaAdmissionQueue++ queue = LlamaAdmissionQueue("http://llama.test")+ queue._unpark_tickets.append(1)+ assert queue.snapshot().queued == 1+++def test_free_never_reports_a_slot_admission_would_refuse():+ """`free` is what a new arrival could take, so it must track _can_admit_locked:+ a resume ticket holds a slot back, so counting it in `queued` without dropping it+ from `free` prints free slots next to a queued request.+ """+ from core.inference.llama_admission import LlamaAdmissionQueue+ for capacity, held, tickets in itertools.product(range(1, 5), range(0, 5), range(0, 3)):+ if held > capacity:+ continue+ queue = LlamaAdmissionQueue("http://llama.test")+ queue._resize_pool_locked(capacity)+ if any(queue._take_slot_locked(0) is None for _ in range(held)):+ continue+ for _ in range(tickets):+ queue._unpark_seq += 1+ queue._unpark_tickets.append(queue._unpark_seq)++ snapshot = queue.snapshot()+ admittable = queue._can_admit_locked(len(queue._unpark_tickets))+ assert (snapshot.free > 0) == admittable, (+ f"capacity={capacity} held={held} tickets={tickets}: "+ f"free={snapshot.free} but _can_admit_locked={admittable}"+ )+++def test_queue_panel_never_shows_a_free_slot_next_to_a_resume(monkeypatch):+ """The panel derives free from the snapshot, so it inherits that invariant."""+ from types import SimpleNamespace++ import routes.inference as inf+ from core.inference.llama_admission import LlamaAdmissionQueue++ queue = LlamaAdmissionQueue("http://llama.test")+ queue._unpark_tickets.append(1)+ monkeypatch.setattr(+ inf,+ "get_llama_cpp_backend",+ lambda: SimpleNamespace(+ is_loaded = True,+ is_diffusion = False,+ base_url = "http://llama.test",+ effective_parallel_slots = 1,+ ),+ )+ monkeypatch.setattr(inf, "peek_llama_admission_snapshot", lambda _base: queue.snapshot())+ monkeypatch.setattr(inf, "_direct_llama_inflight", 0)++ assert inf._monitor_queue_state() == {"capacity": 1, "active": 0, "queued": 1, "free": 0}+++def test_set_perf_survives_an_out_of_range_engine_number():+ """float() on a huge upstream int raises OverflowError, which is not ValueError,+ and these helpers run inside streaming generators where a raise truncates the+ user's response.+ """+ monitor = ApiMonitor(max_entries = 3)+ entry_id = monitor.start(+ endpoint = "/v1/chat/completions",+ method = "POST",+ model = "local-model",+ prompt = "user: hello",+ )+ huge = int("9" * 400)+ monitor.set_perf(entry_id, tok_per_sec = huge, prompt_ms = huge, stop_reason = "stop")+ monitor.finish(entry_id)++ [entry] = monitor.snapshot()+ assert entry["tok_per_sec"] is None+ assert entry["ttft_ms"] is None+ assert entry["stop_reason"] == "stop"+++ "chunk",+ [+ {"choices": [{"delta": {"content": "x"}}], "timings": {"predicted_per_second": 10**400}},+ {"choices": [{"delta": {"content": "x"}}], "timings": {"prompt_ms": 10**400}},+ {"choices": [{"delta": {"content": "x"}}], "usage": {"total_tokens": 10**400}},+ {"choices": [{"delta": {"content": "x"}}], "usage": "not-a-dict"},+ {"choices": [{"delta": {"content": "x"}}], "timings": "not-a-dict"},+ {"choices": "not-a-list"},+ {"choices": [{"delta": "not-a-dict"}]},+ {},+ ],+)+def test_monitor_chunk_never_raises_on_a_malformed_upstream_chunk(monkeypatch, chunk):+ """A raise here escapes into the SSE generator and truncates the response."""+ import routes.inference as inf++ monitor = ApiMonitor(max_entries = 3)+ monkeypatch.setattr(inf, "api_monitor", monitor)+ entry_id = monitor.start(+ endpoint = "/v1/chat/completions",+ method = "POST",+ model = "local-model",+ prompt = "user: hello",+ )+ inf._monitor_openai_chunk(entry_id, chunk, 4096, streaming = True)+ # snapshot() divides by the recorded counts, so it has to survive them too.+ assert monitor.snapshot()+++def test_direct_llama_counter_is_started_last_before_its_guarding_try():+ """Anything between started() and the try leaks a permanent +1 if it raises, and+ this counter has no reset hook, so one leak pins the slot panel at busy until the+ process restarts.+ """+ import ast+ import inspect+ import textwrap++ for func_name in ("openai_completions", "openai_embeddings", "_direct_llama_request"):+ tree = ast.parse(textwrap.dedent(inspect.getsource(getattr(inference_route, func_name))))+ started = [+ node+ for node in ast.walk(tree)+ if isinstance(node, ast.Expr)+ and isinstance(node.value, ast.Call)+ and isinstance(node.value.func, ast.Name)+ and node.value.func.id == "_direct_llama_request_started"+ ]+ assert started, f"{func_name}: no _direct_llama_request_started() call found"++ for node in ast.walk(tree):+ block = getattr(node, "body", None)+ if not isinstance(block, list):+ continue+ for index, stmt in enumerate(block):+ if not any(stmt is call for call in started):+ continue+ assert index + 1 < len(block) and isinstance(block[index + 1], ast.Try), (+ f"{func_name}: _direct_llama_request_started() is not immediately "+ f"followed by the try whose finally decrements it:\n"+ + "\n".join(ast.unparse(s) for s in block[index : index + 3])+ )+++def _llama_slot_readout(+ monkeypatch,+ *,+ is_audio = False,+ slots = 4,+):+ """Point the slot readout at a loaded llama-server with ``slots`` free slots."""+ from types import SimpleNamespace++ import routes.inference as inf++ backend = SimpleNamespace(+ is_loaded = True,+ is_diffusion = False,+ is_vision = True,+ base_url = "http://llama.test",+ effective_parallel_slots = slots,+ context_length = 4096,+ model_identifier = "some/tts-GGUF",+ _is_audio = is_audio,+ _audio_type = "codec",+ _auth_headers = None,+ )+ monkeypatch.setattr(inf, "get_llama_cpp_backend", lambda: backend)+ monkeypatch.setattr(inf, "peek_llama_admission_snapshot", lambda _base: None)+ monkeypatch.setattr(inf, "_direct_llama_inflight", 0)+ return backend+++def test_queue_state_counts_rag_vision_captioning(monkeypatch):+ """RAG captioning/OCR reaches llama-server with no lease (see the+ LlamaAdmissionQueue docstring), so without the direct count the panel reported an+ idle server for the whole ingestion.+ """+ import routes.inference as inf+ from core.rag import captioner++ _llama_slot_readout(monkeypatch)+ seen = {}++ class _Resp:+ status_code = 200++ def raise_for_status(self):+ pass++ def json(self):+ return {"choices": [{"message": {"content": "a caption"}}]}++ def _fake_post(*_a, **_k):+ seen["state"] = inf._monitor_queue_state()+ return _Resp()++ monkeypatch.setattr("httpx.post", _fake_post)++ assert captioner._caption_one("http://llama.test", "local", b"png", 5.0) == "a caption"+ assert seen["state"] == {"capacity": 4, "active": 1, "queued": 0, "free": 3}+ assert inf._monitor_queue_state() == {"capacity": 4, "active": 0, "queued": 0, "free": 4}++[email protected]("fails", [False, True])+def test_rag_vision_call_balances_the_direct_counter(monkeypatch, fails):+ """Both outcomes must return the count to zero: a failed vision call is swallowed+ as non-fatal, so a leak here would pin the panel at busy for the whole session.+ """+ import routes.inference as inf+ from core.rag import captioner++ _llama_slot_readout(monkeypatch)++ class _Resp:+ status_code = 500++ def raise_for_status(self):+ raise RuntimeError("llama-server said no")++ def json(self):+ return {"choices": [{"message": {"content": "ok"}}]}++ def _fake_post(*_a, **_k):+ if fails:+ raise RuntimeError("connection refused")+ return _Resp()++ monkeypatch.setattr("httpx.post", _fake_post)++ assert captioner._ocr_one("http://llama.test", "local", b"png", 5.0) is None+ assert inf._direct_llama_inflight == 0+++def _run_gguf_tts(monkeypatch, backend, generate):+ """Drive POST /audio/generate onto the GGUF (llama-server) branch."""+ import asyncio++ import routes.inference as inf+ from models.inference import ChatCompletionRequest++ backend.generate_audio_response = generate+ monkeypatch.setattr(inf, "_llama_public_model_id", lambda *_a, **_k: "some/tts-GGUF")+ monkeypatch.setattr(inf, "_fill_recommended_sampling_openai", lambda *_a, **_k: None)++ async def _noop_switch(*_a, **_k):+ return None++ monkeypatch.setattr(inf, "_maybe_auto_switch_model", _noop_switch)+ payload = ChatCompletionRequest(+ model = "some/tts-GGUF", messages = [{"role": "user", "content": "hi"}]+ )+ return asyncio.run(inf.generate_audio(payload, request = None, current_subject = "t"))+++def test_queue_state_counts_gguf_tts(monkeypatch):+ """GGUF TTS holds a llama-server slot for the whole request without a lease."""+ import routes.inference as inf++ backend = _llama_slot_readout(monkeypatch, is_audio = True)+ seen = {}++ def _generate(**_kwargs):+ seen["state"] = inf._monitor_queue_state()+ return (b"RIFFfake", 24000)++ _run_gguf_tts(monkeypatch, backend, _generate)+ assert seen["state"] == {"capacity": 4, "active": 1, "queued": 0, "free": 3}+ assert inf._monitor_queue_state() == {"capacity": 4, "active": 0, "queued": 0, "free": 4}++[email protected]("outcome", ["completed", "raised", "disconnected"])+def test_gguf_tts_balances_the_direct_counter(monkeypatch, outcome):+ """Every exit from the TTS branch gives the slot back; the counter has no reset hook."""+ from fastapi import HTTPException++ import routes.inference as inf++ backend = _llama_slot_readout(monkeypatch, is_audio = True)++ def _generate(**kwargs):+ if outcome == "raised":+ raise RuntimeError("llama-server died")+ if outcome == "disconnected":+ kwargs["cancel_event"].set()+ raise RuntimeError("stream closed")+ return (b"RIFFfake", 24000)++ if outcome == "completed":+ _run_gguf_tts(monkeypatch, backend, _generate)+ else:+ with pytest.raises(HTTPException) as excinfo:+ _run_gguf_tts(monkeypatch, backend, _generate)+ assert excinfo.value.status_code == (499 if outcome == "disconnected" else 500)++ assert inf._direct_llama_inflight == 0+++def test_top_level_provider_tool_event_stamps_first_token(monkeypatch):+ # _toolEvent rides the chunk itself, beside choices, with an empty delta.+ import routes.inference as inf++ monitor = ApiMonitor(max_entries = 3)+ monkeypatch.setattr(inf, "api_monitor", monitor)+ entry_id = monitor.start(+ endpoint = "/v1/chat/completions",+ method = "POST",+ model = "provider/model",+ prompt = "hi",+ )+ inf._monitor_openai_chunk(+ entry_id,+ {+ "object": "chat.completion.chunk",+ "choices": [{"index": 0, "delta": {}, "finish_reason": None}],+ "_toolEvent": {"type": "web_search"},+ },+ streaming = True,+ )+ monitor.finish(entry_id)++ [entry] = monitor.snapshot()+ assert entry["ttft_ms"] is not None+++def test_disagreeing_choice_finish_reasons_report_no_stop_reason(monkeypatch):+ # The row aggregates every choice, so one choice's reason is only the request's+ # when they all agree.+ import routes.inference as inf++ monitor = ApiMonitor(max_entries = 3)+ monkeypatch.setattr(inf, "api_monitor", monitor)++ def row_for(reasons):+ entry_id = monitor.start(+ endpoint = "/v1/chat/completions",+ method = "POST",+ model = "m",+ prompt = "hi",+ )+ inf._monitor_openai_chunk(+ entry_id,+ {+ "choices": [+ {"index": i, "message": {"content": "x"}, "finish_reason": r}+ for i, r in enumerate(reasons)+ ]+ },+ )+ monitor.finish(entry_id)+ return next(r for r in monitor.snapshot() if r["id"] == entry_id)["stop_reason"]++ assert row_for(["stop"]) == "stop"+ assert row_for(["stop", "stop"]) == "stop"+ assert row_for(["stop", "length"]) is None+++def test_streamed_choice_finish_reasons_are_compared_across_chunks(monkeypatch):+ # llama-server streams an n > 1 request as one single-choice chunk per sample, so+ # agreement can only be judged across the whole stream, not inside one chunk.+ import routes.inference as inf++ monitor = ApiMonitor(max_entries = 3)+ monkeypatch.setattr(inf, "api_monitor", monitor)++ def row_for(reasons):+ entry_id = monitor.start(+ endpoint = "/v1/completions",+ method = "POST",+ model = "m",+ prompt = "hi",+ )+ for i, reason in enumerate(reasons):+ inf._monitor_openai_sse_line(+ entry_id,+ "data: "+ + json.dumps({"choices": [{"index": i, "text": "x", "finish_reason": reason}]}),+ )+ monitor.finish(entry_id)+ return next(r for r in monitor.snapshot() if r["id"] == entry_id)["stop_reason"]++ assert row_for(["stop"]) == "stop"+ assert row_for(["stop", "stop"]) == "stop"+ # Used to report "length": each chunk agreed with itself and the last one won.+ assert row_for(["stop", "length"]) is None+++def test_streamed_stop_reason_is_withheld_until_the_request_finishes(monkeypatch):+ # An n > 1 stream finishes its choices in separate chunks, so publishing the first one+ # would state a request-level verdict while the rest are still running, then retract it.+ monitor = ApiMonitor(max_entries = 3)+ entry_id = monitor.start(+ endpoint = "/v1/completions",+ method = "POST",+ model = "m",+ prompt = "hi",+ )++ def row():+ return next(r for r in monitor.snapshot() if r["id"] == entry_id)++ monitor.note_stop_reason(entry_id, "stop")+ assert row()["finished_at"] is None+ assert row()["stop_reason"] is None+ monitor.note_stop_reason(entry_id, "stop")+ assert row()["stop_reason"] is None+ monitor.finish(entry_id)+ assert row()["stop_reason"] == "stop"++[email protected]("writer", ["note_stop_reason", "set_perf"])+ "status, expected",+ [("completed", "stop"), ("cancelled", None), ("failed", None), ("error", None)],+)+def test_stop_reason_is_kept_only_by_completed_requests(writer, status, expected):+ # A cancelled n > 1 stream stopped its remaining choices rather than hearing from+ # them, and several local streams record "stop" through set_perf on the way out of a+ # cancelled loop, before the cancellation is stamped. Neither describes how it ended.+ monitor = ApiMonitor(max_entries = 3)+ entry_id = monitor.start(+ endpoint = "/v1/completions",+ method = "POST",+ model = "m",+ prompt = "hi",+ )+ if writer == "set_perf":+ monitor.set_perf(entry_id, stop_reason = "stop")+ else:+ monitor.note_stop_reason(entry_id, "stop")+ if status == "error":+ monitor.fail(entry_id, "boom")+ else:+ monitor.finish(entry_id, status)+ row = next(r for r in monitor.snapshot() if r["id"] == entry_id)+ assert row["status"] == status+ assert row["stop_reason"] == expected+++def test_non_streaming_stop_reason_survives_the_finish(monkeypatch):+ # Nothing accumulates on that path, so resolving at finish must not clear what+ # set_perf already recorded.+ monitor = ApiMonitor(max_entries = 3)+ entry_id = monitor.start(+ endpoint = "/v1/completions",+ method = "POST",+ model = "m",+ prompt = "hi",+ )+ monitor.set_perf(entry_id, stop_reason = "stop")+ monitor.finish(entry_id)+ assert next(r for r in monitor.snapshot() if r["id"] == entry_id)["stop_reason"] == "stop"+++ "queue, expected",+ [+ ({"capacity": 4, "active": 1, "queued": 0, "free": 3}, "generating"),+ ({"capacity": 4, "active": 0, "queued": 2, "free": 0}, "generating"),+ ({"capacity": 4, "active": 0, "queued": 0, "free": 4}, "ready"),+ (None, "ready"),+ ],+)+def test_monitor_status_counts_slots_no_row_can_see(monkeypatch, queue, expected):+ # A direct llama call (RAG caption/OCR) opens no row, logging may be off, and another+ # subject's work is not counted here, so rows alone would report Ready beside a busy+ # slot readout the same response carries.+ import routes.inference as inf++ monkeypatch.setattr(inf, "api_monitor", ApiMonitor(max_entries = 3))+ monkeypatch.setattr(inf, "_monitor_active_model", lambda: "org/M-GGUF")+ monkeypatch.setattr(inf, "_monitor_context_length", lambda: 4096)+ monkeypatch.setattr(inf, "_monitor_queue_state", lambda: queue)++ app = FastAPI()+ app.include_router(inf.studio_router)+ app.dependency_overrides = {get_current_subject: lambda: "alice"}+ body = TestClient(app).get("/monitor").json()++ assert body["active_requests"] == 0+ assert body["status"] == expected+++def test_monitor_status_is_idle_without_a_model(monkeypatch):+ import routes.inference as inf++ monkeypatch.setattr(inf, "api_monitor", ApiMonitor(max_entries = 3))+ monkeypatch.setattr(inf, "_monitor_active_model", lambda: None)+ monkeypatch.setattr(inf, "_monitor_context_length", lambda: None)+ monkeypatch.setattr(inf, "_monitor_queue_state", lambda: None)++ app = FastAPI()+ app.include_router(inf.studio_router)+ app.dependency_overrides = {get_current_subject: lambda: "alice"}+ assert TestClient(app).get("/monitor").json()["status"] == "idle"+++def test_tool_card_starts_ttft_but_not_the_token_rate_clock(monkeypatch):+ # A tool card is client output, so it starts TTFT. It is not decoded output, so the+ # tool run (or a human confirming one) after it must not count as decoding time --+ # dividing by that wait reports a rate near zero.+ import core.inference.api_monitor as m++ clock = [100.0]+ monkeypatch.setattr(m.time, "monotonic", lambda: clock[0])+ monitor = ApiMonitor(max_entries = 3)+ entry_id = monitor.start(+ endpoint = "/v1/chat/completions",+ method = "POST",+ model = "m",+ prompt = "hi",+ )++ monitor.mark_first_token(entry_id, decoded = False)+ clock[0] = 160.0 # a minute of tool run / human confirmation+ monitor.append_reply(entry_id, "first real token")+ clock[0] = 162.0 # two seconds of decoding+ monitor.set_usage(entry_id, completion_tokens = 21)+ monitor.finish(entry_id)++ row = next(r for r in monitor.snapshot() if r["id"] == entry_id)+ # TTFT still measures from the card the user actually saw.+ assert row["ttft_ms"] == 0+ # 20 gaps over 2s, not over 62s.+ assert row["tok_per_sec"] == 10.0+++def test_a_decoded_first_token_starts_both_clocks(monkeypatch):+ import core.inference.api_monitor as m++ clock = [100.0]+ monkeypatch.setattr(m.time, "monotonic", lambda: clock[0])+ monitor = ApiMonitor(max_entries = 3)+ entry_id = monitor.start(+ endpoint = "/v1/chat/completions",+ method = "POST",+ model = "m",+ prompt = "hi",+ )++ # Reasoning tokens are decoded output, so they start the rate clock as before.+ monitor.mark_first_token(entry_id)+ clock[0] = 102.0+ monitor.set_usage(entry_id, completion_tokens = 21)+ monitor.finish(entry_id)++ assert next(r for r in monitor.snapshot() if r["id"] == entry_id)["tok_per_sec"] == 10.0+++def test_a_stop_reason_written_after_finish_escapes_the_clearing():+ # Why every route records the reason before finish(): the settle runs once, at the+ # terminal transition, so a later write would put a natural stop reason back onto a+ # cancelled row.+ monitor = ApiMonitor(max_entries = 3)+ entry_id = monitor.start(+ endpoint = "/v1/chat/completions",+ method = "POST",+ model = "m",+ prompt = "hi",+ )+ monitor.set_perf(entry_id, stop_reason = "stop")+ monitor.finish(entry_id, "cancelled")+ assert next(r for r in monitor.snapshot() if r["id"] == entry_id)["stop_reason"] is None++ monitor.set_perf(entry_id, stop_reason = "stop")+ assert next(r for r in monitor.snapshot() if r["id"] == entry_id)["stop_reason"] == "stop"+++ "line, dropped",+ [+ ('data: {"choices":[],"usage":{"completion_tokens":9}}', True),+ # A content chunk carrying inline usage still has to reach the client.+ ('data: {"choices":[{"delta":{"content":"x"}}],"usage":{"completion_tokens":9}}', False),+ ('data: {"choices":[{"delta":{"content":"x"}}]}', False),+ # Content that quotes the key gets past the cheap prefilter, so only the parse+ # can tell it apart from a real usage chunk.+ ('data: {"choices":[{"delta":{"content":"\\"usage\\":1"}}]}', False),+ ("data: [DONE]", False),+ ("data: not json", False),+ (": keepalive comment", False),+ ],+)+def test_usage_only_sse_is_recognized_for_relay_filtering(line, dropped):+ # Providers are asked for stream usage regardless of what the caller wanted, so the+ # proxy has to drop the standalone chunk on the way out: a client that did not opt in+ # would index choices[0] on it. Same rule _cmpl_stream_event_out applies locally.+ import routes.inference as inf+ assert inf._is_openai_usage_only_sse(line) is dropped++[email protected]("include_usage, expected", [(True, True), (False, False)])+def test_wants_stream_usage_reads_the_callers_opt_in(include_usage, expected):+ import routes.inference as inf+ from types import SimpleNamespace++ payload = SimpleNamespace(stream_options = {"include_usage": include_usage})+ assert inf._wants_stream_usage(payload) is expected+ assert inf._wants_stream_usage(SimpleNamespace(stream_options = None)) is False+++def test_direct_llama_work_is_busy_without_the_admission_snapshot(monkeypatch):+ # With UNSLOTH_LLAMA_ADMISSION_CONTROL=off the queue readout is None, so a caption or+ # OCR call (which opens no row) would leave the row saying Ready while the server works.+ import routes.inference as inf++ monkeypatch.setattr(inf, "api_monitor", ApiMonitor(max_entries = 3))+ monkeypatch.setattr(inf, "_monitor_active_model", lambda: "org/M-GGUF")+ monkeypatch.setattr(inf, "_monitor_context_length", lambda: 4096)+ monkeypatch.setattr(inf, "_monitor_queue_state", lambda: None)+ monkeypatch.setattr(inf, "_direct_llama_inflight", 1)++ app = FastAPI()+ app.include_router(inf.studio_router)+ app.dependency_overrides = {get_current_subject: lambda: "alice"}+ body = TestClient(app).get("/monitor").json()++ assert body["active_requests"] == 0+ assert body["queue"] is None+ assert body["status"] == "generating"++ # Back to ready once it finishes.+ monkeypatch.setattr(inf, "_direct_llama_inflight", 0)+ assert TestClient(app).get("/monitor").json()["status"] == "ready"+++def test_direct_busy_reads_the_live_counter(monkeypatch):+ import routes.inference as inf++ monkeypatch.setattr(inf, "_direct_llama_inflight", 0)+ assert inf._direct_llama_is_busy() is False+ monkeypatch.setattr(inf, "_direct_llama_inflight", 2)+ assert inf._direct_llama_is_busy() is Truediff --git a/studio/backend/tests/test_external_provider_usage_chunk.py b/studio/backend/tests/test_external_provider_usage_chunk.pyindex 3c5967cc81a..e48ba02e8f7 100644--- a/studio/backend/tests/test_external_provider_usage_chunk.py+++ b/studio/backend/tests/test_external_provider_usage_chunk.py@@ -539,3 +539,97 @@ def test_other_providers_do_not_get_the_continuation_flags(monkeypatch, providerbody = _continuation_body(monkeypatch, provider_type, base_url)assert "continue_final_message" not in bodyassert "add_generation_prompt" not in body+++ "provider_type, expected",+ [+ ("vllm", True),+ ("openrouter", True),+ ("kimi", True),+ # Any user-supplied base_url: a strict endpoint 400s on an unknown field.+ ("custom", False),+ ("ollama", False),+ # "openai" is absent: it routes to /v1/responses, which reports usage itself.+ ],+)+def test_streamed_usage_is_requested_only_where_documented(monkeypatch, provider_type, expected):+ # An OAI-compatible stream omits usage without stream_options.include_usage, and+ # these providers report no llama.cpp timings, so the monitor has no token count to+ # derive a speed from and the row shows a blank Speed for every completed request.+ captured: dict = {}++ def handler(request: httpx.Request) -> httpx.Response:+ captured["body"] = json.loads(request.content.decode("utf-8"))+ return httpx.Response(+ 200,+ content = b'data: {"choices":[{"delta":{"content":"ok"}}]}\n\ndata: [DONE]\n\n',+ headers = {"content-type": "text/event-stream"},+ )++ _mock_http_client(monkeypatch, handler)++ async def run():+ client = ExternalProviderClient(+ provider_type = provider_type,+ base_url = "http://provider.example/v1",+ api_key = "sk-test",+ )+ await _collect(+ client.stream_chat_completion(+ messages = [{"role": "user", "content": "ping"}],+ model = "m",+ temperature = 0.7,+ top_p = 0.95,+ max_tokens = 64,+ )+ )+ await client.close()++ _drive(run())+ assert captured["body"]["stream"] is True+ if expected:+ assert captured["body"]["stream_options"] == {"include_usage": True}+ else:+ assert "stream_options" not in captured["body"]+++def test_kimi_no_search_fallback_requests_usage(monkeypatch):+ # The web-search path returns before the common body injection, and Kimi reports no+ # engine timings, so this fallback would leave tokens and speed blank.+ bodies: list = []++ def handler(request: httpx.Request) -> httpx.Response:+ body = json.loads(request.content.decode("utf-8"))+ bodies.append(body)+ # First call: the model declines to invoke $web_search.+ return httpx.Response(+ 200,+ content = b'data: {"choices":[{"delta":{"content":"hi"}}]}\n\ndata: [DONE]\n\n',+ headers = {"content-type": "text/event-stream"},+ )++ _mock_http_client(monkeypatch, handler)++ async def run():+ client = ExternalProviderClient(+ provider_type = "kimi",+ base_url = "http://kimi.example/v1",+ api_key = "sk-test",+ )+ await _collect(+ client.stream_chat_completion(+ messages = [{"role": "user", "content": "ping"}],+ model = "kimi-k2",+ max_tokens = 64,+ enabled_tools = ["web_search"],+ )+ )+ await client.close()++ _drive(run())+ assert len(bodies) >= 2, "the search call then the plain fallback"+ search_body, fallback_body = bodies[0], bodies[-1]+ assert "tools" in search_body+ assert "tools" not in fallback_body+ assert fallback_body["stream_options"] == {"include_usage": True}diff --git a/studio/backend/tests/test_responses_tool_passthrough.py b/studio/backend/tests/test_responses_tool_passthrough.pyindex 69715649b76..af1751b39ee 100644--- a/studio/backend/tests/test_responses_tool_passthrough.py+++ b/studio/backend/tests/test_responses_tool_passthrough.py@@ -2279,3 +2279,129 @@ class TestResponsesStreamHealing:]assert len(calls) == 1assert calls[0]["item"]["name"] == "lookup"+++def test_healed_responses_tool_call_stamps_first_token(monkeypatch):+ # Healed output bypasses append_reply, so a text-form tool call would go untimed+ # until the item closes near end-of-stream.+ from core.inference.api_monitor import api_monitor++ xml = TestResponsesStreamHealing._XML+ tool = TestResponsesStreamHealing._TOOL+ TestResponsesStreamAdapter._install_stream_mock(+ monkeypatch, [{"choices": [{"delta": {"content": xml}}]}]+ )+ payload = ResponsesRequest(input = "hi", stream = True, tools = [tool])+ messages = [ChatMessage(role = "user", content = "hi")]+ monitor_id = api_monitor.start(+ endpoint = "/v1/responses", method = "POST", model = "org/M-GGUF", prompt = "hi"+ )+ stamped: list[str] = []+ real_mark = api_monitor.mark_first_token+ monkeypatch.setattr(+ api_monitor,+ "mark_first_token",+ lambda mid: (stamped.append(mid), real_mark(mid))[1],+ )++ async def run():+ response = await _responses_stream(+ payload, messages, TestResponsesStreamAdapter._Request(), monitor_id+ )+ return await TestResponsesStreamAdapter._collect(response)++ asyncio.run(run())++ assert stamped, "a healed tool call is output the client already received"+++def test_finalized_healed_tool_call_stamps_first_token(monkeypatch):+ # A response that is only an unclosed tool block heals in finalize() after the+ # chunk loop, so nothing before it stamped; the item closes several yields later.+ from core.inference.api_monitor import api_monitor++ unclosed = '<tool_call>{"name":"lookup","arguments":{"q":"x"}}'+ tool = TestResponsesStreamHealing._TOOL+ TestResponsesStreamAdapter._install_stream_mock(+ monkeypatch, [{"choices": [{"delta": {"content": unclosed}}]}]+ )+ payload = ResponsesRequest(input = "hi", stream = True, tools = [tool])+ messages = [ChatMessage(role = "user", content = "hi")]+ monitor_id = api_monitor.start(+ endpoint = "/v1/responses", method = "POST", model = "org/M-GGUF", prompt = "hi"+ )+ stamped: list[str] = []+ real_mark = api_monitor.mark_first_token+ monkeypatch.setattr(+ api_monitor,+ "mark_first_token",+ lambda mid: (stamped.append(mid), real_mark(mid))[1],+ )++ async def run():+ response = await _responses_stream(+ payload, messages, TestResponsesStreamAdapter._Request(), monitor_id+ )+ return await TestResponsesStreamAdapter._collect(response)++ lines = asyncio.run(run())++ # The call really was promoted, so the stamp covers a function_call the client saw.+ assert any("response.function_call_arguments.delta" in line for line in lines)+ assert stamped, "a finalized healed call is output the client already received"+++def test_healed_responses_tool_call_reports_a_tool_call_stop(monkeypatch):+ # The upstream chunk still says "stop" while this adapter emitted a function_call,+ # so the monitor would disagree with the chat stream's synthetic finish line.+ from core.inference.api_monitor import api_monitor++ xml = TestResponsesStreamHealing._XML+ tool = TestResponsesStreamHealing._TOOL+ TestResponsesStreamAdapter._install_stream_mock(+ monkeypatch,+ [{"choices": [{"delta": {"content": xml}, "finish_reason": "stop"}]}],+ )+ payload = ResponsesRequest(input = "hi", stream = True, tools = [tool])+ messages = [ChatMessage(role = "user", content = "hi")]+ monitor_id = api_monitor.start(+ endpoint = "/v1/responses", method = "POST", model = "org/M-GGUF", prompt = "hi"+ )++ async def run():+ response = await _responses_stream(+ payload, messages, TestResponsesStreamAdapter._Request(), monitor_id+ )+ return await TestResponsesStreamAdapter._collect(response)++ asyncio.run(run())++ row = next(r for r in api_monitor.snapshot() if r["id"] == monitor_id)+ assert row["stop_reason"] == "tool_calls"+++def test_unhealed_responses_stream_keeps_the_upstream_stop(monkeypatch):+ # Nothing was promoted, so the upstream reason still describes the response.+ from core.inference.api_monitor import api_monitor++ tool = TestResponsesStreamHealing._TOOL+ TestResponsesStreamAdapter._install_stream_mock(+ monkeypatch,+ [{"choices": [{"delta": {"content": "plain text"}, "finish_reason": "stop"}]}],+ )+ payload = ResponsesRequest(input = "hi", stream = True, tools = [tool])+ messages = [ChatMessage(role = "user", content = "hi")]+ monitor_id = api_monitor.start(+ endpoint = "/v1/responses", method = "POST", model = "org/M-GGUF", prompt = "hi"+ )++ async def run():+ response = await _responses_stream(+ payload, messages, TestResponsesStreamAdapter._Request(), monitor_id+ )+ return await TestResponsesStreamAdapter._collect(response)++ asyncio.run(run())++ row = next(r for r in api_monitor.snapshot() if r["id"] == monitor_id)+ assert row["stop_reason"] == "stop"diff --git a/studio/backend/tests/test_sf_client_tools_passthrough.py b/studio/backend/tests/test_sf_client_tools_passthrough.pyindex 3cc7d0604ff..026051d7d2d 100644--- a/studio/backend/tests/test_sf_client_tools_passthrough.py+++ b/studio/backend/tests/test_sf_client_tools_passthrough.py@@ -13,6 +13,8 @@ import asyncioimport jsonfrom types import SimpleNamespace+import pytest+from models.inference import ChatCompletionRequest, ChatMessagefrom routes.inference import openai_chat_completionsfrom core.inference.api_monitor import ApiMonitor@@ -362,6 +364,58 @@ def test_usage_recorded_when_stats_present(monkeypatch):assert entry["completion_tokens"] == 3+class _ToolLoopBackend(_ScriptedBackend):+ """Server-side tool loop: the event stream the GGUF loop also emits."""++ def generate_chat_completion_with_tools(+ self,+ *,+ messages,+ tools = None,+ stats_holder = None,+ **kwargs,+ ):+ self.calls.append({"messages": messages, "tools": tools, **kwargs})+ if stats_holder is not None and self._stats is not None:+ stats_holder["stats"] = self._stats+ yield {"type": "content", "text": "done"}+++ "kind, stream, expected",+ [+ ("plain", True, "stop"),+ ("plain", False, "stop"),+ ("healed", True, "tool_calls"),+ ("healed", False, "tool_calls"),+ ("tool_loop", True, "stop"),+ ("tool_loop", False, "stop"),+ ],+)+def test_stop_reason_recorded_without_backend_stats(monkeypatch, kind, stream, expected):+ # last_generation_stats is MLX-only, so a transformers generation leaves+ # stats_holder empty; the stop reason must not ride along with it.+ if kind == "tool_loop":+ backend = _ToolLoopBackend(_fixed("done"))+ payload = _request(stream = stream, enable_tools = True)+ elif kind == "healed":+ backend = _ScriptedBackend(_fixed(_CALL_XML))+ payload = _request(stream = stream, tools = [LOOKUP_TOOL])+ else:+ backend = _ScriptedBackend(_fixed("plain answer"))+ payload = _request(stream = stream)+ monitor = _install(monkeypatch, backend)++ async def _run():+ return await openai_chat_completions(payload, request = _Request(), current_subject = "u")++ response = asyncio.run(_run())+ if stream:+ _collect_sse(response)+ [entry] = monitor.snapshot()+ assert entry["stop_reason"] == expected++# ── Nudge ─────────────────────────────────────────────────────────diff --git a/studio/frontend/src/features/api-monitor/api-monitor-page.tsx b/studio/frontend/src/features/api-monitor/api-monitor-page.tsxindex 11e2cc932a9..0df5b96a861 100644--- a/studio/frontend/src/features/api-monitor/api-monitor-page.tsx+++ b/studio/frontend/src/features/api-monitor/api-monitor-page.tsx@@ -83,6 +83,13 @@ function formatCount(value: number): string {return value.toLocaleString();}+function formatTokPerSec(value?: number | null): string | null {+ if (value == null || value <= 0) {+ return null;+ }+ return `${value >= 100 ? Math.round(value) : value.toFixed(1)} tok/s`;+}+function compactEndpoint(endpoint: string): string {return endpoint.replace(API_INFERENCE_PREFIX_RE, "/api")@@ -298,8 +305,11 @@ function RequestRow({<span className="truncate text-ui-11 text-muted-foreground">{entry.model}</span>- <span className="ml-auto shrink-0 text-ui-11 tabular-nums text-muted-foreground">- {formatTime(entry.started_at)}+ <span className="ml-auto flex shrink-0 items-center gap-2 text-ui-11 tabular-nums text-muted-foreground">+ {formatTokPerSec(entry.tok_per_sec) ? (+ <span>{formatTokPerSec(entry.tok_per_sec)}</span>+ ) : null}+ <span>{formatTime(entry.started_at)}</span></span></div><p@@ -441,6 +451,18 @@ function RequestDetail({? formatCount(entry.context_length): "–",},+ {+ label: "First token",+ value: entry.ttft_ms != null ? formatDuration(entry.ttft_ms) : "–",+ },+ {+ label: "Speed",+ value: formatTokPerSec(entry.tok_per_sec) ?? "–",+ },+ {+ label: "Stop reason",+ value: entry.stop_reason ?? "–",+ },].map((item) => (<div key={item.label} className="flex min-w-0 flex-col gap-0.5"><dt className="truncate text-ui-10 font-medium uppercase tracking-wider text-muted-foreground">@@ -780,6 +802,22 @@ export function ApiMonitorPage(): ReactElement {{statusCopy}</span></div>+ {data?.queue ? (+ <div className="flex min-w-0 flex-col">+ <span className="text-ui-10 font-medium uppercase tracking-wider text-muted-foreground">+ Slots+ </span>+ <span+ className={cn(+ "text-ui-12 tabular-nums text-foreground",+ data.queue.queued > 0 && "text-amber-700 dark:text-amber-500",+ )}+ >+ {data.queue.active}/{data.queue.capacity} busy+ {data.queue.queued > 0 ? ` · ${data.queue.queued} queued` : ""}+ </span>+ </div>+ ) : null}<div className="flex min-w-0 flex-1 flex-col"><span className="text-ui-10 font-medium uppercase tracking-wider text-muted-foreground">Loaded modeldiff --git a/studio/frontend/src/features/chat/types/api.ts b/studio/frontend/src/features/chat/types/api.tsindex 94525b0d1ca..023ef18223d 100644--- a/studio/frontend/src/features/chat/types/api.ts+++ b/studio/frontend/src/features/chat/types/api.ts@@ -373,6 +373,17 @@ export interface ApiMonitorEntry {reason?: "manual" | "idle" | "api" | null;// 0-100 while a download row is running.progress?: number | null;+ // Server-side time to first token (measured, else engine prefill).+ ttft_ms?: number | null;+ tok_per_sec?: number | null;+ stop_reason?: string | null;+}++export interface ApiMonitorQueue {+ capacity: number;+ active: number;+ queued: number;+ free: number;}export interface ApiMonitorResponse {@@ -383,6 +394,8 @@ export interface ApiMonitorResponse {active_model?: string | null;context_length?: number | null;active_requests: number;+ /** Live slot/queue occupancy; null when no llama model is loaded. */+ queue?: ApiMonitorQueue | null;/** Absent on older backends -- treat only an explicit `false` as disabled. */logging_enabled?: boolean;entries: ApiMonitorEntry[];