Skip to content

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

Studio: track API token usage in Profile (#9320)

Etherlc21b05725ec1
diff --git a/studio/backend/core/inference/api_monitor.py b/studio/backend/core/inference/api_monitor.py
index 9219873d481..6747eaf9975 100644
--- a/studio/backend/core/inference/api_monitor.py
+++ b/studio/backend/core/inference/api_monitor.py
@@ -1,18 +1,31 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""Small in-memory monitor for OpenAI-compatible API traffic."""
+"""In-memory API monitor with an optional content-free terminal receipt sink."""
from __future__ import annotations
import math
+import logging
import os
import threading
import time
import uuid
from collections import deque
from dataclasses import dataclass, field
-from typing import Any, Optional
+from typing import Any, Callable, Optional
+
+from storage.api_usage_db import (
+ MAX_ENDPOINT_CHARS,
+ MAX_STATUS_CHARS,
+ ApiUsageReceipt,
+ canonical_api_model,
+ canonical_api_subject,
+)
+
+
+logger = logging.getLogger(__name__)
+TerminalCallback = Callable[[ApiUsageReceipt], None]
_MAX_ENTRIES = 50
@@ -197,13 +210,18 @@ class ApiMonitor:
max_entries: int = _MAX_ENTRIES,
*,
enabled: bool = True,
+ terminal_callback: Optional[TerminalCallback] = None,
):
self._entries: deque[ApiMonitorEntry] = deque()
# Shared rows one subject cleared: deleting would erase another caller's history.
self._hidden_shared: dict[str, set[str]] = {}
self._max_entries = max(0, max_entries)
self._lock = threading.Lock()
+ self._callback_condition = threading.Condition(self._lock)
self._enabled = enabled
+ self._terminal_callback = terminal_callback
+ self._terminal_callback_leases: dict[str, TerminalCallback] = {}
+ self._terminal_callbacks_inflight: dict[Optional[str], int] = {}
@property
def enabled(self) -> bool:
@@ -211,6 +229,38 @@ class ApiMonitor:
startup env var, so nothing may flip it on a live monitor."""
return self._enabled
+ def set_terminal_callback(self, callback: Optional[TerminalCallback]) -> None:
+ """Replace the unleased terminal sink used by tests and embedders."""
+ with self._lock:
+ self._terminal_callback = callback
+
+ def acquire_terminal_callback(self, callback: TerminalCallback) -> str:
+ """Register a callback owned by one lifespan and return its lease token.
+
+ Only the newest live lease is notified, so overlapping lifespans do not
+ duplicate durable receipts. Releasing an older lease cannot disable a
+ newer owner, while releasing the newer one falls back to the older.
+ """
+ lease = uuid.uuid4().hex
+ with self._lock:
+ self._terminal_callback_leases[lease] = callback
+ return lease
+
+ def release_terminal_callback(self, lease: str) -> None:
+ """Remove only the terminal callback registration owned by ``lease``."""
+ with self._callback_condition:
+ self._terminal_callback_leases.pop(lease, None)
+ # A notification may already have captured this callback. Let its
+ # fast enqueue finish before the owner drains/stops the writer.
+ while self._terminal_callbacks_inflight.get(lease, 0):
+ self._callback_condition.wait()
+
+ def _terminal_callback_locked(self) -> tuple[Optional[str], Optional[TerminalCallback]]:
+ if self._terminal_callback_leases:
+ lease = next(reversed(self._terminal_callback_leases))
+ return lease, self._terminal_callback_leases[lease]
+ return None, self._terminal_callback
+
def start(
self,
*,
@@ -226,7 +276,7 @@ class ApiMonitor:
return ""
now = time.time()
entry = ApiMonitorEntry(
- id = f"apireq_{uuid.uuid4().hex[:12]}",
+ id = f"apireq_{uuid.uuid4().hex}",
endpoint = endpoint,
method = method,
# str(): a raw JSON body can carry any type, and a non-string breaks the UI.
@@ -337,7 +387,7 @@ class ApiMonitor:
return
with self._lock:
entry = self._find_locked(entry_id)
- if entry is None:
+ if entry is None or entry.finished_at is not None:
return
# Only a streaming delta stamps TTFT; a full-response append is end-to-end latency.
if stamp_first_token:
@@ -477,7 +527,7 @@ class ApiMonitor:
context_length = _token_count_or_none(context_length)
with self._lock:
entry = self._find_locked(entry_id)
- if entry is None:
+ if entry is None or entry.finished_at is not None:
return
if prompt_tokens is not None:
entry.prompt_tokens = prompt_tokens
@@ -503,6 +553,7 @@ class ApiMonitor:
) -> None:
if not entry_id:
return
+ notification = None
with self._lock:
entry = self._find_locked(entry_id)
if entry is None:
@@ -520,22 +571,28 @@ class ApiMonitor:
self._entries.remove(entry)
self._entries.appendleft(entry)
self._trim_terminal_locked()
+ notification = self._terminal_notification_locked(entry)
+ self._notify_terminal(notification)
def fail_open(self, entry_id: Optional[str], error: str) -> None:
"""Fail only a still-open row: unlike :meth:`fail`, a catch-all in a
``finally`` cannot stamp an error onto a request that already succeeded."""
if not entry_id:
return
+ notification = None
with self._lock:
entry = self._find_locked(entry_id)
if entry is None or entry.finished_at is not None:
return
# Same lock as the check, so a finish() cannot land in between.
self._fail_locked(entry, error)
+ notification = self._terminal_notification_locked(entry)
+ self._notify_terminal(notification)
def fail(self, entry_id: Optional[str], error: str) -> None:
if not entry_id:
return
+ notification = None
with self._lock:
entry = self._find_locked(entry_id)
if entry is None:
@@ -546,6 +603,8 @@ class ApiMonitor:
entry.error = _trim(error, 1000)
return
self._fail_locked(entry, error)
+ notification = self._terminal_notification_locked(entry)
+ self._notify_terminal(notification)
def _fail_locked(self, entry: ApiMonitorEntry, error: str) -> None:
self._settle_stop_reason_locked(entry, False)
@@ -559,6 +618,59 @@ class ApiMonitor:
self._entries.appendleft(entry)
self._trim_terminal_locked()
+ def _terminal_notification_locked(
+ self, entry: ApiMonitorEntry
+ ) -> Optional[tuple[Optional[str], TerminalCallback, ApiUsageReceipt]]:
+ callback_owner, callback = self._terminal_callback_locked()
+ subject = canonical_api_subject(entry.subject)
+ if (
+ callback is None
+ or entry.kind != "request"
+ or entry.via_api_key is not True
+ or not subject
+ or entry.finished_at is None
+ ):
+ return None
+ self._terminal_callbacks_inflight[callback_owner] = (
+ self._terminal_callbacks_inflight.get(callback_owner, 0) + 1
+ )
+ return (
+ callback_owner,
+ callback,
+ ApiUsageReceipt(
+ id = entry.id,
+ subject = subject,
+ endpoint = str(entry.endpoint)[:MAX_ENDPOINT_CHARS],
+ model = canonical_api_model(entry.model),
+ status = str(entry.status)[:MAX_STATUS_CHARS],
+ prompt_tokens = entry.prompt_tokens or 0,
+ completion_tokens = entry.completion_tokens or 0,
+ total_tokens = entry.total_tokens or 0,
+ created_at = int(entry.finished_at * 1000),
+ kind = entry.kind,
+ via_api_key = entry.via_api_key,
+ ),
+ )
+
+ def _notify_terminal(
+ self, notification: Optional[tuple[Optional[str], TerminalCallback, ApiUsageReceipt]]
+ ) -> None:
+ if notification is None:
+ return
+ callback_owner, callback, receipt = notification
+ try:
+ callback(receipt)
+ except Exception: # noqa: BLE001 - monitoring must never break inference.
+ logger.warning("api_monitor.terminal_callback_failed", exc_info = True)
+ finally:
+ with self._callback_condition:
+ remaining = self._terminal_callbacks_inflight.get(callback_owner, 0) - 1
+ if remaining > 0:
+ self._terminal_callbacks_inflight[callback_owner] = remaining
+ else:
+ self._terminal_callbacks_inflight.pop(callback_owner, None)
+ self._callback_condition.notify_all()
+
def snapshot(
self,
*,
diff --git a/studio/backend/main.py b/studio/backend/main.py
index c21165cefe5..1fbc5803f16 100644
--- a/studio/backend/main.py
+++ b/studio/backend/main.py
@@ -746,8 +746,25 @@ async def lifespan(app: FastAPI):
"lifespan startup completed in %.1fms",
(_time.perf_counter() - _lifespan_started) * 1000,
)
+ # Persist only terminal scalar usage from authenticated third-party API
+ # requests. The monitor itself stays storage-agnostic until the production
+ # lifespan is ready, which keeps imports and unit tests deterministic.
+ from core.inference.api_monitor import api_monitor as _api_monitor
+ from storage.api_usage_db import (
+ acquire_api_usage_writer as _acquire_api_usage_writer,
+ enqueue_api_usage as _enqueue_api_usage,
+ release_api_usage_writer as _release_api_usage_writer,
+ )
+
+ _api_usage_writer_lease = _acquire_api_usage_writer()
+ _api_usage_callback_lease = _api_monitor.acquire_terminal_callback(_enqueue_api_usage)
yield
+ # Remove only this lifespan's callback. A concurrently live sibling keeps
+ # both the monitor sink and the shared serialized writer. The final owner
+ # drains accepted receipts off the event loop before stopping the worker.
+ _api_monitor.release_terminal_callback(_api_usage_callback_lease)
+
# Before any shutdown await: a warm finishing during one would still read the lifespan as current.
_stop_post_warm_thread()
@@ -758,6 +775,8 @@ async def lifespan(app: FastAPI):
if _invalidate_detection is not None:
_invalidate_detection()
+ await asyncio.to_thread(_release_api_usage_writer, _api_usage_writer_lease)
+
from core.inference.openai_codex_auth import shutdown_flows
await shutdown_flows()
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 136b1337c69..71452383721 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -1082,6 +1082,7 @@ def _is_openai_usage_only_sse(line: str) -> bool:
_OPENAI_PASSTHROUGH_TERMINAL_GRACE_S = 2.0
+_OPENAI_INTERNAL_USAGE_GRACE_S = 0.25
_SSE_DONE_LINE = "data: [DONE]"
_SSE_DONE_CHUNK = "data: [DONE]\n\n"
@@ -2654,9 +2655,11 @@ def _request_used_api_key(request: Any) -> bool:
using Unsloth". Internal workflow keys (Deep Research, data recipes) are Studio
itself and are excluded, or every research step would pop the API monitor open.
"""
- # Total by construction: this only decides a monitor label and must never fail a
- # load. Saved-secret authorization uses _request_has_api_key instead, narrowed by
- # _request_is_internal_workflow where a Studio workflow needs its own connection.
+ # Total by construction: this must never fail a load. It also gates durable API
+ # usage receipts, so an indeterminate key origin must not attribute Studio's own
+ # workflow traffic to an external caller. Saved-secret authorization uses
+ # _request_has_api_key instead, narrowed by _request_is_internal_workflow where a
+ # Studio workflow needs its own connection.
token = _request_api_key_token(request)
if token is None:
# keyless traffic is someone using Unsloth as an API server too
@@ -2666,7 +2669,7 @@ def _request_used_api_key(request: Any) -> bool:
return not auth_storage.is_internal_api_key(token)
except Exception:
logger.debug("api_monitor.internal_key_probe_failed", exc_info = True)
- return True
+ return False
from state.tool_approvals import resolve_tool_decision
@@ -20073,6 +20076,13 @@ 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"))
+ # llama-server only emits the terminal usage chunk when asked. Always
+ # request it for internal accounting, then keep the caller's opt-in
+ # contract by filtering that chunk through _cmpl_stream_event_out.
+ upstream_body = dict(body)
+ upstream_stream_options = dict(body.get("stream_options") or {})
+ upstream_stream_options["include_usage"] = True
+ upstream_body["stream_options"] = upstream_stream_options
from core.inference.llama_keepwarm import mark_response_failed
client = httpx.AsyncClient(
@@ -20095,7 +20105,7 @@ async def openai_completions(request: Request, current_subject: str = Depends(ge
_direct_llama_request_started()
try:
req = client.build_request(
- "POST", target_url, json = body, headers = {"Connection": "close"}
+ "POST", target_url, json = upstream_body, headers = {"Connection": "close"}
)
first_token_deadline = time.monotonic() + _DEFAULT_FIRST_TOKEN_TIMEOUT_S
# Same event the relay loop polls, so a forced swap ends the request during prefill
@@ -24784,6 +24794,20 @@ async def _anthropic_passthrough_stream(
)
+def _sum_passthrough_attempt_stats(first: dict, retry: dict, selected: dict) -> dict:
+ """Keep selected content with the chronological attempts' aggregate stats."""
+ if not all(isinstance(item, dict) for item in (first, retry, selected)):
+ return selected
+ if not isinstance(first.get("usage"), dict) or not isinstance(retry.get("usage"), dict):
+ return selected
+ aggregate = _summed_tool_loop_stats(first, retry)
+ result = dict(selected)
+ result["usage"] = aggregate["usage"]
+ if "timings" in aggregate:
+ result["timings"] = aggregate["timings"]
+ return result
+
+
async def _anthropic_passthrough_non_streaming(
llama_backend,
openai_messages,
@@ -24905,6 +24929,7 @@ async def _anthropic_passthrough_non_streaming(
and nudge_enabled(nudge_tool_calls)
and nudge_should_retry(data, _allowed_tools, _healing_tools)
):
+ first_data = data
retry_body = {
**body,
"messages": _nudge_retry_messages(
@@ -24916,7 +24941,9 @@ async def _anthropic_passthrough_non_streaming(
if retry_resp.status_code == 200:
retry_data = retry_resp.json()
if response_has_promotable_calls(retry_data, _allowed_tools, openai_tools):
- data = retry_data
+ data = _sum_passthrough_attempt_stats(first_data, retry_data, retry_data)
+ else:
+ data = _sum_passthrough_attempt_stats(first_data, retry_data, first_data)
except (httpx.RequestError, ValueError) as exc:
logger.warning("tool-call nudge retry failed; keeping original: %s", exc)
@@ -25760,6 +25787,10 @@ async def _openai_passthrough_stream_admitted(
body = await _build_openai_passthrough_body_async(
payload, backend_ctx = llama_backend.context_length, llama_backend = llama_backend
)
+ client_wants_usage = _wants_stream_usage(payload)
+ upstream_stream_options = dict(body.get("stream_options") or {})
+ upstream_stream_options["include_usage"] = True
+ body["stream_options"] = upstream_stream_options
# Text-form tool calls from small models get promoted to structured calls on
# the way back (declared client tools only); requests without tools or with
# auto_heal_tool_calls=false keep the unhealed relay. tool_choice constrains
@@ -25995,7 +26026,11 @@ async def _openai_passthrough_stream_admitted(
def _terminal_read_timeout_s() -> Optional[float]:
if terminal_seen:
- return _OPENAI_PASSTHROUGH_TERMINAL_GRACE_S
+ return (
+ _OPENAI_PASSTHROUGH_TERMINAL_GRACE_S
+ if client_wants_usage
+ else _OPENAI_INTERNAL_USAGE_GRACE_S
+ )
return stall_timeout_s
def _heal_transform(chunk_data: dict, raw_line: str) -> list:
@@ -26372,20 +26407,19 @@ 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"
- if monitor_event == "done":
- monitor_done = True
- break
terminal_state = (
_openai_passthrough_terminal_state_from_data(chunk_data)
if out_line is raw_line
else _openai_passthrough_sse_line_terminal_state(out_line)
)
- if terminal_state == "usage" or (
- terminal_state == "finish" and not _wants_stream_usage(payload)
- ):
+ # The upstream usage-only chunk is always requested for
+ # accounting, but remains caller-visible only by opt-in.
+ if terminal_state != "usage" or client_wants_usage:
+ yield out_line + "\n\n"
+ if monitor_event == "done":
+ monitor_done = True
+ break
+ if terminal_state == "usage":
done_line = _SSE_DONE_LINE
_monitor_openai_sse_line(
monitor_id,
@@ -26813,11 +26847,13 @@ async def _openai_passthrough_non_streaming_upstream(
# original prompt prefix intact (llama-server reuses the slot's KV cache)
# plus a two-message nudge suffix. The retry replaces the original response
# only when it actually yields a usable call.
+ usage_aggregated = False
if (
_allowed_tools
and nudge_enabled(payload.nudge_tool_calls)
and nudge_should_retry(data, _allowed_tools, body.get("tools"))
):
+ first_data = data
retry_body = {
**body,
"messages": _nudge_retry_messages(
@@ -26829,14 +26865,18 @@ async def _openai_passthrough_non_streaming_upstream(
if retry_resp.status_code == 200:
retry_data = retry_resp.json()
if response_has_promotable_calls(retry_data, _allowed_tools, body.get("tools")):
- resp, data = retry_resp, retry_data
+ resp = retry_resp
+ data = _sum_passthrough_attempt_stats(first_data, retry_data, retry_data)
+ else:
+ data = _sum_passthrough_attempt_stats(first_data, retry_data, first_data)
+ usage_aggregated = data is not first_data and data is not retry_data
except asyncio.CancelledError:
api_monitor.finish(monitor_id, "cancelled")
raise
except (httpx.RequestError, ValueError) as exc:
logger.warning("tool-call nudge retry failed; keeping original: %s", exc)
- changed = False
+ changed = usage_aggregated
if _context_was_truncated and isinstance(data, dict):
data["context_truncated"] = {
"dropped_messages": _truncated_messages,
diff --git a/studio/backend/routes/profile_stats.py b/studio/backend/routes/profile_stats.py
index ff48646eff7..46e98277c9f 100644
--- a/studio/backend/routes/profile_stats.py
+++ b/studio/backend/routes/profile_stats.py
@@ -34,7 +34,11 @@ async def get_profile_stats(
tz: str = Query("", max_length = 64),
current_subject: str = Depends(get_current_subject),
) -> dict[str, Any]:
- """Usage stats for the signed-in user's local history.
+ """Usage stats from this install, with API receipts scoped to the caller.
+
+ Studio chat and training history is legacy install-wide data because those
+ tables have no subject column. Authenticated external API usage is always
+ filtered to ``current_subject`` and cannot cross accounts.
Days and hours are bucketed in the caller's timezone so a remote browser
does not read the server's calendar. ``tz`` is an IANA name, which carries
@@ -50,6 +54,7 @@ async def get_profile_stats(
days = days,
tz_offset_minutes = tz_offset_minutes,
tz_name = tz,
+ subject = current_subject,
)
except Exception as exc:
raise log_and_http_error(
diff --git a/studio/backend/storage/api_usage_db.py b/studio/backend/storage/api_usage_db.py
new file mode 100644
index 00000000000..6b65193460e
--- /dev/null
+++ b/studio/backend/storage/api_usage_db.py
@@ -0,0 +1,309 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Durable, content-free receipts for authenticated external API usage."""
+
+from __future__ import annotations
+
+import logging
+import hashlib
+import queue
+import sqlite3
+import threading
+import time
+import uuid
+from dataclasses import dataclass
+from typing import Callable, Optional
+
+from storage.studio_db import get_connection
+
+
+# Kept aligned with the API monitor's defensive upper bound. The storage layer
+# validates independently because callers can invoke it directly in tests or
+# future integrations.
+MAX_TOKEN_COUNT = 1 << 40
+MAX_RECEIPT_ID_CHARS = 128
+MAX_SUBJECT_CHARS = 256
+MAX_ENDPOINT_CHARS = 512
+MAX_MODEL_CHARS = 1024
+MAX_STATUS_CHARS = 64
+
+_WRITE_BUSY_TIMEOUT_SECONDS = 0.05
+_WRITE_RETRIES = 20
+_WORKER_BUSY_RETRY_SECONDS = 0.25
+_WORKER_DRAIN_TIMEOUT_SECONDS = 5.0
+
+logger = logging.getLogger(__name__)
+
+
+@dataclass(frozen = True, slots = True)
+class ApiUsageReceipt:
+ """Terminal scalar usage only. Prompts, replies and credentials never enter it."""
+
+ id: str
+ subject: str
+ endpoint: str
+ model: str
+ status: str
+ prompt_tokens: int
+ completion_tokens: int
+ total_tokens: int
+ created_at: int
+ kind: str = "request"
+ via_api_key: bool = True
+
+
+def _valid_token_count(value: object) -> bool:
+ return isinstance(value, int) and not isinstance(value, bool) and 0 <= value <= MAX_TOKEN_COUNT
+
+
+def _bounded_text(value: object, limit: int, *, truncate: bool) -> Optional[str]:
+ if not isinstance(value, str) or not value:
+ return None
+ if len(value) <= limit:
+ return value
+ return value[:limit] if truncate else None
+
+
+def _canonical_text(value: object, limit: int) -> Optional[str]:
+ """Bound an identity string without merging values with a shared prefix."""
+ if not isinstance(value, str) or not value:
+ return None
+ needs_digest = len(value) > limit
+ try:
+ encoded = value.encode("utf-8")
+ except UnicodeEncodeError:
+ # json accepts unpaired surrogates, but utf-8 storage and hashing do not.
+ encoded = value.encode("utf-8", errors = "surrogatepass")
+ value = value.encode("utf-8", errors = "backslashreplace").decode("utf-8")
+ needs_digest = True
+ if not needs_digest:
+ return value
+ digest = hashlib.blake2s(encoded, digest_size = 16).hexdigest()
+ return f"{value[: limit - len(digest) - 1]}~{digest}"
+
+
+def canonical_api_subject(subject: object) -> str:
+ """Stable database/cache key for an authenticated subject."""
+ return _canonical_text(subject, MAX_SUBJECT_CHARS) or ""
+
+
+def canonical_api_model(model: object) -> str:
+ """Stable bounded model key that keeps long shared prefixes distinct."""
+ return _canonical_text(model or "default", MAX_MODEL_CHARS) or "default"
+
+
+def _is_busy_error(exc: sqlite3.OperationalError) -> bool:
+ message = str(exc).lower()
+ return "locked" in message or "busy" in message
+
+
+def _sleep_after_busy(delay: float) -> None:
+ time.sleep(delay)
+
+
+def _insert_api_usage(receipt: ApiUsageReceipt) -> bool:
+ receipt_id = _bounded_text(receipt.id, MAX_RECEIPT_ID_CHARS, truncate = False)
+ subject = canonical_api_subject(receipt.subject)
+ endpoint = _bounded_text(receipt.endpoint, MAX_ENDPOINT_CHARS, truncate = True)
+ model = canonical_api_model(receipt.model)
+ status = _bounded_text(receipt.status, MAX_STATUS_CHARS, truncate = True)
+ if receipt_id is None or not subject or endpoint is None or not model or status is None:
+ return False
+
+ conn = get_connection(busy_timeout_seconds = _WRITE_BUSY_TIMEOUT_SECONDS)
+ try:
+ cursor = conn.execute(
+ """
+ INSERT OR IGNORE INTO api_usage_events
+ (id, subject, endpoint, model, status,
+ prompt_tokens, completion_tokens, total_tokens, created_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
+ """,
+ (
+ receipt_id,
+ subject,
+ endpoint,
+ model,
+ status,
+ receipt.prompt_tokens,
+ receipt.completion_tokens,
+ receipt.total_tokens,
+ receipt.created_at,
+ ),
+ )
+ conn.commit()
+ return cursor.rowcount == 1
+ finally:
+ conn.close()
+
+
+def record_api_usage(receipt: ApiUsageReceipt) -> bool:
+ """Insert one external request receipt, returning whether a row was added.
+
+ The monitor id is the idempotency key, so repeated completion notification
+ cannot inflate profile totals. Invalid or zero-usage receipts are ignored.
+ """
+ if receipt.kind != "request" or receipt.via_api_key is not True:
+ return False
+ counts = (receipt.prompt_tokens, receipt.completion_tokens, receipt.total_tokens)
+ if not all(_valid_token_count(value) for value in counts) or not any(counts):
+ return False
+ if (
+ not isinstance(receipt.created_at, int)
+ or isinstance(receipt.created_at, bool)
+ or receipt.created_at <= 0
+ or receipt.created_at > (1 << 63) - 1
+ ):
+ return False
+
+ for attempt in range(_WRITE_RETRIES):
+ try:
+ inserted = _insert_api_usage(receipt)
+ break
+ except sqlite3.OperationalError as exc:
+ if not _is_busy_error(exc) or attempt + 1 == _WRITE_RETRIES:
+ raise
+ # The worker is the only production writer of these receipts. A
+ # short bounded backoff lets unrelated Studio transactions finish
+ # without ever holding up the inference/streaming caller.
+ _sleep_after_busy(min(0.01 * (2**attempt), _WORKER_BUSY_RETRY_SECONDS))
+
+ if inserted:
+ # Lazy import avoids making profile aggregation part of schema startup.
+ from storage.profile_stats_db import invalidate_profile_stats_cache
+ invalidate_profile_stats_cache()
+ return inserted
+
+
+_STOP = object()
+
+
+class ApiUsageWriter:
+ """One serialized background writer for terminal API usage receipts."""
+
+ def __init__(self, sink: Callable[[ApiUsageReceipt], bool] = record_api_usage):
+ self._sink = sink
+ self._queue: queue.Queue[object] = queue.Queue()
+ self._thread = threading.Thread(
+ target = self._run,
+ name = "api-usage-writer",
+ daemon = True,
+ )
+ self._state_lock = threading.Lock()
+ self._stopped = False
+ self._thread.start()
+
+ def submit(self, receipt: ApiUsageReceipt) -> bool:
+ """Enqueue without waiting for SQLite or running caller-controlled code."""
+ with self._state_lock:
+ if self._stopped:
+ return False
+ self._queue.put_nowait(receipt)
+ return True
+
+ def stop(self, timeout: float = _WORKER_DRAIN_TIMEOUT_SECONDS) -> bool:
+ """Stop accepting receipts and wait boundedly for the queue to drain.
+
+ Returns ``True`` once the daemon consumed the stop sentinel. On timeout,
+ the daemon keeps retrying the already accepted head receipt and exits
+ after it succeeds and drains the remaining queue.
+ """
+ with self._state_lock:
+ if not self._stopped:
+ self._stopped = True
+ self._queue.put_nowait(_STOP)
+ # Production calls this through asyncio.to_thread so even the bounded
+ # wait cannot pause inference or the event loop.
+ self._thread.join(timeout = max(0.0, timeout))
+ drained = not self._thread.is_alive()
+ if not drained:
+ logger.warning(
+ "api usage writer drain timed out after %.1f seconds; the daemon will keep "
+ "retrying accepted receipts, which may be lost if the process exits before "
+ "SQLite becomes writable",
+ timeout,
+ )
+ return drained
+
+ def _run(self) -> None:
+ while True:
+ item = self._queue.get()
+ try:
+ if item is _STOP:
+ return
+ busy_failures = 0
+ while True:
+ try:
+ self._sink(item) # type: ignore[arg-type]
+ break
+ except sqlite3.OperationalError as exc:
+ if not _is_busy_error(exc):
+ logger.warning("api usage receipt persistence failed", exc_info = True)
+ break
+ # record_api_usage already made its bounded fast retries.
+ # Retain this accepted item at the head of the single
+ # writer until a normal long Studio transaction releases
+ # SQLite. The stop sentinel remains behind it, so final
+ # shutdown drains rather than silently dropping usage.
+ busy_failures += 1
+ if busy_failures == 1 or busy_failures % 20 == 0:
+ logger.warning(
+ "api usage database remains busy; retaining receipt for retry"
+ )
+ _sleep_after_busy(_WORKER_BUSY_RETRY_SECONDS)
+ except Exception: # noqa: BLE001 - usage accounting cannot break inference.
+ logger.warning("api usage receipt persistence failed", exc_info = True)
+ break
+ finally:
+ self._queue.task_done()
+
+
+_writer_condition = threading.Condition()
+_writer: Optional[ApiUsageWriter] = None
+_writer_leases: set[str] = set()
+_writer_stopping = False
+
+
+def acquire_api_usage_writer() -> str:
+ """Lease the process writer; overlapping app lifespans share one worker."""
+ global _writer
+ lease = uuid.uuid4().hex
+ with _writer_condition:
+ while _writer_stopping:
+ _writer_condition.wait()
+ if _writer is None:
+ _writer = ApiUsageWriter()
+ _writer_leases.add(lease)
+ return lease
+
+
+def enqueue_api_usage(receipt: ApiUsageReceipt) -> None:
+ """Fast production monitor callback; it performs no database I/O."""
+ with _writer_condition:
+ if _writer is not None:
+ _writer.submit(receipt)
+
+
+def release_api_usage_writer(lease: str) -> None:
+ """Release one lifespan and boundedly drain after the last owner exits.
+
+ A timed-out daemon retains its accepted queue, but the global gate is always
+ cleared so a successor lifespan can start a fresh writer.
+ """
+ global _writer, _writer_stopping
+ writer = None
+ with _writer_condition:
+ _writer_leases.discard(lease)
+ if not _writer_leases and _writer is not None and not _writer_stopping:
+ writer = _writer
+ _writer_stopping = True
+ if writer is not None:
+ try:
+ writer.stop()
+ finally:
+ with _writer_condition:
+ if _writer is writer:
+ _writer = None
+ _writer_stopping = False
+ _writer_condition.notify_all()
diff --git a/studio/backend/storage/profile_stats_db.py b/studio/backend/storage/profile_stats_db.py
index 61d0e7b6394..d56b302d867 100644
--- a/studio/backend/storage/profile_stats_db.py
+++ b/studio/backend/storage/profile_stats_db.py
@@ -4,15 +4,18 @@
"""
Profile usage statistics derived from studio.db.
-Read-only aggregation over rows the app already writes: chat threads/messages
-(with their per-message ``metadata_json``) and training runs/metrics. Nothing
-is recorded specifically for stats, so the numbers are only as complete as the
-local history.
+Read-only aggregation over chat threads/messages (with their per-message
+``metadata_json``), content-free API usage receipts, and training runs/metrics.
+The numbers are only as complete as the local history retained after each
+feature was introduced.
+
+Chat and training tables predate authenticated subjects and therefore remain
+install-wide. API usage receipts are filtered to the requesting subject.
Token counts live inside each message's metadata blob, so they cannot be summed
in SQL portably (JSON1 is not guaranteed on every bundled SQLite). Rows are
streamed once in (thread, time) order and every metric is folded in that single
-pass, then memoised against a (count, max created_at) fingerprint so reopening
+pass, then memoised against per-source count/timestamp fingerprints so reopening
the Profile tab is free until history changes.
"""
@@ -25,6 +28,7 @@ from typing import Any, Optional
from loggers import get_logger
+from storage.api_usage_db import canonical_api_subject
from storage.studio_db import count_chat_message_attachments, get_connection
logger = get_logger(__name__)
@@ -193,6 +197,72 @@ class _MessageFold:
bucket["threads"].add(thread_id)
+class _ApiUsageFold:
+ """Scalar-only API receipts folded separately from chat-only metrics."""
+
+ def __init__(self) -> None:
+ self.prompt_tokens = 0
+ self.completion_tokens = 0
+ self.total_tokens = 0
+ self.by_day: dict[date, int] = {}
+ self.models: dict[str, dict[str, Any]] = {}
+ self.requests = 0
+
+
+def _fold_api_usage(conn, zone, subject: str) -> _ApiUsageFold:
+ fold = _ApiUsageFold()
+ rows = conn.execute(
+ """
+ SELECT model, prompt_tokens, completion_tokens, total_tokens, created_at
+ FROM api_usage_events
+ WHERE subject = ?
+ ORDER BY created_at
+ """,
+ (subject,),
+ )
+ for row in rows:
+ prompt_tokens = _as_int(row["prompt_tokens"])
+ completion_tokens = _as_int(row["completion_tokens"])
+ total_tokens = _as_int(row["total_tokens"])
+ fold.prompt_tokens += prompt_tokens
+ fold.completion_tokens += completion_tokens
+ # Preserve the provider's authoritative total even when it differs
+ # from the input/output sum.
+ fold.total_tokens += total_tokens
+ fold.requests += 1
+
+ stamp = _local_stamp(_as_int(row["created_at"]), zone)
+ if stamp is not None:
+ day = stamp.date()
+ fold.by_day[day] = fold.by_day.get(day, 0) + total_tokens
+
+ model_id = _clean_str(row["model"])
+ if model_id:
+ model = fold.models.setdefault(
+ model_id,
+ {"id": model_id, "label": _model_label(model_id), "messages": 0, "tokens": 0},
+ )
+ # One terminal API request represents one model response in the
+ # combined leaderboard.
+ model["messages"] += 1
+ model["tokens"] += total_tokens
+ return fold
+
+
+def _merge_api_activity(chat: _MessageFold, api: _ApiUsageFold) -> None:
+ """Merge only combined activity surfaces, leaving chat counters intact."""
+ for day, tokens in api.by_day.items():
+ bucket = chat.by_day.setdefault(day, {"tokens": 0, "messages": 0, "threads": set()})
+ bucket["tokens"] += tokens
+ for model_id, api_model in api.models.items():
+ model = chat.models.setdefault(
+ model_id,
+ {"id": model_id, "label": api_model["label"], "messages": 0, "tokens": 0},
+ )
+ model["messages"] += api_model["messages"]
+ model["tokens"] += api_model["tokens"]
+
+
def _fork_keepers(conn) -> dict[tuple[str, int, str], str]:
"""For each original message, the one clone elected to stand in for it.
@@ -548,30 +618,54 @@ def _training_stats(conn) -> dict[str, Any]:
}
-def _fingerprint(conn) -> tuple:
+def _fingerprint(conn, subject: str) -> tuple:
message_row = conn.execute(
"SELECT COUNT(*), COALESCE(MAX(created_at), 0) FROM chat_messages"
).fetchone()
run_row = conn.execute(
"SELECT COUNT(*), COALESCE(MAX(started_at), '') FROM training_runs"
).fetchone()
- return (message_row[0], message_row[1], run_row[0], run_row[1])
+ api_row = conn.execute(
+ """
+ SELECT COUNT(*), COALESCE(MAX(created_at), 0)
+ FROM api_usage_events
+ WHERE subject = ?
+ """,
+ (subject,),
+ ).fetchone()
+ return (
+ message_row[0],
+ message_row[1],
+ run_row[0],
+ run_row[1],
+ subject,
+ api_row[0],
+ api_row[1],
+ )
def compute_profile_stats(
days: int = MAX_DAILY_DAYS,
tz_offset_minutes: int = 0,
tz_name: str = "",
+ *,
+ subject: str = "",
) -> dict[str, Any]:
- """Aggregate every profile statistic in one pass, memoised per history state."""
+ """Aggregate profile statistics, subject-scoping only external API usage.
+
+ Legacy Studio chat and training history is install-wide because those rows
+ have no authenticated owner. An empty subject intentionally sees no API
+ receipts, keeping non-route callers fail-closed.
+ """
days = max(1, min(int(days), MAX_DAILY_DAYS))
tz_offset_minutes = max(
-MAX_TZ_OFFSET_MINUTES, min(int(tz_offset_minutes), MAX_TZ_OFFSET_MINUTES)
)
zone = _resolve_zone(tz_name, tz_offset_minutes)
+ subject = canonical_api_subject(subject)
conn = get_connection()
try:
- fingerprint = (_fingerprint(conn), days, tz_offset_minutes, tz_name)
+ fingerprint = (_fingerprint(conn, subject), days, tz_offset_minutes, tz_name)
now = time.monotonic()
with _cache_lock:
if (
@@ -583,6 +677,8 @@ def compute_profile_stats(
started = time.perf_counter()
fold = _fold_messages(conn, zone)
+ api_fold = _fold_api_usage(conn, zone, subject)
+ _merge_api_activity(fold, api_fold)
training = _training_stats(conn)
# "Today" has to match the buckets above, or the newest column and the
@@ -609,9 +705,15 @@ def compute_profile_stats(
"messages": fold.messages,
"userMessages": fold.user_messages,
"assistantMessages": fold.assistant_messages,
- "promptTokens": fold.prompt_tokens,
- "completionTokens": fold.completion_tokens,
- "totalTokens": fold.total_tokens,
+ "promptTokens": fold.prompt_tokens + api_fold.prompt_tokens,
+ "completionTokens": fold.completion_tokens + api_fold.completion_tokens,
+ "totalTokens": fold.total_tokens + api_fold.total_tokens,
+ "chatPromptTokens": fold.prompt_tokens,
+ "chatCompletionTokens": fold.completion_tokens,
+ "chatTokens": fold.total_tokens,
+ "apiPromptTokens": api_fold.prompt_tokens,
+ "apiCompletionTokens": api_fold.completion_tokens,
+ "apiTokens": api_fold.total_tokens,
"cachedTokens": fold.cached_tokens,
"toolCalls": fold.tool_calls,
"attachments": fold.attachments,
@@ -656,9 +758,10 @@ def compute_profile_stats(
}
logger.debug(
- "profile stats computed in %.1f ms (%d messages)",
+ "profile stats computed in %.1f ms (%d messages, %d API requests)",
(time.perf_counter() - started) * 1000,
fold.messages,
+ api_fold.requests,
)
with _cache_lock:
diff --git a/studio/backend/storage/studio_db.py b/studio/backend/storage/studio_db.py
index 632cb68bc45..e2b30c5d56c 100644
--- a/studio/backend/storage/studio_db.py
+++ b/studio/backend/storage/studio_db.py
@@ -320,6 +320,29 @@ def _ensure_schema(conn: sqlite3.Connection) -> None:
"""
)
conn.execute("CREATE INDEX IF NOT EXISTS idx_metrics_run_id ON training_metrics(run_id)")
+ conn.execute(
+ """
+ CREATE TABLE IF NOT EXISTS api_usage_events (
+ id TEXT NOT NULL PRIMARY KEY,
+ subject TEXT NOT NULL,
+ endpoint TEXT NOT NULL,
+ model TEXT NOT NULL,
+ status TEXT NOT NULL,
+ prompt_tokens INTEGER NOT NULL,
+ completion_tokens INTEGER NOT NULL,
+ total_tokens INTEGER NOT NULL,
+ created_at INTEGER NOT NULL
+ ) WITHOUT ROWID
+ """
+ )
+ conn.execute(
+ "CREATE INDEX IF NOT EXISTS idx_api_usage_events_created_at "
+ "ON api_usage_events(created_at)"
+ )
+ conn.execute(
+ "CREATE INDEX IF NOT EXISTS idx_api_usage_events_subject_created_at "
+ "ON api_usage_events(subject, created_at)"
+ )
# Windows: COLLATE NOCASE so C:\Models and c:\models dedup; elsewhere BINARY keeps them distinct.
collation = "COLLATE NOCASE" if platform.system() == "Windows" else ""
conn.execute(
diff --git a/studio/backend/tests/test_api_monitor.py b/studio/backend/tests/test_api_monitor.py
index 4af25c222b6..e3bbb99897e 100644
--- a/studio/backend/tests/test_api_monitor.py
+++ b/studio/backend/tests/test_api_monitor.py
@@ -3,6 +3,8 @@
import itertools
import json
+import logging
+from dataclasses import FrozenInstanceError
import pytest
from fastapi import FastAPI
@@ -13,6 +15,192 @@ from core.inference.api_monitor import ApiMonitor, _trim
import routes.inference as inference_route
+def test_terminal_api_usage_receipt_is_immutable_and_emitted_once():
+ receipts = []
+ monitor = ApiMonitor(terminal_callback = receipts.append)
+ entry_id = monitor.start(
+ endpoint = "/v1/chat/completions",
+ method = "POST",
+ model = "org/model",
+ prompt = "do not persist this",
+ subject = "alice",
+ via_api_key = True,
+ )
+ monitor.set_usage(entry_id, prompt_tokens = 40, completion_tokens = 10, total_tokens = 50)
+ monitor.finish(entry_id)
+ monitor.finish(entry_id)
+ monitor.fail(entry_id, "late error")
+ monitor.set_usage(entry_id, total_tokens = 999)
+
+ assert len(receipts) == 1
+ receipt = receipts[0]
+ assert (receipt.prompt_tokens, receipt.completion_tokens, receipt.total_tokens) == (40, 10, 50)
+ assert receipt.status == "completed"
+ assert not hasattr(receipt, "prompt")
+ assert not hasattr(receipt, "reply")
+ with pytest.raises(FrozenInstanceError):
+ receipt.total_tokens = 999
+
+
+ "terminal,status",
+ [
+ (lambda monitor, entry_id: monitor.finish(entry_id, "cancelled"), "cancelled"),
+ (lambda monitor, entry_id: monitor.fail(entry_id, "boom"), "error"),
+ (lambda monitor, entry_id: monitor.fail_open(entry_id, "boom"), "error"),
+ ],
+)
+def test_partial_terminal_api_usage_is_emitted_once(terminal, status):
+ receipts = []
+ monitor = ApiMonitor(terminal_callback = receipts.append)
+ entry_id = monitor.start(
+ endpoint = "/v1/responses",
+ method = "POST",
+ model = "m",
+ prompt = "private",
+ subject = "alice",
+ via_api_key = True,
+ )
+ monitor.set_usage(entry_id, completion_tokens = 7)
+ terminal(monitor, entry_id)
+ terminal(monitor, entry_id)
+ assert len(receipts) == 1
+ assert receipts[0].status == status
+ assert receipts[0].total_tokens == 7
+
+
+def test_terminal_callback_runs_outside_monitor_lock():
+ lock_was_free = []
+ monitor = ApiMonitor()
+
+ def callback(_receipt):
+ acquired = monitor._lock.acquire(blocking = False)
+ lock_was_free.append(acquired)
+ if acquired:
+ monitor._lock.release()
+ assert monitor.snapshot()
+
+ monitor.set_terminal_callback(callback)
+ entry_id = monitor.start(
+ endpoint = "/v1/messages",
+ method = "POST",
+ model = "m",
+ prompt = "private",
+ subject = "alice",
+ via_api_key = True,
+ )
+ monitor.set_usage(entry_id, total_tokens = 1)
+ monitor.finish(entry_id)
+ assert lock_was_free == [True]
+
+
+def test_terminal_callback_failure_is_logged_and_swallowed(caplog):
+ def broken(_receipt):
+ raise RuntimeError("storage unavailable")
+
+ monitor = ApiMonitor(terminal_callback = broken)
+ entry_id = monitor.start(
+ endpoint = "/v1/completions",
+ method = "POST",
+ model = "m",
+ prompt = "private",
+ subject = "alice",
+ via_api_key = True,
+ )
+ monitor.set_usage(entry_id, total_tokens = 1)
+ with caplog.at_level(logging.WARNING):
+ monitor.finish(entry_id)
+ assert monitor.get(entry_id)["status"] == "completed"
+ assert "api_monitor.terminal_callback_failed" in caplog.text
+
+
+def test_overlapping_callback_leases_do_not_disable_the_live_owner():
+ monitor = ApiMonitor()
+ older_receipts = []
+ newer_receipts = []
+ older = monitor.acquire_terminal_callback(older_receipts.append)
+ newer = monitor.acquire_terminal_callback(newer_receipts.append)
+
+ # Lifespan A exits while the later lifespan B remains live.
+ monitor.release_terminal_callback(older)
+ entry_id = monitor.start(
+ endpoint = "/v1/responses",
+ method = "POST",
+ model = "m",
+ prompt = "private",
+ subject = "alice",
+ via_api_key = True,
+ )
+ monitor.set_usage(entry_id, total_tokens = 1)
+ monitor.finish(entry_id)
+
+ assert older_receipts == []
+ assert len(newer_receipts) == 1
+ monitor.release_terminal_callback(newer)
+
+
+def test_request_ids_keep_the_full_uuid(monkeypatch):
+ full_hex = "0123456789ab" + "cdef" * 5
+ monkeypatch.setattr(
+ "core.inference.api_monitor.uuid.uuid4",
+ lambda: type("FakeUuid", (), {"hex": full_hex})(),
+ )
+ monitor = ApiMonitor()
+
+ entry_id = monitor.start(endpoint = "/v1", method = "POST", model = "m", prompt = "")
+ lifecycle_id = monitor.record_lifecycle(event = "unload", model = "m")
+
+ assert entry_id == f"apireq_{full_hex}"
+ assert lifecycle_id == f"apievt_{full_hex[:12]}"
+
+
+def test_non_external_and_non_request_rows_never_emit_usage_receipts():
+ receipts = []
+ monitor = ApiMonitor(terminal_callback = receipts.append)
+
+ studio = monitor.start(
+ endpoint = "/v1/chat/completions",
+ method = "POST",
+ model = "m",
+ prompt = "studio",
+ subject = "alice",
+ via_api_key = False,
+ )
+ monitor.set_usage(studio, total_tokens = 10)
+ monitor.finish(studio)
+
+ anonymous = monitor.start(
+ endpoint = "/v1/chat/completions",
+ method = "POST",
+ model = "m",
+ prompt = "anonymous",
+ via_api_key = True,
+ )
+ monitor.set_usage(anonymous, total_tokens = 10)
+ monitor.finish(anonymous)
+
+ lifecycle = monitor.record_lifecycle(
+ event = "load", model = "m", running = True, subject = "alice", via_api_key = True
+ )
+ monitor.finish(lifecycle)
+ monitor.record_lifecycle(event = "unload", model = "m", subject = "alice", via_api_key = True)
+
+ discarded = monitor.start(
+ endpoint = "/v1/responses",
+ method = "POST",
+ model = "m",
+ prompt = "private",
+ subject = "alice",
+ via_api_key = True,
+ )
+ monitor.discard(discarded)
+ monitor.finish(discarded)
+
+ disabled = ApiMonitor(enabled = False, terminal_callback = receipts.append)
+ assert disabled.start(endpoint = "/v1", method = "POST", model = "m", prompt = "") == ""
+ assert receipts == []
+
+
def _get_monitor(monkeypatch, *, enabled: bool):
"""Call GET /monitor against a monitor in a known state.
diff --git a/studio/backend/tests/test_api_profile_usage_routes.py b/studio/backend/tests/test_api_profile_usage_routes.py
new file mode 100644
index 00000000000..b3ee05638f1
--- /dev/null
+++ b/studio/backend/tests/test_api_profile_usage_routes.py
@@ -0,0 +1,77 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Route attribution contract for durable Profile API usage receipts."""
+
+import ast
+import inspect
+import textwrap
+from pathlib import Path
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from auth.authentication import get_current_subject
+import routes.inference as inference_route
+import routes.profile_stats as profile_stats_route
+
+
+def _monitor_start_keywords(function) -> list[set[str]]:
+ tree = ast.parse(textwrap.dedent(inspect.getsource(function)))
+ calls: list[set[str]] = []
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.Call) or not isinstance(node.func, ast.Attribute):
+ continue
+ owner = node.func.value
+ if isinstance(owner, ast.Name) and owner.id == "api_monitor" and node.func.attr == "start":
+ calls.append({keyword.arg for keyword in node.keywords if keyword.arg is not None})
+ return calls
+
+
+ "function",
+ [
+ inference_route.openai_chat_completions,
+ inference_route._responses_non_streaming,
+ inference_route.openai_responses,
+ inference_route.anthropic_messages,
+ inference_route.openai_completions,
+ inference_route.openai_embeddings,
+ ],
+)
+def test_every_profile_tracked_route_preserves_external_identity(function):
+ starts = _monitor_start_keywords(function)
+ assert starts, f"{function.__name__} must create a monitor request row"
+ for keywords in starts:
+ assert "via_api_key" in keywords
+ assert "subject" in keywords
+
+
+def test_production_lifespan_installs_and_removes_the_usage_sink():
+ source = (Path(__file__).resolve().parents[1] / "main.py").read_text(encoding = "utf-8")
+ assert "_api_monitor.acquire_terminal_callback(_enqueue_api_usage)" in source
+ assert "_api_monitor.release_terminal_callback(_api_usage_callback_lease)" in source
+ assert "await asyncio.to_thread(_release_api_usage_writer" in source
+
+
+def test_profile_endpoint_forwards_each_authenticated_subject(monkeypatch):
+ seen: list[str] = []
+
+ def fake_stats(**kwargs):
+ seen.append(kwargs["subject"])
+ return {"subject": kwargs["subject"]}
+
+ monkeypatch.setattr(profile_stats_route, "compute_profile_stats", fake_stats)
+ active = {"subject": "alice"}
+ app = FastAPI()
+ app.include_router(profile_stats_route.router, prefix = "/api/profile")
+ app.dependency_overrides = {
+ get_current_subject: lambda: active["subject"],
+ }
+ client = TestClient(app)
+
+ assert client.get("/api/profile/stats").json() == {"subject": "alice"}
+ active["subject"] = "bob"
+ assert client.get("/api/profile/stats").json() == {"subject": "bob"}
+ assert seen == ["alice", "bob"]
diff --git a/studio/backend/tests/test_openai_tool_passthrough.py b/studio/backend/tests/test_openai_tool_passthrough.py
index 9af6cce87bf..3aa30f97f80 100644
--- a/studio/backend/tests/test_openai_tool_passthrough.py
+++ b/studio/backend/tests/test_openai_tool_passthrough.py
@@ -4213,7 +4213,10 @@ class TestApiMonitorProviderAndCompletionStreams:
async def is_disconnected(self):
return False
- async def fake_send(*_args, **_kwargs):
+ upstream_bodies = []
+
+ async def fake_send(_client, built_request, *_args, **_kwargs):
+ upstream_bodies.append(json.loads(built_request.content))
return httpx.Response(200, content = b"")
async def fake_items(*_args, **_kwargs):
@@ -4260,7 +4263,12 @@ class TestApiMonitorProviderAndCompletionStreams:
monitor_id = monitor_id,
)
chunks = [chunk async for chunk in response.body_iterator]
- return SimpleNamespace(chunks = chunks, body = "".join(chunks), monitor = monitor)
+ return SimpleNamespace(
+ chunks = chunks,
+ body = "".join(chunks),
+ monitor = monitor,
+ upstream_bodies = upstream_bodies,
+ )
def test_passthrough_stream_preheader_dispatched_with_timeout(self, monkeypatch):
async def _run():
@@ -5237,6 +5245,62 @@ class TestApiMonitorProviderAndCompletionStreams:
asyncio.run(_run())
+ def test_completions_stream_requests_usage_only_for_monitor(self, monkeypatch):
+ async def _run():
+ import routes.inference as inf_mod
+
+ class Request:
+ state = SimpleNamespace()
+ url = SimpleNamespace(path = "/v1/completions")
+ method = "POST"
+
+ async def json(self):
+ return {"prompt": "hi", "stream": True}
+
+ async def is_disconnected(self):
+ return False
+
+ upstream_bodies = []
+
+ async def fake_send(_client, built_request, *_args, **_kwargs):
+ upstream_bodies.append(json.loads(built_request.content))
+ return httpx.Response(200, content = b"")
+
+ async def fake_items(*_args, **_kwargs):
+ yield (
+ b'data: {"choices":[{"text":"ok","finish_reason":"stop"}]}\n\n'
+ b'data: {"choices":[],"usage":{"prompt_tokens":3,'
+ b'"completion_tokens":2,"total_tokens":5}}\n\n'
+ b"data: [DONE]\n\n"
+ )
+
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
+ monkeypatch.setattr(
+ inf_mod,
+ "get_llama_cpp_backend",
+ lambda: SimpleNamespace(
+ is_loaded = True,
+ base_url = "http://llama.test",
+ context_length = 4096,
+ model_identifier = "gguf",
+ ),
+ )
+ monkeypatch.setattr(inf_mod, "_send_stream_with_preheader_cancel", fake_send)
+ monkeypatch.setattr(inf_mod, "_aiter_llama_stream_items", fake_items)
+
+ response = await openai_completions(Request(), current_subject = "test")
+ body = b"".join([chunk async for chunk in response.body_iterator])
+
+ assert upstream_bodies[0]["stream_options"]["include_usage"] is True
+ assert b'"usage"' not in body
+ [entry] = monitor.snapshot()
+ assert entry["prompt_tokens"] == 3
+ assert entry["completion_tokens"] == 2
+ assert entry["total_tokens"] == 5
+
+ asyncio.run(_run())
+
def test_completions_non_streaming_post_error_finalizes_monitor(self, monkeypatch):
async def _run():
import routes.inference as inf_mod
@@ -6047,6 +6111,26 @@ class TestApiMonitorProviderAndCompletionStreams:
asyncio.run(_run())
+ def test_passthrough_requests_usage_for_monitor_without_exposing_it(self, monkeypatch):
+ async def _run():
+ result = await self._run_passthrough_stream(
+ monkeypatch,
+ [
+ 'data: {"id":"chatcmpl-test","choices":[{"index":0,"delta":{"content":"ok"},"finish_reason":null}]}',
+ 'data: {"id":"chatcmpl-test","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}',
+ 'data: {"id":"chatcmpl-test","choices":[],"usage":{"prompt_tokens":3,"completion_tokens":2,"total_tokens":5}}',
+ ],
+ )
+
+ assert result.upstream_bodies[0]["stream_options"]["include_usage"] is True
+ assert '"usage"' not in result.body
+ [entry] = result.monitor.snapshot()
+ assert entry["prompt_tokens"] == 3
+ assert entry["completion_tokens"] == 2
+ assert entry["total_tokens"] == 5
+
+ asyncio.run(_run())
+
def test_passthrough_stream_queued_request_sends_keepalive_before_upstream(self, monkeypatch):
async def _run():
import routes.inference as inf_mod
@@ -6826,10 +6910,16 @@ class TestApiMonitorProviderAndCompletionStreams:
async def fake_send(*_args, **_kwargs):
return httpx.Response(200, content = b"")
- async def fake_items(*_args, **_kwargs):
+ async def fake_items(
+ *_args,
+ post_first_item_read_timeout_s = None,
+ **_kwargs,
+ ):
yield 'data: {"choices":[{"index":0,"delta":{"content":"hi"},"finish_reason":null}]}'
yield 'data: {"choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}'
- await asyncio.Event().wait() # upstream never closes
+ timeout = post_first_item_read_timeout_s()
+ await asyncio.sleep(timeout)
+ raise httpx.ReadTimeout("upstream never closed")
monitor = ApiMonitor(max_entries = 3)
monkeypatch.setattr(inf_mod, "api_monitor", monitor)
diff --git a/studio/backend/tests/test_passthrough_healing.py b/studio/backend/tests/test_passthrough_healing.py
index 5a018399145..5d6efdbdc0a 100644
--- a/studio/backend/tests/test_passthrough_healing.py
+++ b/studio/backend/tests/test_passthrough_healing.py
@@ -489,6 +489,7 @@ def _upstream_message(
content,
tool_calls = None,
finish_reason = "stop",
+ usage = None,
):
message = {"role": "assistant", "content": content}
if tool_calls is not None:
@@ -499,7 +500,7 @@ def _upstream_message(
"created": 1,
"model": "gguf",
"choices": [{"index": 0, "message": message, "finish_reason": finish_reason}],
- "usage": {"prompt_tokens": 1, "completion_tokens": 2, "total_tokens": 3},
+ "usage": usage or {"prompt_tokens": 1, "completion_tokens": 2, "total_tokens": 3},
}
@@ -804,6 +805,49 @@ class TestNudgeRetryOpenai:
asyncio.run(_run())
+ def test_retry_usage_includes_both_generation_attempts(self, monkeypatch):
+ async def _run():
+ import routes.inference as inf_mod
+
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
+ monitor_id = monitor.start(
+ endpoint = "/v1/chat/completions",
+ method = "POST",
+ model = "gguf",
+ prompt = "hi",
+ )
+ first = _upstream_message(
+ GARBAGE_SIGNAL,
+ usage = {"prompt_tokens": 7, "completion_tokens": 3, "total_tokens": 10},
+ )
+ retry = _upstream_message(
+ LOOKUP_XML,
+ usage = {"prompt_tokens": 20, "completion_tokens": 5, "total_tokens": 25},
+ )
+ client = ScriptedClient([first, retry])
+ monkeypatch.setattr(inf_mod, "nonstreaming_client", lambda: client)
+
+ response = await _openai_passthrough_non_streaming(
+ _llama_backend(),
+ _payload(nudge_tool_calls = True),
+ "gguf",
+ monitor_id = monitor_id,
+ )
+ data = json.loads(response.body)
+
+ assert data["usage"] == {
+ "prompt_tokens": 20,
+ "completion_tokens": 8,
+ "total_tokens": 28,
+ }
+ [entry] = monitor.snapshot()
+ assert entry["prompt_tokens"] == 20
+ assert entry["completion_tokens"] == 8
+ assert entry["total_tokens"] == 28
+
+ asyncio.run(_run())
+
def test_retry_still_garbage_returns_original(self, monkeypatch):
async def _run():
client, data = await _drive_non_streaming(
@@ -901,6 +945,29 @@ class TestNudgeRetryAnthropic:
asyncio.run(_run())
+ def test_discarded_retry_usage_still_counts_generated_tokens(self, monkeypatch):
+ async def _run():
+ first = _upstream_message(
+ GARBAGE_SIGNAL,
+ usage = {"prompt_tokens": 7, "completion_tokens": 3, "total_tokens": 10},
+ )
+ retry = _upstream_message(
+ GARBAGE_SIGNAL + "2",
+ usage = {"prompt_tokens": 20, "completion_tokens": 5, "total_tokens": 25},
+ )
+ client, data = await self._drive(
+ monkeypatch,
+ [first, retry],
+ nudge = True,
+ )
+
+ assert len(client.posts) == 2
+ assert data["content"][0]["text"] == GARBAGE_SIGNAL
+ assert data["usage"]["input_tokens"] == 20
+ assert data["usage"]["output_tokens"] == 8
+
+ asyncio.run(_run())
+
def test_healed_tool_use_precedes_trailing_text(self, monkeypatch):
async def _run():
_, data = await self._drive(monkeypatch, [_upstream_message(f"{LOOKUP_XML} done")])
diff --git a/studio/backend/tests/test_profile_stats.py b/studio/backend/tests/test_profile_stats.py
index d08553948ee..8eca314eacf 100644
--- a/studio/backend/tests/test_profile_stats.py
+++ b/studio/backend/tests/test_profile_stats.py
@@ -4,12 +4,30 @@
"""Profile statistics aggregation over local chat/training history."""
import json
+import sqlite3
+import threading
import time
from datetime import datetime, timedelta, timezone
+from types import SimpleNamespace
import pytest
-from storage import profile_stats_db, studio_db
+from storage import api_usage_db, profile_stats_db, studio_db
+from core.inference.api_monitor import ApiMonitor
+import core.inference.api_monitor as api_monitor_module
+from storage.api_usage_db import (
+ MAX_ENDPOINT_CHARS,
+ MAX_MODEL_CHARS,
+ MAX_RECEIPT_ID_CHARS,
+ MAX_STATUS_CHARS,
+ MAX_SUBJECT_CHARS,
+ ApiUsageReceipt,
+ ApiUsageWriter,
+ acquire_api_usage_writer,
+ enqueue_api_usage,
+ record_api_usage,
+ release_api_usage_writer,
+)
from storage.profile_stats_db import compute_profile_stats, invalidate_profile_stats_cache
@@ -28,6 +46,32 @@ def stats_db(tmp_path, monkeypatch):
REPLY_DELAY = timedelta(seconds = 10)
+def _api_receipt(
+ receipt_id: str,
+ when: datetime,
+ *,
+ prompt: int = 40,
+ completion: int = 10,
+ total: int = 50,
+ model: str = "unsloth/api-model",
+ status: str = "completed",
+ via_api_key: bool = True,
+ subject: str = "external-client",
+) -> ApiUsageReceipt:
+ return ApiUsageReceipt(
+ id = receipt_id,
+ subject = subject,
+ endpoint = "/v1/chat/completions",
+ model = model,
+ status = status,
+ prompt_tokens = prompt,
+ completion_tokens = completion,
+ total_tokens = total,
+ created_at = _ms(when),
+ via_api_key = via_api_key,
+ )
+
+
def _ms(when: datetime) -> int:
return int(when.timestamp() * 1000)
@@ -98,6 +142,8 @@ def test_empty_history_returns_zeroed_payload(stats_db):
assert stats["totals"]["messages"] == 0
assert stats["totals"]["totalTokens"] == 0
+ assert stats["totals"]["chatTokens"] == 0
+ assert stats["totals"]["apiTokens"] == 0
assert stats["streak"] == {"current": 0, "longest": 0, "lastActiveDay": None}
assert stats["peakDay"] is None
assert stats["longestChat"] is None
@@ -105,6 +151,509 @@ def test_empty_history_returns_zeroed_payload(stats_db):
assert all(day["tokens"] == 0 for day in stats["daily"])
+def test_mixed_chat_and_api_usage_combines_only_activity_metrics(stats_db):
+ today = datetime.now(timezone.utc).replace(hour = 12, minute = 0, second = 0, microsecond = 0)
+ conn = studio_db.get_connection()
+ try:
+ _seed_thread(
+ conn,
+ "mixed",
+ "unused-thread-model",
+ [(today, _metadata(100, 25))],
+ )
+ conn.commit()
+ finally:
+ conn.close()
+
+ assert record_api_usage(_api_receipt("api-mixed", today, model = "unsloth/gpt-oss-20b"))
+ stats = compute_profile_stats(days = 7, tz_name = "UTC", subject = "external-client")
+ totals = stats["totals"]
+
+ assert totals["promptTokens"] == 140
+ assert totals["completionTokens"] == 35
+ assert totals["totalTokens"] == 175
+ assert totals["chatPromptTokens"] == 100
+ assert totals["chatCompletionTokens"] == 25
+ assert totals["chatTokens"] == 125
+ assert totals["apiPromptTokens"] == 40
+ assert totals["apiCompletionTokens"] == 10
+ assert totals["apiTokens"] == 50
+ # API requests do not inflate the chat-only counters.
+ assert totals["threads"] == 1
+ assert totals["messages"] == 2
+ assert totals["cachedTokens"] == 5
+ assert stats["daily"][-1] == {
+ "date": today.date().isoformat(),
+ "tokens": 175,
+ "messages": 2,
+ "chats": 1,
+ }
+ assert stats["peakDay"] == {"date": today.date().isoformat(), "tokens": 175}
+ assert stats["models"][0]["id"] == "unsloth/gpt-oss-20b"
+ assert stats["models"][0]["messages"] == 2
+ assert stats["models"][0]["tokens"] == 175
+
+
+def test_api_usage_and_cache_are_subject_scoped_while_legacy_chat_is_shared(stats_db):
+ now = datetime.now(timezone.utc).replace(microsecond = 0)
+ conn = studio_db.get_connection()
+ try:
+ _seed_thread(conn, "shared-chat", "unused", [(now, _metadata(10, 5))])
+ conn.commit()
+ finally:
+ conn.close()
+
+ assert record_api_usage(
+ _api_receipt("alice-api", now, total = 11, prompt = 7, completion = 4, subject = "alice")
+ )
+ assert record_api_usage(
+ _api_receipt("bob-api", now, total = 23, prompt = 20, completion = 3, subject = "bob")
+ )
+
+ alice = compute_profile_stats(days = 1, tz_name = "UTC", subject = "alice")
+ bob = compute_profile_stats(days = 1, tz_name = "UTC", subject = "bob")
+
+ # Chat tables have no subject column and remain install-wide for compatibility.
+ assert alice["totals"]["chatTokens"] == bob["totals"]["chatTokens"] == 15
+ assert alice["totals"]["apiTokens"] == 11
+ assert bob["totals"]["apiTokens"] == 23
+ assert alice["totals"]["totalTokens"] == 26
+ assert bob["totals"]["totalTokens"] == 38
+ # Both subjects deliberately have the same count/max-time fingerprint;
+ # distinct payloads prove the cache key includes identity.
+ assert alice is not bob
+
+
+def test_api_only_usage_is_durable_idempotent_and_invalidates_cache(stats_db):
+ now = datetime.now(timezone.utc).replace(microsecond = 0)
+ initial = compute_profile_stats(days = 7, tz_name = "UTC", subject = "external-client")
+ receipt = _api_receipt("api-only", now)
+
+ assert record_api_usage(receipt) is True
+ assert record_api_usage(receipt) is False
+ after_insert = compute_profile_stats(days = 7, tz_name = "UTC", subject = "external-client")
+ assert after_insert is not initial
+ assert after_insert["totals"]["messages"] == 0
+ assert after_insert["totals"]["apiTokens"] == 50
+ assert after_insert["totals"]["totalTokens"] == 50
+ assert after_insert["models"][0]["id"] == "unsloth/api-model"
+ assert after_insert["streak"]["current"] == 1
+
+ # A fresh process/schema initialization still reads the same receipt.
+ studio_db._schema_ready = False
+ invalidate_profile_stats_cache()
+ after_restart = compute_profile_stats(days = 7, tz_name = "UTC", subject = "external-client")
+ assert after_restart["totals"]["apiTokens"] == 50
+ assert after_restart["daily"][-1]["tokens"] == 50
+
+
+def test_terminal_callback_returns_promptly_while_locked_db_eventually_persists(stats_db):
+ # Initialize the additive schema before taking the writer lock.
+ lock_conn = studio_db.get_connection()
+ callback_lease = None
+ writer_lease = acquire_api_usage_writer()
+ monitor = ApiMonitor()
+ try:
+ lock_conn.execute("BEGIN IMMEDIATE")
+ callback_lease = monitor.acquire_terminal_callback(enqueue_api_usage)
+ entry_id = monitor.start(
+ endpoint = "/v1/responses",
+ method = "POST",
+ model = "m",
+ prompt = "private",
+ subject = "alice",
+ via_api_key = True,
+ )
+ monitor.set_usage(entry_id, prompt_tokens = 2, completion_tokens = 3, total_tokens = 5)
+
+ started = time.perf_counter()
+ monitor.finish(entry_id)
+ elapsed = time.perf_counter() - started
+ assert elapsed < 0.2
+ assert (
+ lock_conn.execute(
+ "SELECT COUNT(*) FROM api_usage_events WHERE id = ?", (entry_id,)
+ ).fetchone()[0]
+ == 0
+ )
+
+ lock_conn.rollback()
+ deadline = time.monotonic() + 5
+ row = None
+ while time.monotonic() < deadline:
+ check = studio_db.get_connection()
+ try:
+ row = check.execute(
+ "SELECT total_tokens FROM api_usage_events WHERE id = ?", (entry_id,)
+ ).fetchone()
+ finally:
+ check.close()
+ if row is not None:
+ break
+ time.sleep(0.02)
+ assert row is not None
+ assert row[0] == 5
+ finally:
+ if lock_conn.in_transaction:
+ lock_conn.rollback()
+ lock_conn.close()
+ if callback_lease is not None:
+ monitor.release_terminal_callback(callback_lease)
+ release_api_usage_writer(writer_lease)
+
+
+def test_writer_stop_drains_accepted_receipts_and_rejects_late_submit():
+ entered = threading.Event()
+ release = threading.Event()
+ persisted = []
+
+ def blocking_sink(receipt):
+ entered.set()
+ release.wait(timeout = 2)
+ persisted.append(receipt.id)
+ return True
+
+ writer = ApiUsageWriter(sink = blocking_sink)
+ first = _api_receipt("accepted-before-stop", datetime.now(timezone.utc))
+ late = _api_receipt("late-after-stop", datetime.now(timezone.utc))
+ assert writer.submit(first)
+ assert entered.wait(timeout = 1)
+
+ stopper = threading.Thread(target = writer.stop)
+ stopper.start()
+ try:
+ deadline = time.monotonic() + 1
+ while not writer._stopped and time.monotonic() < deadline:
+ time.sleep(0.001)
+ assert writer._stopped
+ assert not writer.submit(late)
+ assert stopper.is_alive()
+ finally:
+ release.set()
+ stopper.join(timeout = 2)
+ assert not stopper.is_alive()
+ assert persisted == ["accepted-before-stop"]
+
+
+def test_writer_retains_busy_receipt_after_inner_retry_budget(stats_db, monkeypatch):
+ attempts = 0
+ persisted = []
+
+ def busy_then_success(receipt):
+ nonlocal attempts
+ attempts += 1
+ if attempts <= api_usage_db._WRITE_RETRIES + 2:
+ raise sqlite3.OperationalError("database is locked")
+ persisted.append(receipt.id)
+ return True
+
+ # Exercise all inner record_api_usage retries plus another worker-level
+ # retry without paying the production backoff in this focused unit test.
+ monkeypatch.setattr(api_usage_db, "_insert_api_usage", busy_then_success)
+ monkeypatch.setattr(api_usage_db, "_sleep_after_busy", lambda _delay: None)
+ writer = ApiUsageWriter()
+ receipt = _api_receipt("busy-past-inner-budget", datetime.now(timezone.utc))
+
+ assert writer.submit(receipt)
+ writer.stop()
+
+ assert attempts == api_usage_db._WRITE_RETRIES + 3
+ assert persisted == [receipt.id]
+
+
+def test_writer_busy_shutdown_is_bounded_then_drains_after_unlock(monkeypatch, caplog):
+ entered = threading.Event()
+ unlocked = threading.Event()
+ persisted = []
+
+ def locked_sink(receipt):
+ entered.set()
+ if not unlocked.is_set():
+ raise sqlite3.OperationalError("database is locked")
+ persisted.append(receipt.id)
+ return True
+
+ # Keep the retry responsive without a hot spin in the test process.
+ monkeypatch.setattr(
+ api_usage_db,
+ "_sleep_after_busy",
+ lambda _delay: unlocked.wait(timeout = 0.01),
+ )
+ writer = ApiUsageWriter(sink = locked_sink)
+ receipt = _api_receipt("busy-through-shutdown", datetime.now(timezone.utc))
+ assert writer.submit(receipt)
+ assert entered.wait(timeout = 1)
+
+ try:
+ started = time.perf_counter()
+ assert writer.stop(timeout = 0.03) is False
+ elapsed = time.perf_counter() - started
+ assert elapsed < 0.2
+ assert not writer.submit(_api_receipt("rejected-after-stop", datetime.now(timezone.utc)))
+ assert writer._thread.is_alive()
+ assert "may be lost if the process exits" in caplog.text
+ finally:
+ unlocked.set()
+ writer._thread.join(timeout = 1)
+ assert not writer._thread.is_alive()
+ assert writer.stop(timeout = 0) is True
+ assert persisted == [receipt.id]
+
+
+def test_timed_out_writer_release_allows_successor_lifespan(monkeypatch):
+ created = []
+
+ class TimedOutWriter:
+ def __init__(self):
+ self.stopped = False
+ created.append(self)
+
+ def submit(self, _receipt):
+ return not self.stopped
+
+ def stop(self):
+ self.stopped = True
+ return False
+
+ monkeypatch.setattr(api_usage_db, "ApiUsageWriter", TimedOutWriter)
+ first_lease = acquire_api_usage_writer()
+ release_api_usage_writer(first_lease)
+ assert api_usage_db._writer is None
+ assert api_usage_db._writer_stopping is False
+
+ second_lease = acquire_api_usage_writer()
+ try:
+ assert len(created) == 2
+ assert created[0] is not created[1]
+ finally:
+ release_api_usage_writer(second_lease)
+
+
+def test_full_uuid_request_ids_do_not_collapse_same_prefix(stats_db, monkeypatch):
+ uuid_hexes = iter(
+ [
+ "0123456789ab00000000000000000001",
+ "0123456789abffffffffffffffffffff",
+ ]
+ )
+ monkeypatch.setattr(
+ api_monitor_module.uuid,
+ "uuid4",
+ lambda: SimpleNamespace(hex = next(uuid_hexes)),
+ )
+ monitor = ApiMonitor(max_entries = 0, terminal_callback = record_api_usage)
+ ids = []
+ for total in (3, 7):
+ entry_id = monitor.start(
+ endpoint = "/v1/messages",
+ method = "POST",
+ model = "m",
+ prompt = "private",
+ subject = "alice",
+ via_api_key = True,
+ )
+ ids.append(entry_id)
+ monitor.set_usage(entry_id, total_tokens = total)
+ monitor.finish(entry_id)
+
+ assert ids[0] != ids[1]
+ assert ids[0][:19] == ids[1][:19]
+ conn = studio_db.get_connection()
+ try:
+ rows = conn.execute(
+ "SELECT id, total_tokens FROM api_usage_events ORDER BY total_tokens"
+ ).fetchall()
+ finally:
+ conn.close()
+ assert [(row["id"], row["total_tokens"]) for row in rows] == [(ids[0], 3), (ids[1], 7)]
+
+
+def test_terminal_receipt_canonicalizes_unpaired_model_surrogate():
+ receipts = []
+ monitor = ApiMonitor(terminal_callback = receipts.append)
+ entry_id = monitor.start(
+ endpoint = "/v1/chat/completions",
+ method = "POST",
+ model = "\ud800" + "m" * MAX_MODEL_CHARS,
+ prompt = "private",
+ subject = "alice",
+ via_api_key = True,
+ )
+ monitor.set_usage(entry_id, total_tokens = 1)
+
+ monitor.finish(entry_id)
+
+ assert len(receipts) == 1
+ assert len(receipts[0].model) == MAX_MODEL_CHARS
+ receipts[0].model.encode("utf-8")
+
+
+def test_api_usage_bounds_every_durable_text_field(stats_db):
+ now = datetime.now(timezone.utc)
+ long_model_prefix = "m" * (MAX_MODEL_CHARS + 100)
+ receipt = ApiUsageReceipt(
+ id = "i" * MAX_RECEIPT_ID_CHARS,
+ subject = "s" * MAX_SUBJECT_CHARS,
+ endpoint = "e" * (MAX_ENDPOINT_CHARS + 100),
+ model = long_model_prefix + "a",
+ status = "x" * (MAX_STATUS_CHARS + 100),
+ prompt_tokens = 1,
+ completion_tokens = 2,
+ total_tokens = 3,
+ created_at = _ms(now),
+ )
+ assert record_api_usage(receipt)
+ assert not record_api_usage(_api_receipt("i" * (MAX_RECEIPT_ID_CHARS + 1), now))
+ long_subject = "s" * (MAX_SUBJECT_CHARS + 100)
+ assert record_api_usage(_api_receipt("oversized-subject", now, subject = long_subject))
+ assert record_api_usage(_api_receipt("second-long-model", now, model = long_model_prefix + "b"))
+
+ conn = studio_db.get_connection()
+ try:
+ row = conn.execute(
+ "SELECT id, subject, endpoint, model, status FROM api_usage_events WHERE id = ?",
+ (receipt.id,),
+ ).fetchone()
+ other_model = conn.execute(
+ "SELECT model FROM api_usage_events WHERE id = 'second-long-model'"
+ ).fetchone()[0]
+ stored_long_subject = conn.execute(
+ "SELECT subject FROM api_usage_events WHERE id = 'oversized-subject'"
+ ).fetchone()[0]
+ finally:
+ conn.close()
+ assert len(row["id"]) == MAX_RECEIPT_ID_CHARS
+ assert len(row["subject"]) == MAX_SUBJECT_CHARS
+ assert len(row["endpoint"]) == MAX_ENDPOINT_CHARS
+ assert len(row["model"]) == MAX_MODEL_CHARS
+ assert len(row["status"]) == MAX_STATUS_CHARS
+ assert len(stored_long_subject) == MAX_SUBJECT_CHARS
+ assert row["model"] != other_model
+ assert (
+ compute_profile_stats(days = 1, tz_name = "UTC", subject = long_subject)["totals"]["apiTokens"]
+ == 50
+ )
+
+
+def test_api_fingerprint_invalidates_cache_for_independent_database_writers(stats_db):
+ now = datetime.now(timezone.utc)
+ cached = compute_profile_stats(days = 1, tz_name = "UTC", subject = "alice")
+ conn = studio_db.get_connection()
+ try:
+ conn.execute(
+ """
+ INSERT INTO api_usage_events
+ (id, subject, endpoint, model, status,
+ prompt_tokens, completion_tokens, total_tokens, created_at)
+ VALUES ('external-writer', 'alice', '/v1/responses', 'm',
+ 'completed', 4, 6, 10, ?)
+ """,
+ (_ms(now),),
+ )
+ conn.commit()
+ finally:
+ conn.close()
+
+ refreshed = compute_profile_stats(days = 1, tz_name = "UTC", subject = "alice")
+ assert refreshed is not cached
+ assert refreshed["totals"]["apiTokens"] == 10
+
+
+def test_api_usage_filters_internal_and_zero_receipts_but_keeps_partial_failures(stats_db):
+ now = datetime.now(timezone.utc)
+ assert record_api_usage(_api_receipt("internal", now, via_api_key = False)) is False
+ assert (
+ record_api_usage(_api_receipt("zero", now, prompt = 0, completion = 0, total = 0, status = "error"))
+ is False
+ )
+ assert (
+ record_api_usage(
+ _api_receipt(
+ "partial",
+ now,
+ prompt = 3,
+ completion = 4,
+ total = 9,
+ status = "cancelled",
+ )
+ )
+ is True
+ )
+
+ stats = compute_profile_stats(days = 1, tz_name = "UTC", subject = "external-client")
+ assert stats["totals"]["apiPromptTokens"] == 3
+ assert stats["totals"]["apiCompletionTokens"] == 4
+ # The authoritative total is retained instead of recomputing 3 + 4.
+ assert stats["totals"]["apiTokens"] == 9
+ conn = studio_db.get_connection()
+ try:
+ columns = {row[1] for row in conn.execute("PRAGMA table_info(api_usage_events)")}
+ assert "prompt" not in columns
+ assert "reply" not in columns
+ assert "api_key" not in columns
+ finally:
+ conn.close()
+
+
+def test_api_usage_uses_iana_timezone_across_dst_dates(stats_db):
+ winter = datetime(2026, 1, 15, 4, 30, tzinfo = timezone.utc)
+ summer = datetime(2026, 7, 15, 3, 30, tzinfo = timezone.utc)
+ assert record_api_usage(_api_receipt("winter", winter, total = 11))
+ assert record_api_usage(_api_receipt("summer", summer, total = 13))
+
+ stats = compute_profile_stats(
+ days = 366,
+ tz_name = "America/New_York",
+ subject = "external-client",
+ )
+ by_date = {day["date"]: day["tokens"] for day in stats["daily"]}
+ # Both UTC instants are before local midnight using the date-specific
+ # standard/daylight offset.
+ assert by_date["2026-01-14"] == 11
+ assert by_date["2026-07-14"] == 13
+
+
+def test_existing_database_gets_additive_api_usage_schema(stats_db):
+ db_path = studio_db.studio_db_path()
+ db_path.parent.mkdir(parents = True, exist_ok = True)
+ legacy = sqlite3.connect(db_path)
+ try:
+ legacy.execute("CREATE TABLE legacy_marker (value TEXT)")
+ legacy.execute("INSERT INTO legacy_marker VALUES ('kept')")
+ legacy.commit()
+ finally:
+ legacy.close()
+
+ studio_db._schema_ready = False
+ conn = studio_db.get_connection()
+ try:
+ assert conn.execute("SELECT value FROM legacy_marker").fetchone()[0] == "kept"
+ assert conn.execute(
+ "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'api_usage_events'"
+ ).fetchone()
+ finally:
+ conn.close()
+
+
+ "query",
+ [
+ "SELECT created_at FROM api_usage_events WHERE subject = ? ORDER BY created_at",
+ "SELECT COUNT(*), MAX(created_at) FROM api_usage_events WHERE subject = ?",
+ ],
+)
+def test_api_usage_subject_queries_use_composite_index(stats_db, query):
+ conn = studio_db.get_connection()
+ try:
+ plan = conn.execute(f"EXPLAIN QUERY PLAN {query}", ("alice",)).fetchall()
+ finally:
+ conn.close()
+
+ detail = " ".join(str(row["detail"]) for row in plan)
+ assert "SEARCH" in detail
+ assert "idx_api_usage_events_subject_created_at" in detail
+
+
def test_tokens_streaks_and_models_are_aggregated(stats_db):
today = datetime.now().replace(hour = 12, minute = 0, second = 0, microsecond = 0)
conn = studio_db.get_connection()
@@ -859,6 +1408,7 @@ def test_route_does_not_block_the_event_loop(stats_db, monkeypatch):
days = 366,
tz_offset_minutes = 0,
tz_name = "",
+ subject = "",
):
time.sleep(0.5)
return {"totals": {"messages": 0}}
diff --git a/studio/backend/tests/test_research_internal_key_monitor.py b/studio/backend/tests/test_research_internal_key_monitor.py
index 843b48f520d..9f21b2af488 100644
--- a/studio/backend/tests/test_research_internal_key_monitor.py
+++ b/studio/backend/tests/test_research_internal_key_monitor.py
@@ -63,9 +63,9 @@ def test_unknown_key_is_treated_as_third_party():
assert _request_used_api_key(_Request("Bearer sk-unsloth-deadbeefdeadbeef")) is True
-def test_probe_failure_keeps_the_row_attributed(monkeypatch):
+def test_probe_failure_suppresses_external_api_attribution(monkeypatch):
def explode(_raw_key):
raise RuntimeError("database is locked")
monkeypatch.setattr(auth_storage, "is_internal_api_key", explode)
- assert _request_used_api_key(_Request("Bearer sk-unsloth-deadbeefdeadbeef")) is True
+ assert _request_used_api_key(_Request("Bearer sk-unsloth-deadbeefdeadbeef")) is False
diff --git a/studio/frontend/src/features/profile/api/profile-stats.ts b/studio/frontend/src/features/profile/api/profile-stats.ts
index 7f3211232d5..aed44b71126 100644
--- a/studio/frontend/src/features/profile/api/profile-stats.ts
+++ b/studio/frontend/src/features/profile/api/profile-stats.ts
@@ -42,6 +42,12 @@ export type ProfileStats = {
promptTokens: number;
completionTokens: number;
totalTokens: number;
+ chatPromptTokens: number;
+ chatCompletionTokens: number;
+ chatTokens: number;
+ apiPromptTokens: number;
+ apiCompletionTokens: number;
+ apiTokens: number;
cachedTokens: number;
toolCalls: number;
attachments: number;
diff --git a/studio/frontend/src/features/profile/components/stats/insights-card.tsx b/studio/frontend/src/features/profile/components/stats/insights-card.tsx
index 9c2c29f0c77..c5d1f30957c 100644
--- a/studio/frontend/src/features/profile/components/stats/insights-card.tsx
+++ b/studio/frontend/src/features/profile/components/stats/insights-card.tsx
@@ -18,9 +18,11 @@ export function ActivityInsightsCard({ stats }: { stats: ProfileStats }) {
const locale = useLocale();
const { totals, speed } = stats;
const averageTokensPerChat =
- totals.threads > 0 ? totals.totalTokens / totals.threads : 0;
+ totals.threads > 0 ? totals.chatTokens / totals.threads : 0;
const cacheShare =
- totals.promptTokens > 0 ? totals.cachedTokens / totals.promptTokens : 0;
+ totals.chatPromptTokens > 0
+ ? totals.cachedTokens / totals.chatPromptTokens
+ : 0;
return (
<StatsCard title={t("settings.profile.stats.insightsTitle")}>
@@ -41,6 +43,18 @@ export function ActivityInsightsCard({ stats }: { stats: ProfileStats }) {
label={t("settings.profile.stats.tokensOut")}
value={formatCompactNumber(totals.completionTokens, locale)}
/>
+ <StatRow
+ label={t("settings.profile.stats.totalTokens")}
+ value={formatCompactNumber(totals.totalTokens, locale)}
+ />
+ <StatRow
+ label={t("settings.profile.stats.studioChatTokens")}
+ value={formatCompactNumber(totals.chatTokens, locale)}
+ />
+ <StatRow
+ label={t("settings.profile.stats.apiTokens")}
+ value={formatCompactNumber(totals.apiTokens, locale)}
+ />
<StatRow
label={t("settings.profile.stats.cachedTokens")}
value={
diff --git a/studio/frontend/src/features/profile/components/stats/profile-stats-content.tsx b/studio/frontend/src/features/profile/components/stats/profile-stats-content.tsx
index 29c93810302..7ce0a56f354 100644
--- a/studio/frontend/src/features/profile/components/stats/profile-stats-content.tsx
+++ b/studio/frontend/src/features/profile/components/stats/profile-stats-content.tsx
@@ -43,7 +43,7 @@ export function ProfileStatsContent() {
if (stats === null) return null;
- const hasChats = stats.totals.messages > 0;
+ const hasUsage = stats.totals.messages > 0 || stats.totals.totalTokens > 0;
const hasTraining = stats.training.runs > 0;
return (
@@ -62,7 +62,7 @@ export function ProfileStatsContent() {
<StatsHighlights stats={stats} />
- {hasChats ? (
+ {hasUsage ? (
<>
<TokenActivityCard daily={stats.daily} />
<div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index 6298f4c021a..c30f63aaf01 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -867,9 +867,9 @@ export const ar = {
"كل ما يلي محسوب من سجلك الخاص. لا يُجمَع أي شيء ولا يُرسَل إلى Unsloth.",
retry: "إعادة المحاولة",
privacyNote:
- "تُحسب الإحصاءات من سجل المحادثات والتدريب المحفوظ في نسخة Unsloth لديك. لا يُجمَع أي شيء، ولا يُرسَل شيء إلى Unsloth أو إلى أي طرف ثالث.",
+ "تُحسب الإحصاءات من سجل المحادثات واستخدام API والتدريب المحلي في نسخة Unsloth لديك. لا تُحفظ مطالبات API أو ردوده أو مفاتيحه للإحصاءات، ولا يُرسل شيء إلى Unsloth أو أي طرف ثالث.",
emptyChats:
- "لا توجد محادثات بعد. ابدأ محادثة وستظهر إحصاءاتك هنا.",
+ "لا يوجد استخدام للمحادثات أو API بعد. ابدأ محادثة أو أرسل طلب API محليًا ومصادقًا عليه لتظهر إحصاءاتك هنا.",
lifetimeTokens: "إجمالي التوكنات",
peakTokens: "يوم الذروة",
longestChat: "أطول محادثة",
@@ -891,6 +891,9 @@ export const ar = {
totalMessages: "إجمالي الرسائل",
tokensIn: "التوكنات المُرسَلة",
tokensOut: "التوكنات المُولَّدة",
+ totalTokens: "إجمالي التوكنات",
+ studioChatTokens: "توكنات محادثة Studio",
+ apiTokens: "توكنات API",
cachedTokens: "التوكنات المخزّنة مؤقتًا",
cachedValue: "{tokens} ({percent}% من المُدخَلات)",
avgTokensPerChat: "متوسط التوكنات لكل محادثة",
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index 38296deb414..329be2e0f52 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -891,9 +891,9 @@ export const de = {
"Alles Folgende wird aus Ihrem eigenen Verlauf berechnet. Es wird nichts erfasst oder an Unsloth gesendet.",
retry: "Erneut versuchen",
privacyNote:
- "Die Statistiken werden aus dem Chat- und Trainingsverlauf berechnet, der in Ihrer Unsloth-Installation gespeichert ist. Es wird nichts erfasst und nichts an Unsloth oder Dritte gesendet.",
+ "Die Statistiken werden aus dem lokalen Chat-, API-Nutzungs- und Trainingsverlauf Ihrer Unsloth-Installation berechnet. API-Eingaben, -Antworten und -Schlüssel werden dafür nie gespeichert. Nichts wird an Unsloth oder Dritte gesendet.",
emptyChats:
- "Noch keine Chats. Starten Sie ein Gespräch, dann erscheinen hier Ihre Statistiken.",
+ "Noch keine Chat- oder API-Nutzung. Starten Sie ein Gespräch oder senden Sie eine authentifizierte lokale API-Anfrage.",
lifetimeTokens: "Tokens insgesamt",
peakTokens: "Aktivster Tag",
longestChat: "Längster Chat",
@@ -915,6 +915,9 @@ export const de = {
totalMessages: "Nachrichten insgesamt",
tokensIn: "Gesendete Tokens",
tokensOut: "Erzeugte Tokens",
+ totalTokens: "Tokens insgesamt",
+ studioChatTokens: "Studio-Chat-Tokens",
+ apiTokens: "API-Tokens",
cachedTokens: "Zwischengespeicherte Tokens",
cachedValue: "{tokens} ({percent} % der Eingabe)",
avgTokensPerChat: "Durchschnittliche Tokens pro Chat",
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index 540b8c25f64..b4f60442ea8 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -862,9 +862,9 @@ export const en = {
"Everything below is counted from your own history. Nothing is collected or sent to Unsloth.",
retry: "Try again",
privacyNote:
- "Stats are computed from the chat and training history held by your Unsloth install. Nothing is collected, and nothing is sent to Unsloth or any third party.",
+ "Stats are computed from local chat, API usage, and training history held by your Unsloth install. API prompts, responses, and keys are never stored for stats. Nothing is sent to Unsloth or any third party.",
emptyChats:
- "No chats yet. Start a conversation and your stats will fill in here.",
+ "No chat or API usage yet. Start a conversation or make an authenticated local API request and your stats will fill in here.",
lifetimeTokens: "Lifetime tokens",
peakTokens: "Peak day",
longestChat: "Longest chat",
@@ -886,6 +886,9 @@ export const en = {
totalMessages: "Total messages",
tokensIn: "Tokens sent",
tokensOut: "Tokens generated",
+ totalTokens: "Total tokens",
+ studioChatTokens: "Studio Chat tokens",
+ apiTokens: "API tokens",
cachedTokens: "Cached tokens",
cachedValue: "{tokens} ({percent}% of input)",
avgTokensPerChat: "Average tokens per chat",
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index 7e63b6fcc74..181a1440280 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -886,9 +886,9 @@ export const es = {
"Todo lo que aparece a continuación se calcula a partir de tu propio historial. No se recopila ni se envía nada a Unsloth.",
retry: "Volver a intentar",
privacyNote:
- "Las estadísticas se calculan a partir del historial de chats y entrenamientos que guarda tu instalación de Unsloth. No se recopila nada y no se envía nada a Unsloth ni a terceros.",
+ "Las estadísticas se calculan a partir del historial local de chats, uso de la API y entrenamientos de tu instalación de Unsloth. Nunca se guardan solicitudes, respuestas ni claves de API para las estadísticas. No se envía nada a Unsloth ni a terceros.",
emptyChats:
- "Todavía no hay chats. Empieza una conversación y tus estadísticas aparecerán aquí.",
+ "Todavía no hay uso de chats ni de la API. Empieza una conversación o haz una solicitud autenticada a la API local.",
lifetimeTokens: "Tokens acumulados",
peakTokens: "Día más activo",
longestChat: "Chat más largo",
@@ -910,6 +910,9 @@ export const es = {
totalMessages: "Mensajes totales",
tokensIn: "Tokens enviados",
tokensOut: "Tokens generados",
+ totalTokens: "Tokens totales",
+ studioChatTokens: "Tokens de Studio Chat",
+ apiTokens: "Tokens de la API",
cachedTokens: "Tokens en caché",
cachedValue: "{tokens} ({percent}% de la entrada)",
avgTokensPerChat: "Media de tokens por chat",
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index e19052093b5..0d0f91a7d8f 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -890,9 +890,9 @@ export const fr = {
"Tout ce qui suit est calculé à partir de votre propre historique. Rien n'est collecté ni envoyé à Unsloth.",
retry: "Réessayer",
privacyNote:
- "Les statistiques sont calculées à partir de l'historique des discussions et des entraînements conservé par votre installation Unsloth. Rien n'est collecté, et rien n'est envoyé à Unsloth ni à un tiers.",
+ "Les statistiques sont calculées à partir de l'historique local des discussions, de l'utilisation de l'API et des entraînements de votre installation Unsloth. Les requêtes, réponses et clés API ne sont jamais stockées pour les statistiques. Rien n'est envoyé à Unsloth ni à un tiers.",
emptyChats:
- "Aucune discussion pour le moment. Lancez une conversation et vos statistiques apparaîtront ici.",
+ "Aucune utilisation du chat ou de l'API pour le moment. Lancez une conversation ou effectuez une requête authentifiée vers l'API locale.",
lifetimeTokens: "Tokens cumulés",
peakTokens: "Jour record",
longestChat: "Discussion la plus longue",
@@ -914,6 +914,9 @@ export const fr = {
totalMessages: "Messages au total",
tokensIn: "Tokens envoyés",
tokensOut: "Tokens générés",
+ totalTokens: "Total des tokens",
+ studioChatTokens: "Tokens de Studio Chat",
+ apiTokens: "Tokens API",
cachedTokens: "Tokens mis en cache",
cachedValue: "{tokens} ({percent} % des tokens d'entrée)",
avgTokensPerChat: "Moyenne de tokens par discussion",
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index c30524a9ada..5c78ff6613b 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -870,9 +870,9 @@ export const hi = {
"नीचे सब कुछ आपके अपने इतिहास से गिना जाता है। कुछ भी इकट्ठा नहीं किया जाता और न ही Unsloth को भेजा जाता है।",
retry: "फिर कोशिश करें",
privacyNote:
- "आँकड़े आपके Unsloth इंस्टॉल में मौजूद चैट और ट्रेनिंग इतिहास से गिने जाते हैं। कुछ भी इकट्ठा नहीं किया जाता, और Unsloth या किसी तीसरे पक्ष को कुछ नहीं भेजा जाता।",
+ "आँकड़े आपके Unsloth इंस्टॉल के स्थानीय चैट, API उपयोग और ट्रेनिंग इतिहास से गिने जाते हैं। आँकड़ों के लिए API प्रॉम्प्ट, जवाब या कुंजियाँ कभी संग्रहीत नहीं होतीं। Unsloth या किसी तीसरे पक्ष को कुछ नहीं भेजा जाता।",
emptyChats:
- "अभी तक कोई चैट नहीं। बातचीत शुरू करें और आपके आँकड़े यहाँ दिखने लगेंगे।",
+ "अभी तक चैट या API उपयोग नहीं है। बातचीत शुरू करें या प्रमाणित स्थानीय API अनुरोध करें।",
lifetimeTokens: "अब तक के कुल टोकन",
peakTokens: "सबसे व्यस्त दिन",
longestChat: "सबसे लंबी चैट",
@@ -894,6 +894,9 @@ export const hi = {
totalMessages: "कुल संदेश",
tokensIn: "भेजे गए टोकन",
tokensOut: "बनाए गए टोकन",
+ totalTokens: "कुल टोकन",
+ studioChatTokens: "Studio Chat टोकन",
+ apiTokens: "API टोकन",
cachedTokens: "कैश किए गए टोकन",
cachedValue: "{tokens} (इनपुट का {percent}%)",
avgTokensPerChat: "प्रति चैट औसत टोकन",
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index 56f43493880..3f33a16cfba 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -855,9 +855,9 @@ export const it = {
"Tutto quello che vedi qui è calcolato dalla tua cronologia. Nessun dato viene raccolto o inviato a Unsloth.",
retry: "Riprova",
privacyNote:
- "Le statistiche sono calcolate dalla cronologia di chat e addestramenti presente nella tua installazione di Unsloth. Nessun dato viene raccolto né inviato a Unsloth o a terze parti.",
+ "Le statistiche sono calcolate dalla cronologia locale di chat, utilizzo API e addestramenti della tua installazione di Unsloth. Prompt, risposte e chiavi API non vengono mai salvati per le statistiche. Nulla viene inviato a Unsloth o a terze parti.",
emptyChats:
- "Nessuna chat. Inizia una conversazione e le tue statistiche compariranno qui.",
+ "Nessun utilizzo della chat o dell'API. Inizia una conversazione o invia una richiesta autenticata all'API locale.",
lifetimeTokens: "Token totali",
peakTokens: "Giorno record",
longestChat: "Chat più lunga",
@@ -879,6 +879,9 @@ export const it = {
totalMessages: "Messaggi totali",
tokensIn: "Token inviati",
tokensOut: "Token generati",
+ totalTokens: "Token totali",
+ studioChatTokens: "Token di Studio Chat",
+ apiTokens: "Token API",
cachedTokens: "Token in cache",
cachedValue: "{tokens} ({percent}% dell'input)",
avgTokensPerChat: "Token medi per chat",
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index 0137b08d723..c6b229cd4e4 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -851,9 +851,9 @@ export const ja = {
"以下はすべてご自身の履歴から集計しています。収集も Unsloth への送信も行いません。",
retry: "再試行",
privacyNote:
- "統計は、お使いの Unsloth が保持しているチャットとトレーニングの履歴から計算されます。データの収集は行わず、Unsloth や第三者への送信も行いません。",
+ "統計は、お使いの Unsloth にあるローカルのチャット、API 利用、トレーニング履歴から計算されます。統計用に API のプロンプト、応答、キーを保存することはありません。Unsloth や第三者への送信も行いません。",
emptyChats:
- "チャットがまだありません。会話を始めると、ここに統計が表示されます。",
+ "チャットまたは API の利用履歴がまだありません。会話を始めるか、認証済みのローカル API リクエストを実行してください。",
lifetimeTokens: "累計トークン",
peakTokens: "トークン最多の日",
longestChat: "最長のチャット",
@@ -875,6 +875,9 @@ export const ja = {
totalMessages: "メッセージ総数",
tokensIn: "送信トークン",
tokensOut: "生成トークン",
+ totalTokens: "合計トークン",
+ studioChatTokens: "Studio Chat トークン",
+ apiTokens: "API トークン",
cachedTokens: "キャッシュされたトークン",
cachedValue: "{tokens} (入力の {percent}%)",
avgTokensPerChat: "チャットあたりの平均トークン",
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index 122f14db540..5ea36641a6d 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -864,9 +864,9 @@ export const ko = {
"아래 내용은 모두 본인의 기록을 바탕으로 계산됩니다. 아무것도 수집하거나 Unsloth로 전송하지 않습니다.",
retry: "다시 시도",
privacyNote:
- "통계는 사용 중인 Unsloth에 저장된 채팅 및 학습 기록을 바탕으로 계산됩니다. 아무것도 수집하지 않으며, Unsloth나 제3자에게 전송하지 않습니다.",
+ "통계는 Unsloth 설치에 저장된 로컬 채팅, API 사용 및 학습 기록을 바탕으로 계산됩니다. 통계를 위해 API 프롬프트, 응답 또는 키를 저장하지 않습니다. Unsloth나 제3자에게 아무것도 전송하지 않습니다.",
emptyChats:
- "아직 채팅이 없습니다. 대화를 시작하면 여기에 통계가 채워집니다.",
+ "아직 채팅 또는 API 사용 기록이 없습니다. 대화를 시작하거나 인증된 로컬 API 요청을 보내세요.",
lifetimeTokens: "누적 토큰",
peakTokens: "최고 기록일",
longestChat: "가장 긴 채팅",
@@ -888,6 +888,9 @@ export const ko = {
totalMessages: "전체 메시지",
tokensIn: "보낸 토큰",
tokensOut: "생성된 토큰",
+ totalTokens: "전체 토큰",
+ studioChatTokens: "Studio Chat 토큰",
+ apiTokens: "API 토큰",
cachedTokens: "캐시된 토큰",
cachedValue: "{tokens}(입력의 {percent}%)",
avgTokensPerChat: "채팅당 평균 토큰",
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index 4bc1352689c..86b5f878716 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -878,9 +878,9 @@ export const ptBR = {
"Tudo abaixo é calculado a partir do seu próprio histórico. Nada é coletado nem enviado ao Unsloth.",
retry: "Tentar novamente",
privacyNote:
- "As estatísticas são calculadas a partir do histórico de chats e de treinos guardado pela sua instalação do Unsloth. Nada é coletado e nada é enviado ao Unsloth ou a terceiros.",
+ "As estatísticas são calculadas a partir do histórico local de chats, uso da API e treinos da sua instalação do Unsloth. Prompts, respostas e chaves da API nunca são salvos para as estatísticas. Nada é enviado ao Unsloth ou a terceiros.",
emptyChats:
- "Nenhum chat ainda. Comece uma conversa e suas estatísticas aparecerão aqui.",
+ "Ainda não há uso de chat ou API. Comece uma conversa ou faça uma solicitação autenticada à API local.",
lifetimeTokens: "Tokens acumulados",
peakTokens: "Dia de pico",
longestChat: "Chat mais longo",
@@ -902,6 +902,9 @@ export const ptBR = {
totalMessages: "Total de mensagens",
tokensIn: "Tokens enviados",
tokensOut: "Tokens gerados",
+ totalTokens: "Total de tokens",
+ studioChatTokens: "Tokens do Studio Chat",
+ apiTokens: "Tokens da API",
cachedTokens: "Tokens em cache",
cachedValue: "{tokens} ({percent}% da entrada)",
avgTokensPerChat: "Média de tokens por chat",
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index 01c883a6d4d..b718bf04e1a 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -871,9 +871,9 @@ export const ru = {
"Всё ниже считается по вашей собственной истории. Ничего не собирается и не отправляется в Unsloth.",
retry: "Повторить",
privacyNote:
- "Статистика рассчитывается по истории чатов и обучения, которая хранится в вашей установке Unsloth. Ничего не собирается и ничего не отправляется ни в Unsloth, ни третьим лицам.",
+ "Статистика рассчитывается по локальной истории чатов, использования API и обучения в вашей установке Unsloth. Запросы, ответы и ключи API для статистики никогда не сохраняются. Ничего не отправляется ни в Unsloth, ни третьим лицам.",
emptyChats:
- "Чатов пока нет. Начните разговор, и статистика появится здесь.",
+ "Чатов и использования API пока нет. Начните разговор или выполните аутентифицированный запрос к локальному API.",
lifetimeTokens: "Токенов за всё время",
peakTokens: "Пиковый день",
longestChat: "Самый длинный чат",
@@ -895,6 +895,9 @@ export const ru = {
totalMessages: "Всего сообщений",
tokensIn: "Отправлено токенов",
tokensOut: "Сгенерировано токенов",
+ totalTokens: "Всего токенов",
+ studioChatTokens: "Токены Studio Chat",
+ apiTokens: "Токены API",
cachedTokens: "Токенов из кеша",
cachedValue: "{tokens} ({percent}% ввода)",
avgTokensPerChat: "В среднем токенов на чат",
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index eb7c2fa78ca..418ed0fc86d 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -848,8 +848,8 @@ export const zhCN = {
"下面的内容全部根据你自己的历史记录统计。不会收集任何数据,也不会发送给 Unsloth。",
retry: "重试",
privacyNote:
- "统计数据由你本地 Unsloth 保存的聊天和训练历史计算得出。不收集任何数据,也不会发送给 Unsloth 或任何第三方。",
- emptyChats: "暂无聊天。开始一段对话后,这里就会显示你的统计数据。",
+ "统计数据由本地 Unsloth 的聊天、API 使用和训练历史计算得出。统计功能绝不会保存 API 提示词、回复或密钥,也不会向 Unsloth 或任何第三方发送数据。",
+ emptyChats: "暂无聊天或 API 使用记录。请开始一段对话,或发起经过认证的本地 API 请求。",
lifetimeTokens: "累计 token",
peakTokens: "单日峰值",
longestChat: "最长的聊天",
@@ -871,6 +871,9 @@ export const zhCN = {
totalMessages: "消息总数",
tokensIn: "发送的 token",
tokensOut: "生成的 token",
+ totalTokens: "Token 总数",
+ studioChatTokens: "Studio Chat token",
+ apiTokens: "API token",
cachedTokens: "缓存的 token",
cachedValue: "{tokens}(占输入的 {percent}%)",
avgTokensPerChat: "每个聊天的平均 token",
diff --git a/studio/frontend/tests/profile-api-usage-stats.test.ts b/studio/frontend/tests/profile-api-usage-stats.test.ts
new file mode 100644
index 00000000000..3d342190cc7
--- /dev/null
+++ b/studio/frontend/tests/profile-api-usage-stats.test.ts
@@ -0,0 +1,48 @@
+// 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 assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+import test from "node:test";
+
+const featureRoot = new URL("../src/features/profile/", import.meta.url);
+
+test("profile stats type exposes combined chat and API token breakdowns", async () => {
+ const source = await readFile(
+ new URL("api/profile-stats.ts", featureRoot),
+ "utf8",
+ );
+ for (const field of [
+ "chatPromptTokens",
+ "chatCompletionTokens",
+ "chatTokens",
+ "apiPromptTokens",
+ "apiCompletionTokens",
+ "apiTokens",
+ ]) {
+ assert.match(source, new RegExp(`${field}: number`));
+ }
+});
+
+test("API-only users render activity and the token breakdown stays semantically split", async () => {
+ const [content, insights] = await Promise.all([
+ readFile(
+ new URL("components/stats/profile-stats-content.tsx", featureRoot),
+ "utf8",
+ ),
+ readFile(
+ new URL("components/stats/insights-card.tsx", featureRoot),
+ "utf8",
+ ),
+ ]);
+
+ assert.match(
+ content,
+ /stats\.totals\.messages > 0 \|\| stats\.totals\.totalTokens > 0/,
+ );
+ assert.match(insights, /totals\.chatTokens \/ totals\.threads/);
+ assert.match(insights, /totals\.cachedTokens \/ totals\.chatPromptTokens/);
+ assert.match(insights, /settings\.profile\.stats\.totalTokens/);
+ assert.match(insights, /settings\.profile\.stats\.studioChatTokens/);
+ assert.match(insights, /settings\.profile\.stats\.apiTokens/);
+});